2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/fsnotify.h>
25 #include <linux/pagemap.h>
26 #include <linux/highmem.h>
27 #include <linux/time.h>
28 #include <linux/init.h>
29 #include <linux/string.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mount.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/swap.h>
35 #include <linux/writeback.h>
36 #include <linux/statfs.h>
37 #include <linux/compat.h>
38 #include <linux/bit_spinlock.h>
39 #include <linux/security.h>
40 #include <linux/xattr.h>
41 #include <linux/vmalloc.h>
42 #include <linux/slab.h>
43 #include <linux/blkdev.h>
44 #include <linux/uuid.h>
45 #include <linux/btrfs.h>
46 #include <linux/uaccess.h>
50 #include "transaction.h"
51 #include "btrfs_inode.h"
52 #include "print-tree.h"
55 #include "inode-map.h"
57 #include "rcu-string.h"
59 #include "dev-replace.h"
61 static int btrfs_clone(struct inode *src, struct inode *inode,
62 u64 off, u64 olen, u64 olen_aligned, u64 destoff);
64 /* Mask out flags that are inappropriate for the given type of inode. */
65 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
69 else if (S_ISREG(mode))
70 return flags & ~FS_DIRSYNC_FL;
72 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
76 * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
78 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
80 unsigned int iflags = 0;
82 if (flags & BTRFS_INODE_SYNC)
84 if (flags & BTRFS_INODE_IMMUTABLE)
85 iflags |= FS_IMMUTABLE_FL;
86 if (flags & BTRFS_INODE_APPEND)
87 iflags |= FS_APPEND_FL;
88 if (flags & BTRFS_INODE_NODUMP)
89 iflags |= FS_NODUMP_FL;
90 if (flags & BTRFS_INODE_NOATIME)
91 iflags |= FS_NOATIME_FL;
92 if (flags & BTRFS_INODE_DIRSYNC)
93 iflags |= FS_DIRSYNC_FL;
94 if (flags & BTRFS_INODE_NODATACOW)
95 iflags |= FS_NOCOW_FL;
97 if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
98 iflags |= FS_COMPR_FL;
99 else if (flags & BTRFS_INODE_NOCOMPRESS)
100 iflags |= FS_NOCOMP_FL;
106 * Update inode->i_flags based on the btrfs internal flags.
108 void btrfs_update_iflags(struct inode *inode)
110 struct btrfs_inode *ip = BTRFS_I(inode);
112 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
114 if (ip->flags & BTRFS_INODE_SYNC)
115 inode->i_flags |= S_SYNC;
116 if (ip->flags & BTRFS_INODE_IMMUTABLE)
117 inode->i_flags |= S_IMMUTABLE;
118 if (ip->flags & BTRFS_INODE_APPEND)
119 inode->i_flags |= S_APPEND;
120 if (ip->flags & BTRFS_INODE_NOATIME)
121 inode->i_flags |= S_NOATIME;
122 if (ip->flags & BTRFS_INODE_DIRSYNC)
123 inode->i_flags |= S_DIRSYNC;
127 * Inherit flags from the parent inode.
129 * Currently only the compression flags and the cow flags are inherited.
131 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
138 flags = BTRFS_I(dir)->flags;
140 if (flags & BTRFS_INODE_NOCOMPRESS) {
141 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
142 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
143 } else if (flags & BTRFS_INODE_COMPRESS) {
144 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
145 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
148 if (flags & BTRFS_INODE_NODATACOW) {
149 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
150 if (S_ISREG(inode->i_mode))
151 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
154 btrfs_update_iflags(inode);
157 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
159 struct btrfs_inode *ip = BTRFS_I(file_inode(file));
160 unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
162 if (copy_to_user(arg, &flags, sizeof(flags)))
167 static int check_flags(unsigned int flags)
169 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
170 FS_NOATIME_FL | FS_NODUMP_FL | \
171 FS_SYNC_FL | FS_DIRSYNC_FL | \
172 FS_NOCOMP_FL | FS_COMPR_FL |
176 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
182 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
184 struct inode *inode = file_inode(file);
185 struct btrfs_inode *ip = BTRFS_I(inode);
186 struct btrfs_root *root = ip->root;
187 struct btrfs_trans_handle *trans;
188 unsigned int flags, oldflags;
191 unsigned int i_oldflags;
194 if (btrfs_root_readonly(root))
197 if (copy_from_user(&flags, arg, sizeof(flags)))
200 ret = check_flags(flags);
204 if (!inode_owner_or_capable(inode))
207 ret = mnt_want_write_file(file);
211 mutex_lock(&inode->i_mutex);
213 ip_oldflags = ip->flags;
214 i_oldflags = inode->i_flags;
215 mode = inode->i_mode;
217 flags = btrfs_mask_flags(inode->i_mode, flags);
218 oldflags = btrfs_flags_to_ioctl(ip->flags);
219 if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
220 if (!capable(CAP_LINUX_IMMUTABLE)) {
226 if (flags & FS_SYNC_FL)
227 ip->flags |= BTRFS_INODE_SYNC;
229 ip->flags &= ~BTRFS_INODE_SYNC;
230 if (flags & FS_IMMUTABLE_FL)
231 ip->flags |= BTRFS_INODE_IMMUTABLE;
233 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
234 if (flags & FS_APPEND_FL)
235 ip->flags |= BTRFS_INODE_APPEND;
237 ip->flags &= ~BTRFS_INODE_APPEND;
238 if (flags & FS_NODUMP_FL)
239 ip->flags |= BTRFS_INODE_NODUMP;
241 ip->flags &= ~BTRFS_INODE_NODUMP;
242 if (flags & FS_NOATIME_FL)
243 ip->flags |= BTRFS_INODE_NOATIME;
245 ip->flags &= ~BTRFS_INODE_NOATIME;
246 if (flags & FS_DIRSYNC_FL)
247 ip->flags |= BTRFS_INODE_DIRSYNC;
249 ip->flags &= ~BTRFS_INODE_DIRSYNC;
250 if (flags & FS_NOCOW_FL) {
253 * It's safe to turn csums off here, no extents exist.
254 * Otherwise we want the flag to reflect the real COW
255 * status of the file and will not set it.
257 if (inode->i_size == 0)
258 ip->flags |= BTRFS_INODE_NODATACOW
259 | BTRFS_INODE_NODATASUM;
261 ip->flags |= BTRFS_INODE_NODATACOW;
265 * Revert back under same assuptions as above
268 if (inode->i_size == 0)
269 ip->flags &= ~(BTRFS_INODE_NODATACOW
270 | BTRFS_INODE_NODATASUM);
272 ip->flags &= ~BTRFS_INODE_NODATACOW;
277 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
278 * flag may be changed automatically if compression code won't make
281 if (flags & FS_NOCOMP_FL) {
282 ip->flags &= ~BTRFS_INODE_COMPRESS;
283 ip->flags |= BTRFS_INODE_NOCOMPRESS;
284 } else if (flags & FS_COMPR_FL) {
285 ip->flags |= BTRFS_INODE_COMPRESS;
286 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
288 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
291 trans = btrfs_start_transaction(root, 1);
293 ret = PTR_ERR(trans);
297 btrfs_update_iflags(inode);
298 inode_inc_iversion(inode);
299 inode->i_ctime = CURRENT_TIME;
300 ret = btrfs_update_inode(trans, root, inode);
302 btrfs_end_transaction(trans, root);
305 ip->flags = ip_oldflags;
306 inode->i_flags = i_oldflags;
310 mutex_unlock(&inode->i_mutex);
311 mnt_drop_write_file(file);
315 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
317 struct inode *inode = file_inode(file);
319 return put_user(inode->i_generation, arg);
322 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
324 struct btrfs_fs_info *fs_info = btrfs_sb(fdentry(file)->d_sb);
325 struct btrfs_device *device;
326 struct request_queue *q;
327 struct fstrim_range range;
328 u64 minlen = ULLONG_MAX;
330 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
333 if (!capable(CAP_SYS_ADMIN))
337 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
341 q = bdev_get_queue(device->bdev);
342 if (blk_queue_discard(q)) {
344 minlen = min((u64)q->limits.discard_granularity,
352 if (copy_from_user(&range, arg, sizeof(range)))
354 if (range.start > total_bytes ||
355 range.len < fs_info->sb->s_blocksize)
358 range.len = min(range.len, total_bytes - range.start);
359 range.minlen = max(range.minlen, minlen);
360 ret = btrfs_trim_fs(fs_info->tree_root, &range);
364 if (copy_to_user(arg, &range, sizeof(range)))
370 int btrfs_is_empty_uuid(u8 *uuid)
372 static char empty_uuid[BTRFS_UUID_SIZE] = {0};
374 return !memcmp(uuid, empty_uuid, BTRFS_UUID_SIZE);
377 static noinline int create_subvol(struct inode *dir,
378 struct dentry *dentry,
379 char *name, int namelen,
381 struct btrfs_qgroup_inherit *inherit)
383 struct btrfs_trans_handle *trans;
384 struct btrfs_key key;
385 struct btrfs_root_item root_item;
386 struct btrfs_inode_item *inode_item;
387 struct extent_buffer *leaf;
388 struct btrfs_root *root = BTRFS_I(dir)->root;
389 struct btrfs_root *new_root;
390 struct btrfs_block_rsv block_rsv;
391 struct timespec cur_time = CURRENT_TIME;
395 u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
400 ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
404 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
406 * The same as the snapshot creation, please see the comment
407 * of create_snapshot().
409 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
410 8, &qgroup_reserved, false);
414 trans = btrfs_start_transaction(root, 0);
416 ret = PTR_ERR(trans);
419 trans->block_rsv = &block_rsv;
420 trans->bytes_reserved = block_rsv.size;
422 ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
426 leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
427 0, objectid, NULL, 0, 0, 0);
433 memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
434 btrfs_set_header_bytenr(leaf, leaf->start);
435 btrfs_set_header_generation(leaf, trans->transid);
436 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
437 btrfs_set_header_owner(leaf, objectid);
439 write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
441 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
442 btrfs_header_chunk_tree_uuid(leaf),
444 btrfs_mark_buffer_dirty(leaf);
446 memset(&root_item, 0, sizeof(root_item));
448 inode_item = &root_item.inode;
449 btrfs_set_stack_inode_generation(inode_item, 1);
450 btrfs_set_stack_inode_size(inode_item, 3);
451 btrfs_set_stack_inode_nlink(inode_item, 1);
452 btrfs_set_stack_inode_nbytes(inode_item, root->leafsize);
453 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
455 btrfs_set_root_flags(&root_item, 0);
456 btrfs_set_root_limit(&root_item, 0);
457 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
459 btrfs_set_root_bytenr(&root_item, leaf->start);
460 btrfs_set_root_generation(&root_item, trans->transid);
461 btrfs_set_root_level(&root_item, 0);
462 btrfs_set_root_refs(&root_item, 1);
463 btrfs_set_root_used(&root_item, leaf->len);
464 btrfs_set_root_last_snapshot(&root_item, 0);
466 btrfs_set_root_generation_v2(&root_item,
467 btrfs_root_generation(&root_item));
468 uuid_le_gen(&new_uuid);
469 memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
470 btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
471 btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
472 root_item.ctime = root_item.otime;
473 btrfs_set_root_ctransid(&root_item, trans->transid);
474 btrfs_set_root_otransid(&root_item, trans->transid);
476 btrfs_tree_unlock(leaf);
477 free_extent_buffer(leaf);
480 btrfs_set_root_dirid(&root_item, new_dirid);
482 key.objectid = objectid;
484 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
485 ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
490 key.offset = (u64)-1;
491 new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
492 if (IS_ERR(new_root)) {
493 btrfs_abort_transaction(trans, root, PTR_ERR(new_root));
494 ret = PTR_ERR(new_root);
498 btrfs_record_root_in_trans(trans, new_root);
500 ret = btrfs_create_subvol_root(trans, new_root, new_dirid);
502 /* We potentially lose an unused inode item here */
503 btrfs_abort_transaction(trans, root, ret);
508 * insert the directory item
510 ret = btrfs_set_inode_index(dir, &index);
512 btrfs_abort_transaction(trans, root, ret);
516 ret = btrfs_insert_dir_item(trans, root,
517 name, namelen, dir, &key,
518 BTRFS_FT_DIR, index);
520 btrfs_abort_transaction(trans, root, ret);
524 btrfs_i_size_write(dir, dir->i_size + namelen * 2);
525 ret = btrfs_update_inode(trans, root, dir);
528 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
529 objectid, root->root_key.objectid,
530 btrfs_ino(dir), index, name, namelen);
533 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
534 root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
537 btrfs_abort_transaction(trans, root, ret);
540 trans->block_rsv = NULL;
541 trans->bytes_reserved = 0;
543 *async_transid = trans->transid;
544 err = btrfs_commit_transaction_async(trans, root, 1);
546 err = btrfs_commit_transaction(trans, root);
548 err = btrfs_commit_transaction(trans, root);
554 d_instantiate(dentry, btrfs_lookup_dentry(dir, dentry));
556 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
560 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
561 struct dentry *dentry, char *name, int namelen,
562 u64 *async_transid, bool readonly,
563 struct btrfs_qgroup_inherit *inherit)
566 struct btrfs_pending_snapshot *pending_snapshot;
567 struct btrfs_trans_handle *trans;
573 ret = btrfs_start_delalloc_inodes(root, 0);
577 btrfs_wait_ordered_extents(root);
579 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
580 if (!pending_snapshot)
583 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
584 BTRFS_BLOCK_RSV_TEMP);
586 * 1 - parent dir inode
589 * 2 - root ref/backref
590 * 1 - root of snapshot
593 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
594 &pending_snapshot->block_rsv, 8,
595 &pending_snapshot->qgroup_reserved,
600 pending_snapshot->dentry = dentry;
601 pending_snapshot->root = root;
602 pending_snapshot->readonly = readonly;
603 pending_snapshot->dir = dir;
604 pending_snapshot->inherit = inherit;
606 trans = btrfs_start_transaction(root, 0);
608 ret = PTR_ERR(trans);
612 spin_lock(&root->fs_info->trans_lock);
613 list_add(&pending_snapshot->list,
614 &trans->transaction->pending_snapshots);
615 spin_unlock(&root->fs_info->trans_lock);
617 *async_transid = trans->transid;
618 ret = btrfs_commit_transaction_async(trans,
619 root->fs_info->extent_root, 1);
621 ret = btrfs_commit_transaction(trans, root);
623 ret = btrfs_commit_transaction(trans,
624 root->fs_info->extent_root);
629 ret = pending_snapshot->error;
633 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
637 inode = btrfs_lookup_dentry(dentry->d_parent->d_inode, dentry);
639 ret = PTR_ERR(inode);
643 d_instantiate(dentry, inode);
646 btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
647 &pending_snapshot->block_rsv,
648 pending_snapshot->qgroup_reserved);
650 kfree(pending_snapshot);
654 /* copy of check_sticky in fs/namei.c()
655 * It's inline, so penalty for filesystems that don't use sticky bit is
658 static inline int btrfs_check_sticky(struct inode *dir, struct inode *inode)
660 kuid_t fsuid = current_fsuid();
662 if (!(dir->i_mode & S_ISVTX))
664 if (uid_eq(inode->i_uid, fsuid))
666 if (uid_eq(dir->i_uid, fsuid))
668 return !capable(CAP_FOWNER);
671 /* copy of may_delete in fs/namei.c()
672 * Check whether we can remove a link victim from directory dir, check
673 * whether the type of victim is right.
674 * 1. We can't do it if dir is read-only (done in permission())
675 * 2. We should have write and exec permissions on dir
676 * 3. We can't remove anything from append-only dir
677 * 4. We can't do anything with immutable dir (done in permission())
678 * 5. If the sticky bit on dir is set we should either
679 * a. be owner of dir, or
680 * b. be owner of victim, or
681 * c. have CAP_FOWNER capability
682 * 6. If the victim is append-only or immutable we can't do antyhing with
683 * links pointing to it.
684 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
685 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
686 * 9. We can't remove a root or mountpoint.
687 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
688 * nfs_async_unlink().
691 static int btrfs_may_delete(struct inode *dir,struct dentry *victim,int isdir)
695 if (!victim->d_inode)
698 BUG_ON(victim->d_parent->d_inode != dir);
699 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
701 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
706 if (btrfs_check_sticky(dir, victim->d_inode)||
707 IS_APPEND(victim->d_inode)||
708 IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
711 if (!S_ISDIR(victim->d_inode->i_mode))
715 } else if (S_ISDIR(victim->d_inode->i_mode))
719 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
724 /* copy of may_create in fs/namei.c() */
725 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
731 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
735 * Create a new subvolume below @parent. This is largely modeled after
736 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
737 * inside this filesystem so it's quite a bit simpler.
739 static noinline int btrfs_mksubvol(struct path *parent,
740 char *name, int namelen,
741 struct btrfs_root *snap_src,
742 u64 *async_transid, bool readonly,
743 struct btrfs_qgroup_inherit *inherit)
745 struct inode *dir = parent->dentry->d_inode;
746 struct dentry *dentry;
749 error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
753 dentry = lookup_one_len(name, parent->dentry, namelen);
754 error = PTR_ERR(dentry);
762 error = btrfs_may_create(dir, dentry);
767 * even if this name doesn't exist, we may get hash collisions.
768 * check for them now when we can safely fail
770 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
776 down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
778 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
782 error = create_snapshot(snap_src, dir, dentry, name, namelen,
783 async_transid, readonly, inherit);
785 error = create_subvol(dir, dentry, name, namelen,
786 async_transid, inherit);
789 fsnotify_mkdir(dir, dentry);
791 up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
795 mutex_unlock(&dir->i_mutex);
800 * When we're defragging a range, we don't want to kick it off again
801 * if it is really just waiting for delalloc to send it down.
802 * If we find a nice big extent or delalloc range for the bytes in the
803 * file you want to defrag, we return 0 to let you know to skip this
806 static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh)
808 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
809 struct extent_map *em = NULL;
810 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
813 read_lock(&em_tree->lock);
814 em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
815 read_unlock(&em_tree->lock);
818 end = extent_map_end(em);
820 if (end - offset > thresh)
823 /* if we already have a nice delalloc here, just stop */
825 end = count_range_bits(io_tree, &offset, offset + thresh,
826 thresh, EXTENT_DELALLOC, 1);
833 * helper function to walk through a file and find extents
834 * newer than a specific transid, and smaller than thresh.
836 * This is used by the defragging code to find new and small
839 static int find_new_extents(struct btrfs_root *root,
840 struct inode *inode, u64 newer_than,
841 u64 *off, int thresh)
843 struct btrfs_path *path;
844 struct btrfs_key min_key;
845 struct extent_buffer *leaf;
846 struct btrfs_file_extent_item *extent;
849 u64 ino = btrfs_ino(inode);
851 path = btrfs_alloc_path();
855 min_key.objectid = ino;
856 min_key.type = BTRFS_EXTENT_DATA_KEY;
857 min_key.offset = *off;
859 path->keep_locks = 1;
862 ret = btrfs_search_forward(root, &min_key, path, newer_than);
865 if (min_key.objectid != ino)
867 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
870 leaf = path->nodes[0];
871 extent = btrfs_item_ptr(leaf, path->slots[0],
872 struct btrfs_file_extent_item);
874 type = btrfs_file_extent_type(leaf, extent);
875 if (type == BTRFS_FILE_EXTENT_REG &&
876 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
877 check_defrag_in_cache(inode, min_key.offset, thresh)) {
878 *off = min_key.offset;
879 btrfs_free_path(path);
883 if (min_key.offset == (u64)-1)
887 btrfs_release_path(path);
890 btrfs_free_path(path);
894 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
896 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
897 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
898 struct extent_map *em;
899 u64 len = PAGE_CACHE_SIZE;
902 * hopefully we have this extent in the tree already, try without
903 * the full extent lock
905 read_lock(&em_tree->lock);
906 em = lookup_extent_mapping(em_tree, start, len);
907 read_unlock(&em_tree->lock);
910 /* get the big lock and read metadata off disk */
911 lock_extent(io_tree, start, start + len - 1);
912 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
913 unlock_extent(io_tree, start, start + len - 1);
922 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
924 struct extent_map *next;
927 /* this is the last extent */
928 if (em->start + em->len >= i_size_read(inode))
931 next = defrag_lookup_extent(inode, em->start + em->len);
932 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
935 free_extent_map(next);
939 static int should_defrag_range(struct inode *inode, u64 start, int thresh,
940 u64 *last_len, u64 *skip, u64 *defrag_end,
943 struct extent_map *em;
945 bool next_mergeable = true;
948 * make sure that once we start defragging an extent, we keep on
951 if (start < *defrag_end)
956 em = defrag_lookup_extent(inode, start);
960 /* this will cover holes, and inline extents */
961 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
966 next_mergeable = defrag_check_next_extent(inode, em);
969 * we hit a real extent, if it is big or the next extent is not a
970 * real extent, don't bother defragging it
972 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
973 (em->len >= thresh || !next_mergeable))
977 * last_len ends up being a counter of how many bytes we've defragged.
978 * every time we choose not to defrag an extent, we reset *last_len
979 * so that the next tiny extent will force a defrag.
981 * The end result of this is that tiny extents before a single big
982 * extent will force at least part of that big extent to be defragged.
985 *defrag_end = extent_map_end(em);
988 *skip = extent_map_end(em);
997 * it doesn't do much good to defrag one or two pages
998 * at a time. This pulls in a nice chunk of pages
1001 * It also makes sure the delalloc code has enough
1002 * dirty data to avoid making new small extents as part
1005 * It's a good idea to start RA on this range
1006 * before calling this.
1008 static int cluster_pages_for_defrag(struct inode *inode,
1009 struct page **pages,
1010 unsigned long start_index,
1013 unsigned long file_end;
1014 u64 isize = i_size_read(inode);
1021 struct btrfs_ordered_extent *ordered;
1022 struct extent_state *cached_state = NULL;
1023 struct extent_io_tree *tree;
1024 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1026 file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1027 if (!isize || start_index > file_end)
1030 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1032 ret = btrfs_delalloc_reserve_space(inode,
1033 page_cnt << PAGE_CACHE_SHIFT);
1037 tree = &BTRFS_I(inode)->io_tree;
1039 /* step one, lock all the pages */
1040 for (i = 0; i < page_cnt; i++) {
1043 page = find_or_create_page(inode->i_mapping,
1044 start_index + i, mask);
1048 page_start = page_offset(page);
1049 page_end = page_start + PAGE_CACHE_SIZE - 1;
1051 lock_extent(tree, page_start, page_end);
1052 ordered = btrfs_lookup_ordered_extent(inode,
1054 unlock_extent(tree, page_start, page_end);
1059 btrfs_start_ordered_extent(inode, ordered, 1);
1060 btrfs_put_ordered_extent(ordered);
1063 * we unlocked the page above, so we need check if
1064 * it was released or not.
1066 if (page->mapping != inode->i_mapping) {
1068 page_cache_release(page);
1073 if (!PageUptodate(page)) {
1074 btrfs_readpage(NULL, page);
1076 if (!PageUptodate(page)) {
1078 page_cache_release(page);
1084 if (page->mapping != inode->i_mapping) {
1086 page_cache_release(page);
1096 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1100 * so now we have a nice long stream of locked
1101 * and up to date pages, lets wait on them
1103 for (i = 0; i < i_done; i++)
1104 wait_on_page_writeback(pages[i]);
1106 page_start = page_offset(pages[0]);
1107 page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1109 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1110 page_start, page_end - 1, 0, &cached_state);
1111 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1112 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1113 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1114 &cached_state, GFP_NOFS);
1116 if (i_done != page_cnt) {
1117 spin_lock(&BTRFS_I(inode)->lock);
1118 BTRFS_I(inode)->outstanding_extents++;
1119 spin_unlock(&BTRFS_I(inode)->lock);
1120 btrfs_delalloc_release_space(inode,
1121 (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1125 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1126 &cached_state, GFP_NOFS);
1128 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1129 page_start, page_end - 1, &cached_state,
1132 for (i = 0; i < i_done; i++) {
1133 clear_page_dirty_for_io(pages[i]);
1134 ClearPageChecked(pages[i]);
1135 set_page_extent_mapped(pages[i]);
1136 set_page_dirty(pages[i]);
1137 unlock_page(pages[i]);
1138 page_cache_release(pages[i]);
1142 for (i = 0; i < i_done; i++) {
1143 unlock_page(pages[i]);
1144 page_cache_release(pages[i]);
1146 btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1151 int btrfs_defrag_file(struct inode *inode, struct file *file,
1152 struct btrfs_ioctl_defrag_range_args *range,
1153 u64 newer_than, unsigned long max_to_defrag)
1155 struct btrfs_root *root = BTRFS_I(inode)->root;
1156 struct file_ra_state *ra = NULL;
1157 unsigned long last_index;
1158 u64 isize = i_size_read(inode);
1162 u64 newer_off = range->start;
1164 unsigned long ra_index = 0;
1166 int defrag_count = 0;
1167 int compress_type = BTRFS_COMPRESS_ZLIB;
1168 int extent_thresh = range->extent_thresh;
1169 int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1170 int cluster = max_cluster;
1171 u64 new_align = ~((u64)128 * 1024 - 1);
1172 struct page **pages = NULL;
1177 if (range->start >= isize)
1180 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1181 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1183 if (range->compress_type)
1184 compress_type = range->compress_type;
1187 if (extent_thresh == 0)
1188 extent_thresh = 256 * 1024;
1191 * if we were not given a file, allocate a readahead
1195 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1198 file_ra_state_init(ra, inode->i_mapping);
1203 pages = kmalloc(sizeof(struct page *) * max_cluster,
1210 /* find the last page to defrag */
1211 if (range->start + range->len > range->start) {
1212 last_index = min_t(u64, isize - 1,
1213 range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1215 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1219 ret = find_new_extents(root, inode, newer_than,
1220 &newer_off, 64 * 1024);
1222 range->start = newer_off;
1224 * we always align our defrag to help keep
1225 * the extents in the file evenly spaced
1227 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1231 i = range->start >> PAGE_CACHE_SHIFT;
1234 max_to_defrag = last_index + 1;
1237 * make writeback starts from i, so the defrag range can be
1238 * written sequentially.
1240 if (i < inode->i_mapping->writeback_index)
1241 inode->i_mapping->writeback_index = i;
1243 while (i <= last_index && defrag_count < max_to_defrag &&
1244 (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
1245 PAGE_CACHE_SHIFT)) {
1247 * make sure we stop running if someone unmounts
1250 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1253 if (btrfs_defrag_cancelled(root->fs_info)) {
1254 printk(KERN_DEBUG "btrfs: defrag_file cancelled\n");
1259 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1260 extent_thresh, &last_len, &skip,
1261 &defrag_end, range->flags &
1262 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1265 * the should_defrag function tells us how much to skip
1266 * bump our counter by the suggested amount
1268 next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1269 i = max(i + 1, next);
1274 cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1275 PAGE_CACHE_SHIFT) - i;
1276 cluster = min(cluster, max_cluster);
1278 cluster = max_cluster;
1281 if (i + cluster > ra_index) {
1282 ra_index = max(i, ra_index);
1283 btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1285 ra_index += max_cluster;
1288 mutex_lock(&inode->i_mutex);
1289 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1290 BTRFS_I(inode)->force_compress = compress_type;
1291 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1293 mutex_unlock(&inode->i_mutex);
1297 defrag_count += ret;
1298 balance_dirty_pages_ratelimited(inode->i_mapping);
1299 mutex_unlock(&inode->i_mutex);
1302 if (newer_off == (u64)-1)
1308 newer_off = max(newer_off + 1,
1309 (u64)i << PAGE_CACHE_SHIFT);
1311 ret = find_new_extents(root, inode,
1312 newer_than, &newer_off,
1315 range->start = newer_off;
1316 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1323 last_len += ret << PAGE_CACHE_SHIFT;
1331 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
1332 filemap_flush(inode->i_mapping);
1334 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1335 /* the filemap_flush will queue IO into the worker threads, but
1336 * we have to make sure the IO is actually started and that
1337 * ordered extents get created before we return
1339 atomic_inc(&root->fs_info->async_submit_draining);
1340 while (atomic_read(&root->fs_info->nr_async_submits) ||
1341 atomic_read(&root->fs_info->async_delalloc_pages)) {
1342 wait_event(root->fs_info->async_submit_wait,
1343 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1344 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1346 atomic_dec(&root->fs_info->async_submit_draining);
1349 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1350 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1356 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1357 mutex_lock(&inode->i_mutex);
1358 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1359 mutex_unlock(&inode->i_mutex);
1367 static noinline int btrfs_ioctl_resize(struct file *file,
1373 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1374 struct btrfs_ioctl_vol_args *vol_args;
1375 struct btrfs_trans_handle *trans;
1376 struct btrfs_device *device = NULL;
1378 char *devstr = NULL;
1382 if (!capable(CAP_SYS_ADMIN))
1385 ret = mnt_want_write_file(file);
1389 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1391 mnt_drop_write_file(file);
1392 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1395 mutex_lock(&root->fs_info->volume_mutex);
1396 vol_args = memdup_user(arg, sizeof(*vol_args));
1397 if (IS_ERR(vol_args)) {
1398 ret = PTR_ERR(vol_args);
1402 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1404 sizestr = vol_args->name;
1405 devstr = strchr(sizestr, ':');
1408 sizestr = devstr + 1;
1410 devstr = vol_args->name;
1411 devid = simple_strtoull(devstr, &end, 10);
1416 printk(KERN_INFO "btrfs: resizing devid %llu\n", devid);
1419 device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1421 printk(KERN_INFO "btrfs: resizer unable to find device %llu\n",
1427 if (!device->writeable) {
1428 printk(KERN_INFO "btrfs: resizer unable to apply on "
1429 "readonly device %llu\n",
1435 if (!strcmp(sizestr, "max"))
1436 new_size = device->bdev->bd_inode->i_size;
1438 if (sizestr[0] == '-') {
1441 } else if (sizestr[0] == '+') {
1445 new_size = memparse(sizestr, NULL);
1446 if (new_size == 0) {
1452 if (device->is_tgtdev_for_dev_replace) {
1457 old_size = device->total_bytes;
1460 if (new_size > old_size) {
1464 new_size = old_size - new_size;
1465 } else if (mod > 0) {
1466 new_size = old_size + new_size;
1469 if (new_size < 256 * 1024 * 1024) {
1473 if (new_size > device->bdev->bd_inode->i_size) {
1478 do_div(new_size, root->sectorsize);
1479 new_size *= root->sectorsize;
1481 printk_in_rcu(KERN_INFO "btrfs: new size for %s is %llu\n",
1482 rcu_str_deref(device->name), new_size);
1484 if (new_size > old_size) {
1485 trans = btrfs_start_transaction(root, 0);
1486 if (IS_ERR(trans)) {
1487 ret = PTR_ERR(trans);
1490 ret = btrfs_grow_device(trans, device, new_size);
1491 btrfs_commit_transaction(trans, root);
1492 } else if (new_size < old_size) {
1493 ret = btrfs_shrink_device(device, new_size);
1494 } /* equal, nothing need to do */
1499 mutex_unlock(&root->fs_info->volume_mutex);
1500 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1501 mnt_drop_write_file(file);
1505 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1506 char *name, unsigned long fd, int subvol,
1507 u64 *transid, bool readonly,
1508 struct btrfs_qgroup_inherit *inherit)
1513 ret = mnt_want_write_file(file);
1517 namelen = strlen(name);
1518 if (strchr(name, '/')) {
1520 goto out_drop_write;
1523 if (name[0] == '.' &&
1524 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1526 goto out_drop_write;
1530 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1531 NULL, transid, readonly, inherit);
1533 struct fd src = fdget(fd);
1534 struct inode *src_inode;
1537 goto out_drop_write;
1540 src_inode = file_inode(src.file);
1541 if (src_inode->i_sb != file_inode(file)->i_sb) {
1542 printk(KERN_INFO "btrfs: Snapshot src from "
1546 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1547 BTRFS_I(src_inode)->root,
1548 transid, readonly, inherit);
1553 mnt_drop_write_file(file);
1558 static noinline int btrfs_ioctl_snap_create(struct file *file,
1559 void __user *arg, int subvol)
1561 struct btrfs_ioctl_vol_args *vol_args;
1564 vol_args = memdup_user(arg, sizeof(*vol_args));
1565 if (IS_ERR(vol_args))
1566 return PTR_ERR(vol_args);
1567 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1569 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1570 vol_args->fd, subvol,
1577 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1578 void __user *arg, int subvol)
1580 struct btrfs_ioctl_vol_args_v2 *vol_args;
1584 bool readonly = false;
1585 struct btrfs_qgroup_inherit *inherit = NULL;
1587 vol_args = memdup_user(arg, sizeof(*vol_args));
1588 if (IS_ERR(vol_args))
1589 return PTR_ERR(vol_args);
1590 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1592 if (vol_args->flags &
1593 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1594 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1599 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1601 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1603 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1604 if (vol_args->size > PAGE_CACHE_SIZE) {
1608 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1609 if (IS_ERR(inherit)) {
1610 ret = PTR_ERR(inherit);
1615 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1616 vol_args->fd, subvol, ptr,
1619 if (ret == 0 && ptr &&
1621 offsetof(struct btrfs_ioctl_vol_args_v2,
1622 transid), ptr, sizeof(*ptr)))
1630 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1633 struct inode *inode = file_inode(file);
1634 struct btrfs_root *root = BTRFS_I(inode)->root;
1638 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1641 down_read(&root->fs_info->subvol_sem);
1642 if (btrfs_root_readonly(root))
1643 flags |= BTRFS_SUBVOL_RDONLY;
1644 up_read(&root->fs_info->subvol_sem);
1646 if (copy_to_user(arg, &flags, sizeof(flags)))
1652 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1655 struct inode *inode = file_inode(file);
1656 struct btrfs_root *root = BTRFS_I(inode)->root;
1657 struct btrfs_trans_handle *trans;
1662 ret = mnt_want_write_file(file);
1666 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1668 goto out_drop_write;
1671 if (copy_from_user(&flags, arg, sizeof(flags))) {
1673 goto out_drop_write;
1676 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1678 goto out_drop_write;
1681 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1683 goto out_drop_write;
1686 if (!inode_owner_or_capable(inode)) {
1688 goto out_drop_write;
1691 down_write(&root->fs_info->subvol_sem);
1694 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1697 root_flags = btrfs_root_flags(&root->root_item);
1698 if (flags & BTRFS_SUBVOL_RDONLY)
1699 btrfs_set_root_flags(&root->root_item,
1700 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1702 btrfs_set_root_flags(&root->root_item,
1703 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1705 trans = btrfs_start_transaction(root, 1);
1706 if (IS_ERR(trans)) {
1707 ret = PTR_ERR(trans);
1711 ret = btrfs_update_root(trans, root->fs_info->tree_root,
1712 &root->root_key, &root->root_item);
1714 btrfs_commit_transaction(trans, root);
1717 btrfs_set_root_flags(&root->root_item, root_flags);
1719 up_write(&root->fs_info->subvol_sem);
1721 mnt_drop_write_file(file);
1727 * helper to check if the subvolume references other subvolumes
1729 static noinline int may_destroy_subvol(struct btrfs_root *root)
1731 struct btrfs_path *path;
1732 struct btrfs_dir_item *di;
1733 struct btrfs_key key;
1737 path = btrfs_alloc_path();
1741 /* Make sure this root isn't set as the default subvol */
1742 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1743 di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1744 dir_id, "default", 7, 0);
1745 if (di && !IS_ERR(di)) {
1746 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1747 if (key.objectid == root->root_key.objectid) {
1751 btrfs_release_path(path);
1754 key.objectid = root->root_key.objectid;
1755 key.type = BTRFS_ROOT_REF_KEY;
1756 key.offset = (u64)-1;
1758 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1765 if (path->slots[0] > 0) {
1767 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1768 if (key.objectid == root->root_key.objectid &&
1769 key.type == BTRFS_ROOT_REF_KEY)
1773 btrfs_free_path(path);
1777 static noinline int key_in_sk(struct btrfs_key *key,
1778 struct btrfs_ioctl_search_key *sk)
1780 struct btrfs_key test;
1783 test.objectid = sk->min_objectid;
1784 test.type = sk->min_type;
1785 test.offset = sk->min_offset;
1787 ret = btrfs_comp_cpu_keys(key, &test);
1791 test.objectid = sk->max_objectid;
1792 test.type = sk->max_type;
1793 test.offset = sk->max_offset;
1795 ret = btrfs_comp_cpu_keys(key, &test);
1801 static noinline int copy_to_sk(struct btrfs_root *root,
1802 struct btrfs_path *path,
1803 struct btrfs_key *key,
1804 struct btrfs_ioctl_search_key *sk,
1806 unsigned long *sk_offset,
1810 struct extent_buffer *leaf;
1811 struct btrfs_ioctl_search_header sh;
1812 unsigned long item_off;
1813 unsigned long item_len;
1819 leaf = path->nodes[0];
1820 slot = path->slots[0];
1821 nritems = btrfs_header_nritems(leaf);
1823 if (btrfs_header_generation(leaf) > sk->max_transid) {
1827 found_transid = btrfs_header_generation(leaf);
1829 for (i = slot; i < nritems; i++) {
1830 item_off = btrfs_item_ptr_offset(leaf, i);
1831 item_len = btrfs_item_size_nr(leaf, i);
1833 btrfs_item_key_to_cpu(leaf, key, i);
1834 if (!key_in_sk(key, sk))
1837 if (sizeof(sh) + item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
1840 if (sizeof(sh) + item_len + *sk_offset >
1841 BTRFS_SEARCH_ARGS_BUFSIZE) {
1846 sh.objectid = key->objectid;
1847 sh.offset = key->offset;
1848 sh.type = key->type;
1850 sh.transid = found_transid;
1852 /* copy search result header */
1853 memcpy(buf + *sk_offset, &sh, sizeof(sh));
1854 *sk_offset += sizeof(sh);
1857 char *p = buf + *sk_offset;
1859 read_extent_buffer(leaf, p,
1860 item_off, item_len);
1861 *sk_offset += item_len;
1865 if (*num_found >= sk->nr_items)
1870 if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1872 else if (key->type < (u8)-1 && key->type < sk->max_type) {
1875 } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1885 static noinline int search_ioctl(struct inode *inode,
1886 struct btrfs_ioctl_search_args *args)
1888 struct btrfs_root *root;
1889 struct btrfs_key key;
1890 struct btrfs_path *path;
1891 struct btrfs_ioctl_search_key *sk = &args->key;
1892 struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1895 unsigned long sk_offset = 0;
1897 path = btrfs_alloc_path();
1901 if (sk->tree_id == 0) {
1902 /* search the root of the inode that was passed */
1903 root = BTRFS_I(inode)->root;
1905 key.objectid = sk->tree_id;
1906 key.type = BTRFS_ROOT_ITEM_KEY;
1907 key.offset = (u64)-1;
1908 root = btrfs_read_fs_root_no_name(info, &key);
1910 printk(KERN_ERR "could not find root %llu\n",
1912 btrfs_free_path(path);
1917 key.objectid = sk->min_objectid;
1918 key.type = sk->min_type;
1919 key.offset = sk->min_offset;
1921 path->keep_locks = 1;
1924 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
1930 ret = copy_to_sk(root, path, &key, sk, args->buf,
1931 &sk_offset, &num_found);
1932 btrfs_release_path(path);
1933 if (ret || num_found >= sk->nr_items)
1939 sk->nr_items = num_found;
1940 btrfs_free_path(path);
1944 static noinline int btrfs_ioctl_tree_search(struct file *file,
1947 struct btrfs_ioctl_search_args *args;
1948 struct inode *inode;
1951 if (!capable(CAP_SYS_ADMIN))
1954 args = memdup_user(argp, sizeof(*args));
1956 return PTR_ERR(args);
1958 inode = file_inode(file);
1959 ret = search_ioctl(inode, args);
1960 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1967 * Search INODE_REFs to identify path name of 'dirid' directory
1968 * in a 'tree_id' tree. and sets path name to 'name'.
1970 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
1971 u64 tree_id, u64 dirid, char *name)
1973 struct btrfs_root *root;
1974 struct btrfs_key key;
1980 struct btrfs_inode_ref *iref;
1981 struct extent_buffer *l;
1982 struct btrfs_path *path;
1984 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
1989 path = btrfs_alloc_path();
1993 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
1995 key.objectid = tree_id;
1996 key.type = BTRFS_ROOT_ITEM_KEY;
1997 key.offset = (u64)-1;
1998 root = btrfs_read_fs_root_no_name(info, &key);
2000 printk(KERN_ERR "could not find root %llu\n", tree_id);
2005 key.objectid = dirid;
2006 key.type = BTRFS_INODE_REF_KEY;
2007 key.offset = (u64)-1;
2010 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2014 ret = btrfs_previous_item(root, path, dirid,
2015 BTRFS_INODE_REF_KEY);
2025 slot = path->slots[0];
2026 btrfs_item_key_to_cpu(l, &key, slot);
2028 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2029 len = btrfs_inode_ref_name_len(l, iref);
2031 total_len += len + 1;
2033 ret = -ENAMETOOLONG;
2038 read_extent_buffer(l, ptr,(unsigned long)(iref + 1), len);
2040 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2043 btrfs_release_path(path);
2044 key.objectid = key.offset;
2045 key.offset = (u64)-1;
2046 dirid = key.objectid;
2048 memmove(name, ptr, total_len);
2049 name[total_len]='\0';
2052 btrfs_free_path(path);
2056 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2059 struct btrfs_ioctl_ino_lookup_args *args;
2060 struct inode *inode;
2063 if (!capable(CAP_SYS_ADMIN))
2066 args = memdup_user(argp, sizeof(*args));
2068 return PTR_ERR(args);
2070 inode = file_inode(file);
2072 if (args->treeid == 0)
2073 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2075 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2076 args->treeid, args->objectid,
2079 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2086 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2089 struct dentry *parent = fdentry(file);
2090 struct dentry *dentry;
2091 struct inode *dir = parent->d_inode;
2092 struct inode *inode;
2093 struct btrfs_root *root = BTRFS_I(dir)->root;
2094 struct btrfs_root *dest = NULL;
2095 struct btrfs_ioctl_vol_args *vol_args;
2096 struct btrfs_trans_handle *trans;
2097 struct btrfs_block_rsv block_rsv;
2098 u64 qgroup_reserved;
2103 vol_args = memdup_user(arg, sizeof(*vol_args));
2104 if (IS_ERR(vol_args))
2105 return PTR_ERR(vol_args);
2107 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2108 namelen = strlen(vol_args->name);
2109 if (strchr(vol_args->name, '/') ||
2110 strncmp(vol_args->name, "..", namelen) == 0) {
2115 err = mnt_want_write_file(file);
2119 err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2122 dentry = lookup_one_len(vol_args->name, parent, namelen);
2123 if (IS_ERR(dentry)) {
2124 err = PTR_ERR(dentry);
2125 goto out_unlock_dir;
2128 if (!dentry->d_inode) {
2133 inode = dentry->d_inode;
2134 dest = BTRFS_I(inode)->root;
2135 if (!capable(CAP_SYS_ADMIN)){
2137 * Regular user. Only allow this with a special mount
2138 * option, when the user has write+exec access to the
2139 * subvol root, and when rmdir(2) would have been
2142 * Note that this is _not_ check that the subvol is
2143 * empty or doesn't contain data that we wouldn't
2144 * otherwise be able to delete.
2146 * Users who want to delete empty subvols should try
2150 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2154 * Do not allow deletion if the parent dir is the same
2155 * as the dir to be deleted. That means the ioctl
2156 * must be called on the dentry referencing the root
2157 * of the subvol, not a random directory contained
2164 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2169 /* check if subvolume may be deleted by a user */
2170 err = btrfs_may_delete(dir, dentry, 1);
2174 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2179 mutex_lock(&inode->i_mutex);
2180 err = d_invalidate(dentry);
2184 down_write(&root->fs_info->subvol_sem);
2186 err = may_destroy_subvol(dest);
2190 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2192 * One for dir inode, two for dir entries, two for root
2195 err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2196 5, &qgroup_reserved, true);
2200 trans = btrfs_start_transaction(root, 0);
2201 if (IS_ERR(trans)) {
2202 err = PTR_ERR(trans);
2205 trans->block_rsv = &block_rsv;
2206 trans->bytes_reserved = block_rsv.size;
2208 ret = btrfs_unlink_subvol(trans, root, dir,
2209 dest->root_key.objectid,
2210 dentry->d_name.name,
2211 dentry->d_name.len);
2214 btrfs_abort_transaction(trans, root, ret);
2218 btrfs_record_root_in_trans(trans, dest);
2220 memset(&dest->root_item.drop_progress, 0,
2221 sizeof(dest->root_item.drop_progress));
2222 dest->root_item.drop_level = 0;
2223 btrfs_set_root_refs(&dest->root_item, 0);
2225 if (!xchg(&dest->orphan_item_inserted, 1)) {
2226 ret = btrfs_insert_orphan_item(trans,
2227 root->fs_info->tree_root,
2228 dest->root_key.objectid);
2230 btrfs_abort_transaction(trans, root, ret);
2236 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2237 dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2238 dest->root_key.objectid);
2239 if (ret && ret != -ENOENT) {
2240 btrfs_abort_transaction(trans, root, ret);
2244 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2245 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2246 dest->root_item.received_uuid,
2247 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2248 dest->root_key.objectid);
2249 if (ret && ret != -ENOENT) {
2250 btrfs_abort_transaction(trans, root, ret);
2257 trans->block_rsv = NULL;
2258 trans->bytes_reserved = 0;
2259 ret = btrfs_end_transaction(trans, root);
2262 inode->i_flags |= S_DEAD;
2264 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2266 up_write(&root->fs_info->subvol_sem);
2268 mutex_unlock(&inode->i_mutex);
2270 shrink_dcache_sb(root->fs_info->sb);
2271 btrfs_invalidate_inodes(dest);
2275 if (dest->cache_inode) {
2276 iput(dest->cache_inode);
2277 dest->cache_inode = NULL;
2283 mutex_unlock(&dir->i_mutex);
2284 mnt_drop_write_file(file);
2290 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2292 struct inode *inode = file_inode(file);
2293 struct btrfs_root *root = BTRFS_I(inode)->root;
2294 struct btrfs_ioctl_defrag_range_args *range;
2297 ret = mnt_want_write_file(file);
2301 if (btrfs_root_readonly(root)) {
2306 switch (inode->i_mode & S_IFMT) {
2308 if (!capable(CAP_SYS_ADMIN)) {
2312 ret = btrfs_defrag_root(root);
2315 ret = btrfs_defrag_root(root->fs_info->extent_root);
2318 if (!(file->f_mode & FMODE_WRITE)) {
2323 range = kzalloc(sizeof(*range), GFP_KERNEL);
2330 if (copy_from_user(range, argp,
2336 /* compression requires us to start the IO */
2337 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2338 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2339 range->extent_thresh = (u32)-1;
2342 /* the rest are all set to zero by kzalloc */
2343 range->len = (u64)-1;
2345 ret = btrfs_defrag_file(file_inode(file), file,
2355 mnt_drop_write_file(file);
2359 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2361 struct btrfs_ioctl_vol_args *vol_args;
2364 if (!capable(CAP_SYS_ADMIN))
2367 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2369 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2372 mutex_lock(&root->fs_info->volume_mutex);
2373 vol_args = memdup_user(arg, sizeof(*vol_args));
2374 if (IS_ERR(vol_args)) {
2375 ret = PTR_ERR(vol_args);
2379 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2380 ret = btrfs_init_new_device(root, vol_args->name);
2384 mutex_unlock(&root->fs_info->volume_mutex);
2385 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2389 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2391 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2392 struct btrfs_ioctl_vol_args *vol_args;
2395 if (!capable(CAP_SYS_ADMIN))
2398 ret = mnt_want_write_file(file);
2402 vol_args = memdup_user(arg, sizeof(*vol_args));
2403 if (IS_ERR(vol_args)) {
2404 ret = PTR_ERR(vol_args);
2408 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2410 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2412 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2416 mutex_lock(&root->fs_info->volume_mutex);
2417 ret = btrfs_rm_device(root, vol_args->name);
2418 mutex_unlock(&root->fs_info->volume_mutex);
2419 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2423 mnt_drop_write_file(file);
2427 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2429 struct btrfs_ioctl_fs_info_args *fi_args;
2430 struct btrfs_device *device;
2431 struct btrfs_device *next;
2432 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2435 if (!capable(CAP_SYS_ADMIN))
2438 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2442 mutex_lock(&fs_devices->device_list_mutex);
2443 fi_args->num_devices = fs_devices->num_devices;
2444 memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2446 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2447 if (device->devid > fi_args->max_id)
2448 fi_args->max_id = device->devid;
2450 mutex_unlock(&fs_devices->device_list_mutex);
2452 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2459 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2461 struct btrfs_ioctl_dev_info_args *di_args;
2462 struct btrfs_device *dev;
2463 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2465 char *s_uuid = NULL;
2467 if (!capable(CAP_SYS_ADMIN))
2470 di_args = memdup_user(arg, sizeof(*di_args));
2471 if (IS_ERR(di_args))
2472 return PTR_ERR(di_args);
2474 if (!btrfs_is_empty_uuid(di_args->uuid))
2475 s_uuid = di_args->uuid;
2477 mutex_lock(&fs_devices->device_list_mutex);
2478 dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2485 di_args->devid = dev->devid;
2486 di_args->bytes_used = dev->bytes_used;
2487 di_args->total_bytes = dev->total_bytes;
2488 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2490 struct rcu_string *name;
2493 name = rcu_dereference(dev->name);
2494 strncpy(di_args->path, name->str, sizeof(di_args->path));
2496 di_args->path[sizeof(di_args->path) - 1] = 0;
2498 di_args->path[0] = '\0';
2502 mutex_unlock(&fs_devices->device_list_mutex);
2503 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2510 static struct page *extent_same_get_page(struct inode *inode, u64 off)
2514 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2516 index = off >> PAGE_CACHE_SHIFT;
2518 page = grab_cache_page(inode->i_mapping, index);
2522 if (!PageUptodate(page)) {
2523 if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2527 if (!PageUptodate(page)) {
2529 page_cache_release(page);
2538 static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
2540 /* do any pending delalloc/csum calc on src, one way or
2541 another, and lock file content */
2543 struct btrfs_ordered_extent *ordered;
2544 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2545 ordered = btrfs_lookup_first_ordered_extent(inode,
2548 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2549 off + len - 1, EXTENT_DELALLOC, 0, NULL))
2551 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2553 btrfs_put_ordered_extent(ordered);
2554 btrfs_wait_ordered_range(inode, off, len);
2558 static void btrfs_double_unlock(struct inode *inode1, u64 loff1,
2559 struct inode *inode2, u64 loff2, u64 len)
2561 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2562 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2564 mutex_unlock(&inode1->i_mutex);
2565 mutex_unlock(&inode2->i_mutex);
2568 static void btrfs_double_lock(struct inode *inode1, u64 loff1,
2569 struct inode *inode2, u64 loff2, u64 len)
2571 if (inode1 < inode2) {
2572 swap(inode1, inode2);
2576 mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2577 lock_extent_range(inode1, loff1, len);
2578 if (inode1 != inode2) {
2579 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2580 lock_extent_range(inode2, loff2, len);
2584 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2585 u64 dst_loff, u64 len)
2588 struct page *src_page, *dst_page;
2589 unsigned int cmp_len = PAGE_CACHE_SIZE;
2590 void *addr, *dst_addr;
2593 if (len < PAGE_CACHE_SIZE)
2596 src_page = extent_same_get_page(src, loff);
2599 dst_page = extent_same_get_page(dst, dst_loff);
2601 page_cache_release(src_page);
2604 addr = kmap_atomic(src_page);
2605 dst_addr = kmap_atomic(dst_page);
2607 flush_dcache_page(src_page);
2608 flush_dcache_page(dst_page);
2610 if (memcmp(addr, dst_addr, cmp_len))
2611 ret = BTRFS_SAME_DATA_DIFFERS;
2613 kunmap_atomic(addr);
2614 kunmap_atomic(dst_addr);
2615 page_cache_release(src_page);
2616 page_cache_release(dst_page);
2622 dst_loff += cmp_len;
2629 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 len)
2631 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2633 if (off + len > inode->i_size || off + len < off)
2635 /* Check that we are block aligned - btrfs_clone() requires this */
2636 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2642 static int btrfs_extent_same(struct inode *src, u64 loff, u64 len,
2643 struct inode *dst, u64 dst_loff)
2648 * btrfs_clone() can't handle extents in the same file
2649 * yet. Once that works, we can drop this check and replace it
2650 * with a check for the same inode, but overlapping extents.
2655 btrfs_double_lock(src, loff, dst, dst_loff, len);
2657 ret = extent_same_check_offsets(src, loff, len);
2661 ret = extent_same_check_offsets(dst, dst_loff, len);
2665 /* don't make the dst file partly checksummed */
2666 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2667 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
2672 ret = btrfs_cmp_data(src, loff, dst, dst_loff, len);
2674 ret = btrfs_clone(src, dst, loff, len, len, dst_loff);
2677 btrfs_double_unlock(src, loff, dst, dst_loff, len);
2682 #define BTRFS_MAX_DEDUPE_LEN (16 * 1024 * 1024)
2684 static long btrfs_ioctl_file_extent_same(struct file *file,
2687 struct btrfs_ioctl_same_args tmp;
2688 struct btrfs_ioctl_same_args *same;
2689 struct btrfs_ioctl_same_extent_info *info;
2690 struct inode *src = file->f_dentry->d_inode;
2691 struct file *dst_file = NULL;
2698 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
2699 bool is_admin = capable(CAP_SYS_ADMIN);
2701 if (!(file->f_mode & FMODE_READ))
2704 ret = mnt_want_write_file(file);
2708 if (copy_from_user(&tmp,
2709 (struct btrfs_ioctl_same_args __user *)argp,
2715 size = sizeof(tmp) +
2716 tmp.dest_count * sizeof(struct btrfs_ioctl_same_extent_info);
2718 same = kmalloc(size, GFP_NOFS);
2724 if (copy_from_user(same,
2725 (struct btrfs_ioctl_same_args __user *)argp, size)) {
2730 off = same->logical_offset;
2734 * Limit the total length we will dedupe for each operation.
2735 * This is intended to bound the total time spent in this
2736 * ioctl to something sane.
2738 if (len > BTRFS_MAX_DEDUPE_LEN)
2739 len = BTRFS_MAX_DEDUPE_LEN;
2741 if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
2743 * Btrfs does not support blocksize < page_size. As a
2744 * result, btrfs_cmp_data() won't correctly handle
2745 * this situation without an update.
2752 if (S_ISDIR(src->i_mode))
2756 if (!S_ISREG(src->i_mode))
2759 /* pre-format output fields to sane values */
2760 for (i = 0; i < same->dest_count; i++) {
2761 same->info[i].bytes_deduped = 0ULL;
2762 same->info[i].status = 0;
2766 for (i = 0; i < same->dest_count; i++) {
2767 info = &same->info[i];
2769 dst_file = fget(info->fd);
2771 info->status = -EBADF;
2775 if (!(is_admin || (dst_file->f_mode & FMODE_WRITE))) {
2776 info->status = -EINVAL;
2780 info->status = -EXDEV;
2781 if (file->f_path.mnt != dst_file->f_path.mnt)
2784 dst = dst_file->f_dentry->d_inode;
2785 if (src->i_sb != dst->i_sb)
2788 if (S_ISDIR(dst->i_mode)) {
2789 info->status = -EISDIR;
2793 if (!S_ISREG(dst->i_mode)) {
2794 info->status = -EACCES;
2798 info->status = btrfs_extent_same(src, off, len, dst,
2799 info->logical_offset);
2800 if (info->status == 0)
2801 info->bytes_deduped += len;
2808 ret = copy_to_user(argp, same, size);
2813 mnt_drop_write_file(file);
2818 * btrfs_clone() - clone a range from inode file to another
2820 * @src: Inode to clone from
2821 * @inode: Inode to clone to
2822 * @off: Offset within source to start clone from
2823 * @olen: Original length, passed by user, of range to clone
2824 * @olen_aligned: Block-aligned value of olen, extent_same uses
2825 * identical values here
2826 * @destoff: Offset within @inode to start clone
2828 static int btrfs_clone(struct inode *src, struct inode *inode,
2829 u64 off, u64 olen, u64 olen_aligned, u64 destoff)
2831 struct btrfs_root *root = BTRFS_I(inode)->root;
2832 struct btrfs_path *path = NULL;
2833 struct extent_buffer *leaf;
2834 struct btrfs_trans_handle *trans;
2836 struct btrfs_key key;
2840 u64 len = olen_aligned;
2843 buf = vmalloc(btrfs_level_size(root, 0));
2847 path = btrfs_alloc_path();
2855 key.objectid = btrfs_ino(src);
2856 key.type = BTRFS_EXTENT_DATA_KEY;
2861 * note the key will change type as we walk through the
2864 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
2869 nritems = btrfs_header_nritems(path->nodes[0]);
2870 if (path->slots[0] >= nritems) {
2871 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
2876 nritems = btrfs_header_nritems(path->nodes[0]);
2878 leaf = path->nodes[0];
2879 slot = path->slots[0];
2881 btrfs_item_key_to_cpu(leaf, &key, slot);
2882 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
2883 key.objectid != btrfs_ino(src))
2886 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
2887 struct btrfs_file_extent_item *extent;
2890 struct btrfs_key new_key;
2891 u64 disko = 0, diskl = 0;
2892 u64 datao = 0, datal = 0;
2896 size = btrfs_item_size_nr(leaf, slot);
2897 read_extent_buffer(leaf, buf,
2898 btrfs_item_ptr_offset(leaf, slot),
2901 extent = btrfs_item_ptr(leaf, slot,
2902 struct btrfs_file_extent_item);
2903 comp = btrfs_file_extent_compression(leaf, extent);
2904 type = btrfs_file_extent_type(leaf, extent);
2905 if (type == BTRFS_FILE_EXTENT_REG ||
2906 type == BTRFS_FILE_EXTENT_PREALLOC) {
2907 disko = btrfs_file_extent_disk_bytenr(leaf,
2909 diskl = btrfs_file_extent_disk_num_bytes(leaf,
2911 datao = btrfs_file_extent_offset(leaf, extent);
2912 datal = btrfs_file_extent_num_bytes(leaf,
2914 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2915 /* take upper bound, may be compressed */
2916 datal = btrfs_file_extent_ram_bytes(leaf,
2919 btrfs_release_path(path);
2921 if (key.offset + datal <= off ||
2922 key.offset >= off + len - 1)
2925 memcpy(&new_key, &key, sizeof(new_key));
2926 new_key.objectid = btrfs_ino(inode);
2927 if (off <= key.offset)
2928 new_key.offset = key.offset + destoff - off;
2930 new_key.offset = destoff;
2933 * 1 - adjusting old extent (we may have to split it)
2934 * 1 - add new extent
2937 trans = btrfs_start_transaction(root, 3);
2938 if (IS_ERR(trans)) {
2939 ret = PTR_ERR(trans);
2943 if (type == BTRFS_FILE_EXTENT_REG ||
2944 type == BTRFS_FILE_EXTENT_PREALLOC) {
2946 * a | --- range to clone ---| b
2947 * | ------------- extent ------------- |
2950 /* substract range b */
2951 if (key.offset + datal > off + len)
2952 datal = off + len - key.offset;
2954 /* substract range a */
2955 if (off > key.offset) {
2956 datao += off - key.offset;
2957 datal -= off - key.offset;
2960 ret = btrfs_drop_extents(trans, root, inode,
2962 new_key.offset + datal,
2965 btrfs_abort_transaction(trans, root,
2967 btrfs_end_transaction(trans, root);
2971 ret = btrfs_insert_empty_item(trans, root, path,
2974 btrfs_abort_transaction(trans, root,
2976 btrfs_end_transaction(trans, root);
2980 leaf = path->nodes[0];
2981 slot = path->slots[0];
2982 write_extent_buffer(leaf, buf,
2983 btrfs_item_ptr_offset(leaf, slot),
2986 extent = btrfs_item_ptr(leaf, slot,
2987 struct btrfs_file_extent_item);
2989 /* disko == 0 means it's a hole */
2993 btrfs_set_file_extent_offset(leaf, extent,
2995 btrfs_set_file_extent_num_bytes(leaf, extent,
2998 inode_add_bytes(inode, datal);
2999 ret = btrfs_inc_extent_ref(trans, root,
3001 root->root_key.objectid,
3003 new_key.offset - datao,
3006 btrfs_abort_transaction(trans,
3009 btrfs_end_transaction(trans,
3015 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3018 if (off > key.offset) {
3019 skip = off - key.offset;
3020 new_key.offset += skip;
3023 if (key.offset + datal > off + len)
3024 trim = key.offset + datal - (off + len);
3026 if (comp && (skip || trim)) {
3028 btrfs_end_transaction(trans, root);
3031 size -= skip + trim;
3032 datal -= skip + trim;
3034 ret = btrfs_drop_extents(trans, root, inode,
3036 new_key.offset + datal,
3039 btrfs_abort_transaction(trans, root,
3041 btrfs_end_transaction(trans, root);
3045 ret = btrfs_insert_empty_item(trans, root, path,
3048 btrfs_abort_transaction(trans, root,
3050 btrfs_end_transaction(trans, root);
3056 btrfs_file_extent_calc_inline_size(0);
3057 memmove(buf+start, buf+start+skip,
3061 leaf = path->nodes[0];
3062 slot = path->slots[0];
3063 write_extent_buffer(leaf, buf,
3064 btrfs_item_ptr_offset(leaf, slot),
3066 inode_add_bytes(inode, datal);
3069 btrfs_mark_buffer_dirty(leaf);
3070 btrfs_release_path(path);
3072 inode_inc_iversion(inode);
3073 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3076 * we round up to the block size at eof when
3077 * determining which extents to clone above,
3078 * but shouldn't round up the file size
3080 endoff = new_key.offset + datal;
3081 if (endoff > destoff+olen)
3082 endoff = destoff+olen;
3083 if (endoff > inode->i_size)
3084 btrfs_i_size_write(inode, endoff);
3086 ret = btrfs_update_inode(trans, root, inode);
3088 btrfs_abort_transaction(trans, root, ret);
3089 btrfs_end_transaction(trans, root);
3092 ret = btrfs_end_transaction(trans, root);
3095 btrfs_release_path(path);
3101 btrfs_release_path(path);
3102 btrfs_free_path(path);
3107 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
3108 u64 off, u64 olen, u64 destoff)
3110 struct inode *inode = fdentry(file)->d_inode;
3111 struct btrfs_root *root = BTRFS_I(inode)->root;
3116 u64 bs = root->fs_info->sb->s_blocksize;
3121 * - split compressed inline extents. annoying: we need to
3122 * decompress into destination's address_space (the file offset
3123 * may change, so source mapping won't do), then recompress (or
3124 * otherwise reinsert) a subrange.
3125 * - allow ranges within the same file to be cloned (provided
3126 * they don't overlap)?
3129 /* the destination must be opened for writing */
3130 if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
3133 if (btrfs_root_readonly(root))
3136 ret = mnt_want_write_file(file);
3140 src_file = fdget(srcfd);
3141 if (!src_file.file) {
3143 goto out_drop_write;
3147 if (src_file.file->f_path.mnt != file->f_path.mnt)
3150 src = file_inode(src_file.file);
3156 /* the src must be open for reading */
3157 if (!(src_file.file->f_mode & FMODE_READ))
3160 /* don't make the dst file partly checksummed */
3161 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3162 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
3166 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3170 if (src->i_sb != inode->i_sb)
3175 mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
3176 mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
3178 mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
3179 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
3182 mutex_lock(&src->i_mutex);
3185 /* determine range to clone */
3187 if (off + len > src->i_size || off + len < off)
3190 olen = len = src->i_size - off;
3191 /* if we extend to eof, continue to block boundary */
3192 if (off + len == src->i_size)
3193 len = ALIGN(src->i_size, bs) - off;
3195 /* verify the end result is block aligned */
3196 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3197 !IS_ALIGNED(destoff, bs))
3200 /* verify if ranges are overlapped within the same file */
3202 if (destoff + len > off && destoff < off + len)
3206 if (destoff > inode->i_size) {
3207 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3212 /* truncate page cache pages from target inode range */
3213 truncate_inode_pages_range(&inode->i_data, destoff,
3214 PAGE_CACHE_ALIGN(destoff + len) - 1);
3216 lock_extent_range(src, off, len);
3218 ret = btrfs_clone(src, inode, off, olen, len, destoff);
3220 unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
3222 mutex_unlock(&src->i_mutex);
3224 mutex_unlock(&inode->i_mutex);
3228 mnt_drop_write_file(file);
3232 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
3234 struct btrfs_ioctl_clone_range_args args;
3236 if (copy_from_user(&args, argp, sizeof(args)))
3238 return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
3239 args.src_length, args.dest_offset);
3243 * there are many ways the trans_start and trans_end ioctls can lead
3244 * to deadlocks. They should only be used by applications that
3245 * basically own the machine, and have a very in depth understanding
3246 * of all the possible deadlocks and enospc problems.
3248 static long btrfs_ioctl_trans_start(struct file *file)
3250 struct inode *inode = file_inode(file);
3251 struct btrfs_root *root = BTRFS_I(inode)->root;
3252 struct btrfs_trans_handle *trans;
3256 if (!capable(CAP_SYS_ADMIN))
3260 if (file->private_data)
3264 if (btrfs_root_readonly(root))
3267 ret = mnt_want_write_file(file);
3271 atomic_inc(&root->fs_info->open_ioctl_trans);
3274 trans = btrfs_start_ioctl_transaction(root);
3278 file->private_data = trans;
3282 atomic_dec(&root->fs_info->open_ioctl_trans);
3283 mnt_drop_write_file(file);
3288 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3290 struct inode *inode = file_inode(file);
3291 struct btrfs_root *root = BTRFS_I(inode)->root;
3292 struct btrfs_root *new_root;
3293 struct btrfs_dir_item *di;
3294 struct btrfs_trans_handle *trans;
3295 struct btrfs_path *path;
3296 struct btrfs_key location;
3297 struct btrfs_disk_key disk_key;
3302 if (!capable(CAP_SYS_ADMIN))
3305 ret = mnt_want_write_file(file);
3309 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3315 objectid = BTRFS_FS_TREE_OBJECTID;
3317 location.objectid = objectid;
3318 location.type = BTRFS_ROOT_ITEM_KEY;
3319 location.offset = (u64)-1;
3321 new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
3322 if (IS_ERR(new_root)) {
3323 ret = PTR_ERR(new_root);
3327 path = btrfs_alloc_path();
3332 path->leave_spinning = 1;
3334 trans = btrfs_start_transaction(root, 1);
3335 if (IS_ERR(trans)) {
3336 btrfs_free_path(path);
3337 ret = PTR_ERR(trans);
3341 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
3342 di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
3343 dir_id, "default", 7, 1);
3344 if (IS_ERR_OR_NULL(di)) {
3345 btrfs_free_path(path);
3346 btrfs_end_transaction(trans, root);
3347 printk(KERN_ERR "Umm, you don't have the default dir item, "
3348 "this isn't going to work\n");
3353 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3354 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3355 btrfs_mark_buffer_dirty(path->nodes[0]);
3356 btrfs_free_path(path);
3358 btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
3359 btrfs_end_transaction(trans, root);
3361 mnt_drop_write_file(file);
3365 void btrfs_get_block_group_info(struct list_head *groups_list,
3366 struct btrfs_ioctl_space_info *space)
3368 struct btrfs_block_group_cache *block_group;
3370 space->total_bytes = 0;
3371 space->used_bytes = 0;
3373 list_for_each_entry(block_group, groups_list, list) {
3374 space->flags = block_group->flags;
3375 space->total_bytes += block_group->key.offset;
3376 space->used_bytes +=
3377 btrfs_block_group_used(&block_group->item);
3381 static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
3383 struct btrfs_ioctl_space_args space_args;
3384 struct btrfs_ioctl_space_info space;
3385 struct btrfs_ioctl_space_info *dest;
3386 struct btrfs_ioctl_space_info *dest_orig;
3387 struct btrfs_ioctl_space_info __user *user_dest;
3388 struct btrfs_space_info *info;
3389 u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
3390 BTRFS_BLOCK_GROUP_SYSTEM,
3391 BTRFS_BLOCK_GROUP_METADATA,
3392 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
3399 if (copy_from_user(&space_args,
3400 (struct btrfs_ioctl_space_args __user *)arg,
3401 sizeof(space_args)))
3404 for (i = 0; i < num_types; i++) {
3405 struct btrfs_space_info *tmp;
3409 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3411 if (tmp->flags == types[i]) {
3421 down_read(&info->groups_sem);
3422 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3423 if (!list_empty(&info->block_groups[c]))
3426 up_read(&info->groups_sem);
3429 /* space_slots == 0 means they are asking for a count */
3430 if (space_args.space_slots == 0) {
3431 space_args.total_spaces = slot_count;
3435 slot_count = min_t(u64, space_args.space_slots, slot_count);
3437 alloc_size = sizeof(*dest) * slot_count;
3439 /* we generally have at most 6 or so space infos, one for each raid
3440 * level. So, a whole page should be more than enough for everyone
3442 if (alloc_size > PAGE_CACHE_SIZE)
3445 space_args.total_spaces = 0;
3446 dest = kmalloc(alloc_size, GFP_NOFS);
3451 /* now we have a buffer to copy into */
3452 for (i = 0; i < num_types; i++) {
3453 struct btrfs_space_info *tmp;
3460 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3462 if (tmp->flags == types[i]) {
3471 down_read(&info->groups_sem);
3472 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3473 if (!list_empty(&info->block_groups[c])) {
3474 btrfs_get_block_group_info(
3475 &info->block_groups[c], &space);
3476 memcpy(dest, &space, sizeof(space));
3478 space_args.total_spaces++;
3484 up_read(&info->groups_sem);
3487 user_dest = (struct btrfs_ioctl_space_info __user *)
3488 (arg + sizeof(struct btrfs_ioctl_space_args));
3490 if (copy_to_user(user_dest, dest_orig, alloc_size))
3495 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3502 * there are many ways the trans_start and trans_end ioctls can lead
3503 * to deadlocks. They should only be used by applications that
3504 * basically own the machine, and have a very in depth understanding
3505 * of all the possible deadlocks and enospc problems.
3507 long btrfs_ioctl_trans_end(struct file *file)
3509 struct inode *inode = file_inode(file);
3510 struct btrfs_root *root = BTRFS_I(inode)->root;
3511 struct btrfs_trans_handle *trans;
3513 trans = file->private_data;
3516 file->private_data = NULL;
3518 btrfs_end_transaction(trans, root);
3520 atomic_dec(&root->fs_info->open_ioctl_trans);
3522 mnt_drop_write_file(file);
3526 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3529 struct btrfs_trans_handle *trans;
3533 trans = btrfs_attach_transaction_barrier(root);
3534 if (IS_ERR(trans)) {
3535 if (PTR_ERR(trans) != -ENOENT)
3536 return PTR_ERR(trans);
3538 /* No running transaction, don't bother */
3539 transid = root->fs_info->last_trans_committed;
3542 transid = trans->transid;
3543 ret = btrfs_commit_transaction_async(trans, root, 0);
3545 btrfs_end_transaction(trans, root);
3550 if (copy_to_user(argp, &transid, sizeof(transid)))
3555 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
3561 if (copy_from_user(&transid, argp, sizeof(transid)))
3564 transid = 0; /* current trans */
3566 return btrfs_wait_for_commit(root, transid);
3569 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3571 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3572 struct btrfs_ioctl_scrub_args *sa;
3575 if (!capable(CAP_SYS_ADMIN))
3578 sa = memdup_user(arg, sizeof(*sa));
3582 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3583 ret = mnt_want_write_file(file);
3588 ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
3589 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3592 if (copy_to_user(arg, sa, sizeof(*sa)))
3595 if (!(sa->flags & BTRFS_SCRUB_READONLY))
3596 mnt_drop_write_file(file);
3602 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
3604 if (!capable(CAP_SYS_ADMIN))
3607 return btrfs_scrub_cancel(root->fs_info);
3610 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
3613 struct btrfs_ioctl_scrub_args *sa;
3616 if (!capable(CAP_SYS_ADMIN))
3619 sa = memdup_user(arg, sizeof(*sa));
3623 ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
3625 if (copy_to_user(arg, sa, sizeof(*sa)))
3632 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
3635 struct btrfs_ioctl_get_dev_stats *sa;
3638 sa = memdup_user(arg, sizeof(*sa));
3642 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3647 ret = btrfs_get_dev_stats(root, sa);
3649 if (copy_to_user(arg, sa, sizeof(*sa)))
3656 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
3658 struct btrfs_ioctl_dev_replace_args *p;
3661 if (!capable(CAP_SYS_ADMIN))
3664 p = memdup_user(arg, sizeof(*p));
3669 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3670 if (root->fs_info->sb->s_flags & MS_RDONLY) {
3675 &root->fs_info->mutually_exclusive_operation_running,
3677 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3679 ret = btrfs_dev_replace_start(root, p);
3681 &root->fs_info->mutually_exclusive_operation_running,
3685 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3686 btrfs_dev_replace_status(root->fs_info, p);
3689 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3690 ret = btrfs_dev_replace_cancel(root->fs_info, p);
3697 if (copy_to_user(arg, p, sizeof(*p)))
3704 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3710 struct btrfs_ioctl_ino_path_args *ipa = NULL;
3711 struct inode_fs_paths *ipath = NULL;
3712 struct btrfs_path *path;
3714 if (!capable(CAP_DAC_READ_SEARCH))
3717 path = btrfs_alloc_path();
3723 ipa = memdup_user(arg, sizeof(*ipa));
3730 size = min_t(u32, ipa->size, 4096);
3731 ipath = init_ipath(size, root, path);
3732 if (IS_ERR(ipath)) {
3733 ret = PTR_ERR(ipath);
3738 ret = paths_from_inode(ipa->inum, ipath);
3742 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3743 rel_ptr = ipath->fspath->val[i] -
3744 (u64)(unsigned long)ipath->fspath->val;
3745 ipath->fspath->val[i] = rel_ptr;
3748 ret = copy_to_user((void *)(unsigned long)ipa->fspath,
3749 (void *)(unsigned long)ipath->fspath, size);
3756 btrfs_free_path(path);
3763 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3765 struct btrfs_data_container *inodes = ctx;
3766 const size_t c = 3 * sizeof(u64);
3768 if (inodes->bytes_left >= c) {
3769 inodes->bytes_left -= c;
3770 inodes->val[inodes->elem_cnt] = inum;
3771 inodes->val[inodes->elem_cnt + 1] = offset;
3772 inodes->val[inodes->elem_cnt + 2] = root;
3773 inodes->elem_cnt += 3;
3775 inodes->bytes_missing += c - inodes->bytes_left;
3776 inodes->bytes_left = 0;
3777 inodes->elem_missed += 3;
3783 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
3788 struct btrfs_ioctl_logical_ino_args *loi;
3789 struct btrfs_data_container *inodes = NULL;
3790 struct btrfs_path *path = NULL;
3792 if (!capable(CAP_SYS_ADMIN))
3795 loi = memdup_user(arg, sizeof(*loi));
3802 path = btrfs_alloc_path();
3808 size = min_t(u32, loi->size, 64 * 1024);
3809 inodes = init_data_container(size);
3810 if (IS_ERR(inodes)) {
3811 ret = PTR_ERR(inodes);
3816 ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
3817 build_ino_list, inodes);
3823 ret = copy_to_user((void *)(unsigned long)loi->inodes,
3824 (void *)(unsigned long)inodes, size);
3829 btrfs_free_path(path);
3836 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
3837 struct btrfs_ioctl_balance_args *bargs)
3839 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3841 bargs->flags = bctl->flags;
3843 if (atomic_read(&fs_info->balance_running))
3844 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3845 if (atomic_read(&fs_info->balance_pause_req))
3846 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3847 if (atomic_read(&fs_info->balance_cancel_req))
3848 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3850 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3851 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3852 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3855 spin_lock(&fs_info->balance_lock);
3856 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3857 spin_unlock(&fs_info->balance_lock);
3859 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3863 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3865 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3866 struct btrfs_fs_info *fs_info = root->fs_info;
3867 struct btrfs_ioctl_balance_args *bargs;
3868 struct btrfs_balance_control *bctl;
3869 bool need_unlock; /* for mut. excl. ops lock */
3872 if (!capable(CAP_SYS_ADMIN))
3875 ret = mnt_want_write_file(file);
3880 if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
3881 mutex_lock(&fs_info->volume_mutex);
3882 mutex_lock(&fs_info->balance_mutex);
3888 * mut. excl. ops lock is locked. Three possibilites:
3889 * (1) some other op is running
3890 * (2) balance is running
3891 * (3) balance is paused -- special case (think resume)
3893 mutex_lock(&fs_info->balance_mutex);
3894 if (fs_info->balance_ctl) {
3895 /* this is either (2) or (3) */
3896 if (!atomic_read(&fs_info->balance_running)) {
3897 mutex_unlock(&fs_info->balance_mutex);
3898 if (!mutex_trylock(&fs_info->volume_mutex))
3900 mutex_lock(&fs_info->balance_mutex);
3902 if (fs_info->balance_ctl &&
3903 !atomic_read(&fs_info->balance_running)) {
3905 need_unlock = false;
3909 mutex_unlock(&fs_info->balance_mutex);
3910 mutex_unlock(&fs_info->volume_mutex);
3914 mutex_unlock(&fs_info->balance_mutex);
3920 mutex_unlock(&fs_info->balance_mutex);
3921 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3926 BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
3929 bargs = memdup_user(arg, sizeof(*bargs));
3930 if (IS_ERR(bargs)) {
3931 ret = PTR_ERR(bargs);
3935 if (bargs->flags & BTRFS_BALANCE_RESUME) {
3936 if (!fs_info->balance_ctl) {
3941 bctl = fs_info->balance_ctl;
3942 spin_lock(&fs_info->balance_lock);
3943 bctl->flags |= BTRFS_BALANCE_RESUME;
3944 spin_unlock(&fs_info->balance_lock);
3952 if (fs_info->balance_ctl) {
3957 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3963 bctl->fs_info = fs_info;
3965 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
3966 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
3967 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
3969 bctl->flags = bargs->flags;
3971 /* balance everything - no filters */
3972 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
3977 * Ownership of bctl and mutually_exclusive_operation_running
3978 * goes to to btrfs_balance. bctl is freed in __cancel_balance,
3979 * or, if restriper was paused all the way until unmount, in
3980 * free_fs_info. mutually_exclusive_operation_running is
3981 * cleared in __cancel_balance.
3983 need_unlock = false;
3985 ret = btrfs_balance(bctl, bargs);
3988 if (copy_to_user(arg, bargs, sizeof(*bargs)))
3995 mutex_unlock(&fs_info->balance_mutex);
3996 mutex_unlock(&fs_info->volume_mutex);
3998 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4000 mnt_drop_write_file(file);
4004 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4006 if (!capable(CAP_SYS_ADMIN))
4010 case BTRFS_BALANCE_CTL_PAUSE:
4011 return btrfs_pause_balance(root->fs_info);
4012 case BTRFS_BALANCE_CTL_CANCEL:
4013 return btrfs_cancel_balance(root->fs_info);
4019 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
4022 struct btrfs_fs_info *fs_info = root->fs_info;
4023 struct btrfs_ioctl_balance_args *bargs;
4026 if (!capable(CAP_SYS_ADMIN))
4029 mutex_lock(&fs_info->balance_mutex);
4030 if (!fs_info->balance_ctl) {
4035 bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
4041 update_ioctl_balance_args(fs_info, 1, bargs);
4043 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4048 mutex_unlock(&fs_info->balance_mutex);
4052 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4054 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4055 struct btrfs_ioctl_quota_ctl_args *sa;
4056 struct btrfs_trans_handle *trans = NULL;
4060 if (!capable(CAP_SYS_ADMIN))
4063 ret = mnt_want_write_file(file);
4067 sa = memdup_user(arg, sizeof(*sa));
4073 down_write(&root->fs_info->subvol_sem);
4074 trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
4075 if (IS_ERR(trans)) {
4076 ret = PTR_ERR(trans);
4081 case BTRFS_QUOTA_CTL_ENABLE:
4082 ret = btrfs_quota_enable(trans, root->fs_info);
4084 case BTRFS_QUOTA_CTL_DISABLE:
4085 ret = btrfs_quota_disable(trans, root->fs_info);
4092 err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
4097 up_write(&root->fs_info->subvol_sem);
4099 mnt_drop_write_file(file);
4103 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4105 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4106 struct btrfs_ioctl_qgroup_assign_args *sa;
4107 struct btrfs_trans_handle *trans;
4111 if (!capable(CAP_SYS_ADMIN))
4114 ret = mnt_want_write_file(file);
4118 sa = memdup_user(arg, sizeof(*sa));
4124 trans = btrfs_join_transaction(root);
4125 if (IS_ERR(trans)) {
4126 ret = PTR_ERR(trans);
4130 /* FIXME: check if the IDs really exist */
4132 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
4135 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
4139 err = btrfs_end_transaction(trans, root);
4146 mnt_drop_write_file(file);
4150 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4152 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4153 struct btrfs_ioctl_qgroup_create_args *sa;
4154 struct btrfs_trans_handle *trans;
4158 if (!capable(CAP_SYS_ADMIN))
4161 ret = mnt_want_write_file(file);
4165 sa = memdup_user(arg, sizeof(*sa));
4171 if (!sa->qgroupid) {
4176 trans = btrfs_join_transaction(root);
4177 if (IS_ERR(trans)) {
4178 ret = PTR_ERR(trans);
4182 /* FIXME: check if the IDs really exist */
4184 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid,
4187 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
4190 err = btrfs_end_transaction(trans, root);
4197 mnt_drop_write_file(file);
4201 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4203 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4204 struct btrfs_ioctl_qgroup_limit_args *sa;
4205 struct btrfs_trans_handle *trans;
4210 if (!capable(CAP_SYS_ADMIN))
4213 ret = mnt_want_write_file(file);
4217 sa = memdup_user(arg, sizeof(*sa));
4223 trans = btrfs_join_transaction(root);
4224 if (IS_ERR(trans)) {
4225 ret = PTR_ERR(trans);
4229 qgroupid = sa->qgroupid;
4231 /* take the current subvol as qgroup */
4232 qgroupid = root->root_key.objectid;
4235 /* FIXME: check if the IDs really exist */
4236 ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
4238 err = btrfs_end_transaction(trans, root);
4245 mnt_drop_write_file(file);
4249 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4251 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4252 struct btrfs_ioctl_quota_rescan_args *qsa;
4255 if (!capable(CAP_SYS_ADMIN))
4258 ret = mnt_want_write_file(file);
4262 qsa = memdup_user(arg, sizeof(*qsa));
4273 ret = btrfs_qgroup_rescan(root->fs_info);
4278 mnt_drop_write_file(file);
4282 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
4284 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4285 struct btrfs_ioctl_quota_rescan_args *qsa;
4288 if (!capable(CAP_SYS_ADMIN))
4291 qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
4295 if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4297 qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
4300 if (copy_to_user(arg, qsa, sizeof(*qsa)))
4307 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
4309 struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
4311 if (!capable(CAP_SYS_ADMIN))
4314 return btrfs_qgroup_wait_for_completion(root->fs_info);
4317 static long btrfs_ioctl_set_received_subvol(struct file *file,
4320 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4321 struct inode *inode = file_inode(file);
4322 struct btrfs_root *root = BTRFS_I(inode)->root;
4323 struct btrfs_root_item *root_item = &root->root_item;
4324 struct btrfs_trans_handle *trans;
4325 struct timespec ct = CURRENT_TIME;
4327 int received_uuid_changed;
4329 ret = mnt_want_write_file(file);
4333 down_write(&root->fs_info->subvol_sem);
4335 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
4340 if (btrfs_root_readonly(root)) {
4345 if (!inode_owner_or_capable(inode)) {
4350 sa = memdup_user(arg, sizeof(*sa));
4359 * 2 - uuid items (received uuid + subvol uuid)
4361 trans = btrfs_start_transaction(root, 3);
4362 if (IS_ERR(trans)) {
4363 ret = PTR_ERR(trans);
4368 sa->rtransid = trans->transid;
4369 sa->rtime.sec = ct.tv_sec;
4370 sa->rtime.nsec = ct.tv_nsec;
4372 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4374 if (received_uuid_changed &&
4375 !btrfs_is_empty_uuid(root_item->received_uuid))
4376 btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
4377 root_item->received_uuid,
4378 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4379 root->root_key.objectid);
4380 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4381 btrfs_set_root_stransid(root_item, sa->stransid);
4382 btrfs_set_root_rtransid(root_item, sa->rtransid);
4383 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4384 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4385 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4386 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4388 ret = btrfs_update_root(trans, root->fs_info->tree_root,
4389 &root->root_key, &root->root_item);
4391 btrfs_end_transaction(trans, root);
4394 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4395 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
4397 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4398 root->root_key.objectid);
4399 if (ret < 0 && ret != -EEXIST) {
4400 btrfs_abort_transaction(trans, root, ret);
4404 ret = btrfs_commit_transaction(trans, root);
4406 btrfs_abort_transaction(trans, root, ret);
4410 ret = copy_to_user(arg, sa, sizeof(*sa));
4416 up_write(&root->fs_info->subvol_sem);
4417 mnt_drop_write_file(file);
4421 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
4423 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4426 char label[BTRFS_LABEL_SIZE];
4428 spin_lock(&root->fs_info->super_lock);
4429 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4430 spin_unlock(&root->fs_info->super_lock);
4432 len = strnlen(label, BTRFS_LABEL_SIZE);
4434 if (len == BTRFS_LABEL_SIZE) {
4435 pr_warn("btrfs: label is too long, return the first %zu bytes\n",
4439 ret = copy_to_user(arg, label, len);
4441 return ret ? -EFAULT : 0;
4444 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4446 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4447 struct btrfs_super_block *super_block = root->fs_info->super_copy;
4448 struct btrfs_trans_handle *trans;
4449 char label[BTRFS_LABEL_SIZE];
4452 if (!capable(CAP_SYS_ADMIN))
4455 if (copy_from_user(label, arg, sizeof(label)))
4458 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4459 pr_err("btrfs: unable to set label with more than %d bytes\n",
4460 BTRFS_LABEL_SIZE - 1);
4464 ret = mnt_want_write_file(file);
4468 trans = btrfs_start_transaction(root, 0);
4469 if (IS_ERR(trans)) {
4470 ret = PTR_ERR(trans);
4474 spin_lock(&root->fs_info->super_lock);
4475 strcpy(super_block->label, label);
4476 spin_unlock(&root->fs_info->super_lock);
4477 ret = btrfs_end_transaction(trans, root);
4480 mnt_drop_write_file(file);
4484 long btrfs_ioctl(struct file *file, unsigned int
4485 cmd, unsigned long arg)
4487 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4488 void __user *argp = (void __user *)arg;
4491 case FS_IOC_GETFLAGS:
4492 return btrfs_ioctl_getflags(file, argp);
4493 case FS_IOC_SETFLAGS:
4494 return btrfs_ioctl_setflags(file, argp);
4495 case FS_IOC_GETVERSION:
4496 return btrfs_ioctl_getversion(file, argp);
4498 return btrfs_ioctl_fitrim(file, argp);
4499 case BTRFS_IOC_SNAP_CREATE:
4500 return btrfs_ioctl_snap_create(file, argp, 0);
4501 case BTRFS_IOC_SNAP_CREATE_V2:
4502 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4503 case BTRFS_IOC_SUBVOL_CREATE:
4504 return btrfs_ioctl_snap_create(file, argp, 1);
4505 case BTRFS_IOC_SUBVOL_CREATE_V2:
4506 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4507 case BTRFS_IOC_SNAP_DESTROY:
4508 return btrfs_ioctl_snap_destroy(file, argp);
4509 case BTRFS_IOC_SUBVOL_GETFLAGS:
4510 return btrfs_ioctl_subvol_getflags(file, argp);
4511 case BTRFS_IOC_SUBVOL_SETFLAGS:
4512 return btrfs_ioctl_subvol_setflags(file, argp);
4513 case BTRFS_IOC_DEFAULT_SUBVOL:
4514 return btrfs_ioctl_default_subvol(file, argp);
4515 case BTRFS_IOC_DEFRAG:
4516 return btrfs_ioctl_defrag(file, NULL);
4517 case BTRFS_IOC_DEFRAG_RANGE:
4518 return btrfs_ioctl_defrag(file, argp);
4519 case BTRFS_IOC_RESIZE:
4520 return btrfs_ioctl_resize(file, argp);
4521 case BTRFS_IOC_ADD_DEV:
4522 return btrfs_ioctl_add_dev(root, argp);
4523 case BTRFS_IOC_RM_DEV:
4524 return btrfs_ioctl_rm_dev(file, argp);
4525 case BTRFS_IOC_FS_INFO:
4526 return btrfs_ioctl_fs_info(root, argp);
4527 case BTRFS_IOC_DEV_INFO:
4528 return btrfs_ioctl_dev_info(root, argp);
4529 case BTRFS_IOC_BALANCE:
4530 return btrfs_ioctl_balance(file, NULL);
4531 case BTRFS_IOC_CLONE:
4532 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
4533 case BTRFS_IOC_CLONE_RANGE:
4534 return btrfs_ioctl_clone_range(file, argp);
4535 case BTRFS_IOC_TRANS_START:
4536 return btrfs_ioctl_trans_start(file);
4537 case BTRFS_IOC_TRANS_END:
4538 return btrfs_ioctl_trans_end(file);
4539 case BTRFS_IOC_TREE_SEARCH:
4540 return btrfs_ioctl_tree_search(file, argp);
4541 case BTRFS_IOC_INO_LOOKUP:
4542 return btrfs_ioctl_ino_lookup(file, argp);
4543 case BTRFS_IOC_INO_PATHS:
4544 return btrfs_ioctl_ino_to_path(root, argp);
4545 case BTRFS_IOC_LOGICAL_INO:
4546 return btrfs_ioctl_logical_to_ino(root, argp);
4547 case BTRFS_IOC_SPACE_INFO:
4548 return btrfs_ioctl_space_info(root, argp);
4549 case BTRFS_IOC_SYNC: {
4552 ret = btrfs_start_all_delalloc_inodes(root->fs_info, 0);
4555 ret = btrfs_sync_fs(file->f_dentry->d_sb, 1);
4558 case BTRFS_IOC_START_SYNC:
4559 return btrfs_ioctl_start_sync(root, argp);
4560 case BTRFS_IOC_WAIT_SYNC:
4561 return btrfs_ioctl_wait_sync(root, argp);
4562 case BTRFS_IOC_SCRUB:
4563 return btrfs_ioctl_scrub(file, argp);
4564 case BTRFS_IOC_SCRUB_CANCEL:
4565 return btrfs_ioctl_scrub_cancel(root, argp);
4566 case BTRFS_IOC_SCRUB_PROGRESS:
4567 return btrfs_ioctl_scrub_progress(root, argp);
4568 case BTRFS_IOC_BALANCE_V2:
4569 return btrfs_ioctl_balance(file, argp);
4570 case BTRFS_IOC_BALANCE_CTL:
4571 return btrfs_ioctl_balance_ctl(root, arg);
4572 case BTRFS_IOC_BALANCE_PROGRESS:
4573 return btrfs_ioctl_balance_progress(root, argp);
4574 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4575 return btrfs_ioctl_set_received_subvol(file, argp);
4576 case BTRFS_IOC_SEND:
4577 return btrfs_ioctl_send(file, argp);
4578 case BTRFS_IOC_GET_DEV_STATS:
4579 return btrfs_ioctl_get_dev_stats(root, argp);
4580 case BTRFS_IOC_QUOTA_CTL:
4581 return btrfs_ioctl_quota_ctl(file, argp);
4582 case BTRFS_IOC_QGROUP_ASSIGN:
4583 return btrfs_ioctl_qgroup_assign(file, argp);
4584 case BTRFS_IOC_QGROUP_CREATE:
4585 return btrfs_ioctl_qgroup_create(file, argp);
4586 case BTRFS_IOC_QGROUP_LIMIT:
4587 return btrfs_ioctl_qgroup_limit(file, argp);
4588 case BTRFS_IOC_QUOTA_RESCAN:
4589 return btrfs_ioctl_quota_rescan(file, argp);
4590 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
4591 return btrfs_ioctl_quota_rescan_status(file, argp);
4592 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
4593 return btrfs_ioctl_quota_rescan_wait(file, argp);
4594 case BTRFS_IOC_DEV_REPLACE:
4595 return btrfs_ioctl_dev_replace(root, argp);
4596 case BTRFS_IOC_GET_FSLABEL:
4597 return btrfs_ioctl_get_fslabel(file, argp);
4598 case BTRFS_IOC_SET_FSLABEL:
4599 return btrfs_ioctl_set_fslabel(file, argp);
4600 case BTRFS_IOC_FILE_EXTENT_SAME:
4601 return btrfs_ioctl_file_extent_same(file, argp);