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(leaf),
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, 0);
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 btrfs_key max_key;
846 struct extent_buffer *leaf;
847 struct btrfs_file_extent_item *extent;
850 u64 ino = btrfs_ino(inode);
852 path = btrfs_alloc_path();
856 min_key.objectid = ino;
857 min_key.type = BTRFS_EXTENT_DATA_KEY;
858 min_key.offset = *off;
860 max_key.objectid = ino;
861 max_key.type = (u8)-1;
862 max_key.offset = (u64)-1;
864 path->keep_locks = 1;
867 ret = btrfs_search_forward(root, &min_key, &max_key,
871 if (min_key.objectid != ino)
873 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
876 leaf = path->nodes[0];
877 extent = btrfs_item_ptr(leaf, path->slots[0],
878 struct btrfs_file_extent_item);
880 type = btrfs_file_extent_type(leaf, extent);
881 if (type == BTRFS_FILE_EXTENT_REG &&
882 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
883 check_defrag_in_cache(inode, min_key.offset, thresh)) {
884 *off = min_key.offset;
885 btrfs_free_path(path);
889 if (min_key.offset == (u64)-1)
893 btrfs_release_path(path);
896 btrfs_free_path(path);
900 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
902 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
903 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
904 struct extent_map *em;
905 u64 len = PAGE_CACHE_SIZE;
908 * hopefully we have this extent in the tree already, try without
909 * the full extent lock
911 read_lock(&em_tree->lock);
912 em = lookup_extent_mapping(em_tree, start, len);
913 read_unlock(&em_tree->lock);
916 /* get the big lock and read metadata off disk */
917 lock_extent(io_tree, start, start + len - 1);
918 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
919 unlock_extent(io_tree, start, start + len - 1);
928 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
930 struct extent_map *next;
933 /* this is the last extent */
934 if (em->start + em->len >= i_size_read(inode))
937 next = defrag_lookup_extent(inode, em->start + em->len);
938 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
941 free_extent_map(next);
945 static int should_defrag_range(struct inode *inode, u64 start, int thresh,
946 u64 *last_len, u64 *skip, u64 *defrag_end,
949 struct extent_map *em;
951 bool next_mergeable = true;
954 * make sure that once we start defragging an extent, we keep on
957 if (start < *defrag_end)
962 em = defrag_lookup_extent(inode, start);
966 /* this will cover holes, and inline extents */
967 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
972 next_mergeable = defrag_check_next_extent(inode, em);
975 * we hit a real extent, if it is big or the next extent is not a
976 * real extent, don't bother defragging it
978 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
979 (em->len >= thresh || !next_mergeable))
983 * last_len ends up being a counter of how many bytes we've defragged.
984 * every time we choose not to defrag an extent, we reset *last_len
985 * so that the next tiny extent will force a defrag.
987 * The end result of this is that tiny extents before a single big
988 * extent will force at least part of that big extent to be defragged.
991 *defrag_end = extent_map_end(em);
994 *skip = extent_map_end(em);
1003 * it doesn't do much good to defrag one or two pages
1004 * at a time. This pulls in a nice chunk of pages
1005 * to COW and defrag.
1007 * It also makes sure the delalloc code has enough
1008 * dirty data to avoid making new small extents as part
1011 * It's a good idea to start RA on this range
1012 * before calling this.
1014 static int cluster_pages_for_defrag(struct inode *inode,
1015 struct page **pages,
1016 unsigned long start_index,
1019 unsigned long file_end;
1020 u64 isize = i_size_read(inode);
1027 struct btrfs_ordered_extent *ordered;
1028 struct extent_state *cached_state = NULL;
1029 struct extent_io_tree *tree;
1030 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1032 file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1033 if (!isize || start_index > file_end)
1036 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1038 ret = btrfs_delalloc_reserve_space(inode,
1039 page_cnt << PAGE_CACHE_SHIFT);
1043 tree = &BTRFS_I(inode)->io_tree;
1045 /* step one, lock all the pages */
1046 for (i = 0; i < page_cnt; i++) {
1049 page = find_or_create_page(inode->i_mapping,
1050 start_index + i, mask);
1054 page_start = page_offset(page);
1055 page_end = page_start + PAGE_CACHE_SIZE - 1;
1057 lock_extent(tree, page_start, page_end);
1058 ordered = btrfs_lookup_ordered_extent(inode,
1060 unlock_extent(tree, page_start, page_end);
1065 btrfs_start_ordered_extent(inode, ordered, 1);
1066 btrfs_put_ordered_extent(ordered);
1069 * we unlocked the page above, so we need check if
1070 * it was released or not.
1072 if (page->mapping != inode->i_mapping) {
1074 page_cache_release(page);
1079 if (!PageUptodate(page)) {
1080 btrfs_readpage(NULL, page);
1082 if (!PageUptodate(page)) {
1084 page_cache_release(page);
1090 if (page->mapping != inode->i_mapping) {
1092 page_cache_release(page);
1102 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1106 * so now we have a nice long stream of locked
1107 * and up to date pages, lets wait on them
1109 for (i = 0; i < i_done; i++)
1110 wait_on_page_writeback(pages[i]);
1112 page_start = page_offset(pages[0]);
1113 page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1115 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1116 page_start, page_end - 1, 0, &cached_state);
1117 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1118 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1119 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1120 &cached_state, GFP_NOFS);
1122 if (i_done != page_cnt) {
1123 spin_lock(&BTRFS_I(inode)->lock);
1124 BTRFS_I(inode)->outstanding_extents++;
1125 spin_unlock(&BTRFS_I(inode)->lock);
1126 btrfs_delalloc_release_space(inode,
1127 (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1131 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1132 &cached_state, GFP_NOFS);
1134 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1135 page_start, page_end - 1, &cached_state,
1138 for (i = 0; i < i_done; i++) {
1139 clear_page_dirty_for_io(pages[i]);
1140 ClearPageChecked(pages[i]);
1141 set_page_extent_mapped(pages[i]);
1142 set_page_dirty(pages[i]);
1143 unlock_page(pages[i]);
1144 page_cache_release(pages[i]);
1148 for (i = 0; i < i_done; i++) {
1149 unlock_page(pages[i]);
1150 page_cache_release(pages[i]);
1152 btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1157 int btrfs_defrag_file(struct inode *inode, struct file *file,
1158 struct btrfs_ioctl_defrag_range_args *range,
1159 u64 newer_than, unsigned long max_to_defrag)
1161 struct btrfs_root *root = BTRFS_I(inode)->root;
1162 struct file_ra_state *ra = NULL;
1163 unsigned long last_index;
1164 u64 isize = i_size_read(inode);
1168 u64 newer_off = range->start;
1170 unsigned long ra_index = 0;
1172 int defrag_count = 0;
1173 int compress_type = BTRFS_COMPRESS_ZLIB;
1174 int extent_thresh = range->extent_thresh;
1175 int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1176 int cluster = max_cluster;
1177 u64 new_align = ~((u64)128 * 1024 - 1);
1178 struct page **pages = NULL;
1183 if (range->start >= isize)
1186 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1187 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1189 if (range->compress_type)
1190 compress_type = range->compress_type;
1193 if (extent_thresh == 0)
1194 extent_thresh = 256 * 1024;
1197 * if we were not given a file, allocate a readahead
1201 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1204 file_ra_state_init(ra, inode->i_mapping);
1209 pages = kmalloc(sizeof(struct page *) * max_cluster,
1216 /* find the last page to defrag */
1217 if (range->start + range->len > range->start) {
1218 last_index = min_t(u64, isize - 1,
1219 range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1221 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1225 ret = find_new_extents(root, inode, newer_than,
1226 &newer_off, 64 * 1024);
1228 range->start = newer_off;
1230 * we always align our defrag to help keep
1231 * the extents in the file evenly spaced
1233 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1237 i = range->start >> PAGE_CACHE_SHIFT;
1240 max_to_defrag = last_index + 1;
1243 * make writeback starts from i, so the defrag range can be
1244 * written sequentially.
1246 if (i < inode->i_mapping->writeback_index)
1247 inode->i_mapping->writeback_index = i;
1249 while (i <= last_index && defrag_count < max_to_defrag &&
1250 (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
1251 PAGE_CACHE_SHIFT)) {
1253 * make sure we stop running if someone unmounts
1256 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1259 if (btrfs_defrag_cancelled(root->fs_info)) {
1260 printk(KERN_DEBUG "btrfs: defrag_file cancelled\n");
1265 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1266 extent_thresh, &last_len, &skip,
1267 &defrag_end, range->flags &
1268 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1271 * the should_defrag function tells us how much to skip
1272 * bump our counter by the suggested amount
1274 next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1275 i = max(i + 1, next);
1280 cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1281 PAGE_CACHE_SHIFT) - i;
1282 cluster = min(cluster, max_cluster);
1284 cluster = max_cluster;
1287 if (i + cluster > ra_index) {
1288 ra_index = max(i, ra_index);
1289 btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1291 ra_index += max_cluster;
1294 mutex_lock(&inode->i_mutex);
1295 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1296 BTRFS_I(inode)->force_compress = compress_type;
1297 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1299 mutex_unlock(&inode->i_mutex);
1303 defrag_count += ret;
1304 balance_dirty_pages_ratelimited(inode->i_mapping);
1305 mutex_unlock(&inode->i_mutex);
1308 if (newer_off == (u64)-1)
1314 newer_off = max(newer_off + 1,
1315 (u64)i << PAGE_CACHE_SHIFT);
1317 ret = find_new_extents(root, inode,
1318 newer_than, &newer_off,
1321 range->start = newer_off;
1322 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1329 last_len += ret << PAGE_CACHE_SHIFT;
1337 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
1338 filemap_flush(inode->i_mapping);
1340 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1341 /* the filemap_flush will queue IO into the worker threads, but
1342 * we have to make sure the IO is actually started and that
1343 * ordered extents get created before we return
1345 atomic_inc(&root->fs_info->async_submit_draining);
1346 while (atomic_read(&root->fs_info->nr_async_submits) ||
1347 atomic_read(&root->fs_info->async_delalloc_pages)) {
1348 wait_event(root->fs_info->async_submit_wait,
1349 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1350 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1352 atomic_dec(&root->fs_info->async_submit_draining);
1355 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1356 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1362 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1363 mutex_lock(&inode->i_mutex);
1364 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1365 mutex_unlock(&inode->i_mutex);
1373 static noinline int btrfs_ioctl_resize(struct file *file,
1379 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1380 struct btrfs_ioctl_vol_args *vol_args;
1381 struct btrfs_trans_handle *trans;
1382 struct btrfs_device *device = NULL;
1384 char *devstr = NULL;
1388 if (!capable(CAP_SYS_ADMIN))
1391 ret = mnt_want_write_file(file);
1395 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1397 mnt_drop_write_file(file);
1398 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1401 mutex_lock(&root->fs_info->volume_mutex);
1402 vol_args = memdup_user(arg, sizeof(*vol_args));
1403 if (IS_ERR(vol_args)) {
1404 ret = PTR_ERR(vol_args);
1408 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1410 sizestr = vol_args->name;
1411 devstr = strchr(sizestr, ':');
1414 sizestr = devstr + 1;
1416 devstr = vol_args->name;
1417 devid = simple_strtoull(devstr, &end, 10);
1422 printk(KERN_INFO "btrfs: resizing devid %llu\n", devid);
1425 device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1427 printk(KERN_INFO "btrfs: resizer unable to find device %llu\n",
1433 if (!device->writeable) {
1434 printk(KERN_INFO "btrfs: resizer unable to apply on "
1435 "readonly device %llu\n",
1441 if (!strcmp(sizestr, "max"))
1442 new_size = device->bdev->bd_inode->i_size;
1444 if (sizestr[0] == '-') {
1447 } else if (sizestr[0] == '+') {
1451 new_size = memparse(sizestr, NULL);
1452 if (new_size == 0) {
1458 if (device->is_tgtdev_for_dev_replace) {
1463 old_size = device->total_bytes;
1466 if (new_size > old_size) {
1470 new_size = old_size - new_size;
1471 } else if (mod > 0) {
1472 new_size = old_size + new_size;
1475 if (new_size < 256 * 1024 * 1024) {
1479 if (new_size > device->bdev->bd_inode->i_size) {
1484 do_div(new_size, root->sectorsize);
1485 new_size *= root->sectorsize;
1487 printk_in_rcu(KERN_INFO "btrfs: new size for %s is %llu\n",
1488 rcu_str_deref(device->name), new_size);
1490 if (new_size > old_size) {
1491 trans = btrfs_start_transaction(root, 0);
1492 if (IS_ERR(trans)) {
1493 ret = PTR_ERR(trans);
1496 ret = btrfs_grow_device(trans, device, new_size);
1497 btrfs_commit_transaction(trans, root);
1498 } else if (new_size < old_size) {
1499 ret = btrfs_shrink_device(device, new_size);
1500 } /* equal, nothing need to do */
1505 mutex_unlock(&root->fs_info->volume_mutex);
1506 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1507 mnt_drop_write_file(file);
1511 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1512 char *name, unsigned long fd, int subvol,
1513 u64 *transid, bool readonly,
1514 struct btrfs_qgroup_inherit *inherit)
1519 ret = mnt_want_write_file(file);
1523 namelen = strlen(name);
1524 if (strchr(name, '/')) {
1526 goto out_drop_write;
1529 if (name[0] == '.' &&
1530 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1532 goto out_drop_write;
1536 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1537 NULL, transid, readonly, inherit);
1539 struct fd src = fdget(fd);
1540 struct inode *src_inode;
1543 goto out_drop_write;
1546 src_inode = file_inode(src.file);
1547 if (src_inode->i_sb != file_inode(file)->i_sb) {
1548 printk(KERN_INFO "btrfs: Snapshot src from "
1552 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1553 BTRFS_I(src_inode)->root,
1554 transid, readonly, inherit);
1559 mnt_drop_write_file(file);
1564 static noinline int btrfs_ioctl_snap_create(struct file *file,
1565 void __user *arg, int subvol)
1567 struct btrfs_ioctl_vol_args *vol_args;
1570 vol_args = memdup_user(arg, sizeof(*vol_args));
1571 if (IS_ERR(vol_args))
1572 return PTR_ERR(vol_args);
1573 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1575 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1576 vol_args->fd, subvol,
1583 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1584 void __user *arg, int subvol)
1586 struct btrfs_ioctl_vol_args_v2 *vol_args;
1590 bool readonly = false;
1591 struct btrfs_qgroup_inherit *inherit = NULL;
1593 vol_args = memdup_user(arg, sizeof(*vol_args));
1594 if (IS_ERR(vol_args))
1595 return PTR_ERR(vol_args);
1596 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1598 if (vol_args->flags &
1599 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1600 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1605 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1607 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1609 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1610 if (vol_args->size > PAGE_CACHE_SIZE) {
1614 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1615 if (IS_ERR(inherit)) {
1616 ret = PTR_ERR(inherit);
1621 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1622 vol_args->fd, subvol, ptr,
1625 if (ret == 0 && ptr &&
1627 offsetof(struct btrfs_ioctl_vol_args_v2,
1628 transid), ptr, sizeof(*ptr)))
1636 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1639 struct inode *inode = file_inode(file);
1640 struct btrfs_root *root = BTRFS_I(inode)->root;
1644 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1647 down_read(&root->fs_info->subvol_sem);
1648 if (btrfs_root_readonly(root))
1649 flags |= BTRFS_SUBVOL_RDONLY;
1650 up_read(&root->fs_info->subvol_sem);
1652 if (copy_to_user(arg, &flags, sizeof(flags)))
1658 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1661 struct inode *inode = file_inode(file);
1662 struct btrfs_root *root = BTRFS_I(inode)->root;
1663 struct btrfs_trans_handle *trans;
1668 ret = mnt_want_write_file(file);
1672 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1674 goto out_drop_write;
1677 if (copy_from_user(&flags, arg, sizeof(flags))) {
1679 goto out_drop_write;
1682 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1684 goto out_drop_write;
1687 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1689 goto out_drop_write;
1692 if (!inode_owner_or_capable(inode)) {
1694 goto out_drop_write;
1697 down_write(&root->fs_info->subvol_sem);
1700 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1703 root_flags = btrfs_root_flags(&root->root_item);
1704 if (flags & BTRFS_SUBVOL_RDONLY)
1705 btrfs_set_root_flags(&root->root_item,
1706 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1708 btrfs_set_root_flags(&root->root_item,
1709 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1711 trans = btrfs_start_transaction(root, 1);
1712 if (IS_ERR(trans)) {
1713 ret = PTR_ERR(trans);
1717 ret = btrfs_update_root(trans, root->fs_info->tree_root,
1718 &root->root_key, &root->root_item);
1720 btrfs_commit_transaction(trans, root);
1723 btrfs_set_root_flags(&root->root_item, root_flags);
1725 up_write(&root->fs_info->subvol_sem);
1727 mnt_drop_write_file(file);
1733 * helper to check if the subvolume references other subvolumes
1735 static noinline int may_destroy_subvol(struct btrfs_root *root)
1737 struct btrfs_path *path;
1738 struct btrfs_dir_item *di;
1739 struct btrfs_key key;
1743 path = btrfs_alloc_path();
1747 /* Make sure this root isn't set as the default subvol */
1748 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1749 di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1750 dir_id, "default", 7, 0);
1751 if (di && !IS_ERR(di)) {
1752 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1753 if (key.objectid == root->root_key.objectid) {
1757 btrfs_release_path(path);
1760 key.objectid = root->root_key.objectid;
1761 key.type = BTRFS_ROOT_REF_KEY;
1762 key.offset = (u64)-1;
1764 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1771 if (path->slots[0] > 0) {
1773 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1774 if (key.objectid == root->root_key.objectid &&
1775 key.type == BTRFS_ROOT_REF_KEY)
1779 btrfs_free_path(path);
1783 static noinline int key_in_sk(struct btrfs_key *key,
1784 struct btrfs_ioctl_search_key *sk)
1786 struct btrfs_key test;
1789 test.objectid = sk->min_objectid;
1790 test.type = sk->min_type;
1791 test.offset = sk->min_offset;
1793 ret = btrfs_comp_cpu_keys(key, &test);
1797 test.objectid = sk->max_objectid;
1798 test.type = sk->max_type;
1799 test.offset = sk->max_offset;
1801 ret = btrfs_comp_cpu_keys(key, &test);
1807 static noinline int copy_to_sk(struct btrfs_root *root,
1808 struct btrfs_path *path,
1809 struct btrfs_key *key,
1810 struct btrfs_ioctl_search_key *sk,
1812 unsigned long *sk_offset,
1816 struct extent_buffer *leaf;
1817 struct btrfs_ioctl_search_header sh;
1818 unsigned long item_off;
1819 unsigned long item_len;
1825 leaf = path->nodes[0];
1826 slot = path->slots[0];
1827 nritems = btrfs_header_nritems(leaf);
1829 if (btrfs_header_generation(leaf) > sk->max_transid) {
1833 found_transid = btrfs_header_generation(leaf);
1835 for (i = slot; i < nritems; i++) {
1836 item_off = btrfs_item_ptr_offset(leaf, i);
1837 item_len = btrfs_item_size_nr(leaf, i);
1839 btrfs_item_key_to_cpu(leaf, key, i);
1840 if (!key_in_sk(key, sk))
1843 if (sizeof(sh) + item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
1846 if (sizeof(sh) + item_len + *sk_offset >
1847 BTRFS_SEARCH_ARGS_BUFSIZE) {
1852 sh.objectid = key->objectid;
1853 sh.offset = key->offset;
1854 sh.type = key->type;
1856 sh.transid = found_transid;
1858 /* copy search result header */
1859 memcpy(buf + *sk_offset, &sh, sizeof(sh));
1860 *sk_offset += sizeof(sh);
1863 char *p = buf + *sk_offset;
1865 read_extent_buffer(leaf, p,
1866 item_off, item_len);
1867 *sk_offset += item_len;
1871 if (*num_found >= sk->nr_items)
1876 if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1878 else if (key->type < (u8)-1 && key->type < sk->max_type) {
1881 } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1891 static noinline int search_ioctl(struct inode *inode,
1892 struct btrfs_ioctl_search_args *args)
1894 struct btrfs_root *root;
1895 struct btrfs_key key;
1896 struct btrfs_key max_key;
1897 struct btrfs_path *path;
1898 struct btrfs_ioctl_search_key *sk = &args->key;
1899 struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1902 unsigned long sk_offset = 0;
1904 path = btrfs_alloc_path();
1908 if (sk->tree_id == 0) {
1909 /* search the root of the inode that was passed */
1910 root = BTRFS_I(inode)->root;
1912 key.objectid = sk->tree_id;
1913 key.type = BTRFS_ROOT_ITEM_KEY;
1914 key.offset = (u64)-1;
1915 root = btrfs_read_fs_root_no_name(info, &key);
1917 printk(KERN_ERR "could not find root %llu\n",
1919 btrfs_free_path(path);
1924 key.objectid = sk->min_objectid;
1925 key.type = sk->min_type;
1926 key.offset = sk->min_offset;
1928 max_key.objectid = sk->max_objectid;
1929 max_key.type = sk->max_type;
1930 max_key.offset = sk->max_offset;
1932 path->keep_locks = 1;
1935 ret = btrfs_search_forward(root, &key, &max_key, path,
1942 ret = copy_to_sk(root, path, &key, sk, args->buf,
1943 &sk_offset, &num_found);
1944 btrfs_release_path(path);
1945 if (ret || num_found >= sk->nr_items)
1951 sk->nr_items = num_found;
1952 btrfs_free_path(path);
1956 static noinline int btrfs_ioctl_tree_search(struct file *file,
1959 struct btrfs_ioctl_search_args *args;
1960 struct inode *inode;
1963 if (!capable(CAP_SYS_ADMIN))
1966 args = memdup_user(argp, sizeof(*args));
1968 return PTR_ERR(args);
1970 inode = file_inode(file);
1971 ret = search_ioctl(inode, args);
1972 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1979 * Search INODE_REFs to identify path name of 'dirid' directory
1980 * in a 'tree_id' tree. and sets path name to 'name'.
1982 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
1983 u64 tree_id, u64 dirid, char *name)
1985 struct btrfs_root *root;
1986 struct btrfs_key key;
1992 struct btrfs_inode_ref *iref;
1993 struct extent_buffer *l;
1994 struct btrfs_path *path;
1996 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2001 path = btrfs_alloc_path();
2005 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
2007 key.objectid = tree_id;
2008 key.type = BTRFS_ROOT_ITEM_KEY;
2009 key.offset = (u64)-1;
2010 root = btrfs_read_fs_root_no_name(info, &key);
2012 printk(KERN_ERR "could not find root %llu\n", tree_id);
2017 key.objectid = dirid;
2018 key.type = BTRFS_INODE_REF_KEY;
2019 key.offset = (u64)-1;
2022 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2026 ret = btrfs_previous_item(root, path, dirid,
2027 BTRFS_INODE_REF_KEY);
2037 slot = path->slots[0];
2038 btrfs_item_key_to_cpu(l, &key, slot);
2040 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2041 len = btrfs_inode_ref_name_len(l, iref);
2043 total_len += len + 1;
2045 ret = -ENAMETOOLONG;
2050 read_extent_buffer(l, ptr,(unsigned long)(iref + 1), len);
2052 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2055 btrfs_release_path(path);
2056 key.objectid = key.offset;
2057 key.offset = (u64)-1;
2058 dirid = key.objectid;
2060 memmove(name, ptr, total_len);
2061 name[total_len]='\0';
2064 btrfs_free_path(path);
2068 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2071 struct btrfs_ioctl_ino_lookup_args *args;
2072 struct inode *inode;
2075 if (!capable(CAP_SYS_ADMIN))
2078 args = memdup_user(argp, sizeof(*args));
2080 return PTR_ERR(args);
2082 inode = file_inode(file);
2084 if (args->treeid == 0)
2085 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2087 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2088 args->treeid, args->objectid,
2091 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2098 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2101 struct dentry *parent = fdentry(file);
2102 struct dentry *dentry;
2103 struct inode *dir = parent->d_inode;
2104 struct inode *inode;
2105 struct btrfs_root *root = BTRFS_I(dir)->root;
2106 struct btrfs_root *dest = NULL;
2107 struct btrfs_ioctl_vol_args *vol_args;
2108 struct btrfs_trans_handle *trans;
2109 struct btrfs_block_rsv block_rsv;
2110 u64 qgroup_reserved;
2115 vol_args = memdup_user(arg, sizeof(*vol_args));
2116 if (IS_ERR(vol_args))
2117 return PTR_ERR(vol_args);
2119 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2120 namelen = strlen(vol_args->name);
2121 if (strchr(vol_args->name, '/') ||
2122 strncmp(vol_args->name, "..", namelen) == 0) {
2127 err = mnt_want_write_file(file);
2131 err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2134 dentry = lookup_one_len(vol_args->name, parent, namelen);
2135 if (IS_ERR(dentry)) {
2136 err = PTR_ERR(dentry);
2137 goto out_unlock_dir;
2140 if (!dentry->d_inode) {
2145 inode = dentry->d_inode;
2146 dest = BTRFS_I(inode)->root;
2147 if (!capable(CAP_SYS_ADMIN)){
2149 * Regular user. Only allow this with a special mount
2150 * option, when the user has write+exec access to the
2151 * subvol root, and when rmdir(2) would have been
2154 * Note that this is _not_ check that the subvol is
2155 * empty or doesn't contain data that we wouldn't
2156 * otherwise be able to delete.
2158 * Users who want to delete empty subvols should try
2162 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2166 * Do not allow deletion if the parent dir is the same
2167 * as the dir to be deleted. That means the ioctl
2168 * must be called on the dentry referencing the root
2169 * of the subvol, not a random directory contained
2176 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2181 /* check if subvolume may be deleted by a user */
2182 err = btrfs_may_delete(dir, dentry, 1);
2186 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2191 mutex_lock(&inode->i_mutex);
2192 err = d_invalidate(dentry);
2196 down_write(&root->fs_info->subvol_sem);
2198 err = may_destroy_subvol(dest);
2202 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2204 * One for dir inode, two for dir entries, two for root
2207 err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2208 5, &qgroup_reserved, true);
2212 trans = btrfs_start_transaction(root, 0);
2213 if (IS_ERR(trans)) {
2214 err = PTR_ERR(trans);
2217 trans->block_rsv = &block_rsv;
2218 trans->bytes_reserved = block_rsv.size;
2220 ret = btrfs_unlink_subvol(trans, root, dir,
2221 dest->root_key.objectid,
2222 dentry->d_name.name,
2223 dentry->d_name.len);
2226 btrfs_abort_transaction(trans, root, ret);
2230 btrfs_record_root_in_trans(trans, dest);
2232 memset(&dest->root_item.drop_progress, 0,
2233 sizeof(dest->root_item.drop_progress));
2234 dest->root_item.drop_level = 0;
2235 btrfs_set_root_refs(&dest->root_item, 0);
2237 if (!xchg(&dest->orphan_item_inserted, 1)) {
2238 ret = btrfs_insert_orphan_item(trans,
2239 root->fs_info->tree_root,
2240 dest->root_key.objectid);
2242 btrfs_abort_transaction(trans, root, ret);
2248 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2249 dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2250 dest->root_key.objectid);
2251 if (ret && ret != -ENOENT) {
2252 btrfs_abort_transaction(trans, root, ret);
2256 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2257 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2258 dest->root_item.received_uuid,
2259 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2260 dest->root_key.objectid);
2261 if (ret && ret != -ENOENT) {
2262 btrfs_abort_transaction(trans, root, ret);
2269 trans->block_rsv = NULL;
2270 trans->bytes_reserved = 0;
2271 ret = btrfs_end_transaction(trans, root);
2274 inode->i_flags |= S_DEAD;
2276 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2278 up_write(&root->fs_info->subvol_sem);
2280 mutex_unlock(&inode->i_mutex);
2282 shrink_dcache_sb(root->fs_info->sb);
2283 btrfs_invalidate_inodes(dest);
2287 if (dest->cache_inode) {
2288 iput(dest->cache_inode);
2289 dest->cache_inode = NULL;
2295 mutex_unlock(&dir->i_mutex);
2296 mnt_drop_write_file(file);
2302 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2304 struct inode *inode = file_inode(file);
2305 struct btrfs_root *root = BTRFS_I(inode)->root;
2306 struct btrfs_ioctl_defrag_range_args *range;
2309 ret = mnt_want_write_file(file);
2313 if (btrfs_root_readonly(root)) {
2318 switch (inode->i_mode & S_IFMT) {
2320 if (!capable(CAP_SYS_ADMIN)) {
2324 ret = btrfs_defrag_root(root);
2327 ret = btrfs_defrag_root(root->fs_info->extent_root);
2330 if (!(file->f_mode & FMODE_WRITE)) {
2335 range = kzalloc(sizeof(*range), GFP_KERNEL);
2342 if (copy_from_user(range, argp,
2348 /* compression requires us to start the IO */
2349 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2350 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2351 range->extent_thresh = (u32)-1;
2354 /* the rest are all set to zero by kzalloc */
2355 range->len = (u64)-1;
2357 ret = btrfs_defrag_file(file_inode(file), file,
2367 mnt_drop_write_file(file);
2371 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2373 struct btrfs_ioctl_vol_args *vol_args;
2376 if (!capable(CAP_SYS_ADMIN))
2379 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2381 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2384 mutex_lock(&root->fs_info->volume_mutex);
2385 vol_args = memdup_user(arg, sizeof(*vol_args));
2386 if (IS_ERR(vol_args)) {
2387 ret = PTR_ERR(vol_args);
2391 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2392 ret = btrfs_init_new_device(root, vol_args->name);
2396 mutex_unlock(&root->fs_info->volume_mutex);
2397 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2401 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2403 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2404 struct btrfs_ioctl_vol_args *vol_args;
2407 if (!capable(CAP_SYS_ADMIN))
2410 ret = mnt_want_write_file(file);
2414 vol_args = memdup_user(arg, sizeof(*vol_args));
2415 if (IS_ERR(vol_args)) {
2416 ret = PTR_ERR(vol_args);
2420 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2422 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2424 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2428 mutex_lock(&root->fs_info->volume_mutex);
2429 ret = btrfs_rm_device(root, vol_args->name);
2430 mutex_unlock(&root->fs_info->volume_mutex);
2431 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2435 mnt_drop_write_file(file);
2439 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2441 struct btrfs_ioctl_fs_info_args *fi_args;
2442 struct btrfs_device *device;
2443 struct btrfs_device *next;
2444 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2447 if (!capable(CAP_SYS_ADMIN))
2450 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2454 mutex_lock(&fs_devices->device_list_mutex);
2455 fi_args->num_devices = fs_devices->num_devices;
2456 memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2458 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2459 if (device->devid > fi_args->max_id)
2460 fi_args->max_id = device->devid;
2462 mutex_unlock(&fs_devices->device_list_mutex);
2464 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2471 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2473 struct btrfs_ioctl_dev_info_args *di_args;
2474 struct btrfs_device *dev;
2475 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2477 char *s_uuid = NULL;
2479 if (!capable(CAP_SYS_ADMIN))
2482 di_args = memdup_user(arg, sizeof(*di_args));
2483 if (IS_ERR(di_args))
2484 return PTR_ERR(di_args);
2486 if (!btrfs_is_empty_uuid(di_args->uuid))
2487 s_uuid = di_args->uuid;
2489 mutex_lock(&fs_devices->device_list_mutex);
2490 dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2497 di_args->devid = dev->devid;
2498 di_args->bytes_used = dev->bytes_used;
2499 di_args->total_bytes = dev->total_bytes;
2500 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2502 struct rcu_string *name;
2505 name = rcu_dereference(dev->name);
2506 strncpy(di_args->path, name->str, sizeof(di_args->path));
2508 di_args->path[sizeof(di_args->path) - 1] = 0;
2510 di_args->path[0] = '\0';
2514 mutex_unlock(&fs_devices->device_list_mutex);
2515 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2522 static struct page *extent_same_get_page(struct inode *inode, u64 off)
2526 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2528 index = off >> PAGE_CACHE_SHIFT;
2530 page = grab_cache_page(inode->i_mapping, index);
2534 if (!PageUptodate(page)) {
2535 if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2539 if (!PageUptodate(page)) {
2541 page_cache_release(page);
2550 static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
2552 /* do any pending delalloc/csum calc on src, one way or
2553 another, and lock file content */
2555 struct btrfs_ordered_extent *ordered;
2556 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2557 ordered = btrfs_lookup_first_ordered_extent(inode,
2560 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2561 off + len - 1, EXTENT_DELALLOC, 0, NULL))
2563 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2565 btrfs_put_ordered_extent(ordered);
2566 btrfs_wait_ordered_range(inode, off, len);
2570 static void btrfs_double_unlock(struct inode *inode1, u64 loff1,
2571 struct inode *inode2, u64 loff2, u64 len)
2573 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2574 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2576 mutex_unlock(&inode1->i_mutex);
2577 mutex_unlock(&inode2->i_mutex);
2580 static void btrfs_double_lock(struct inode *inode1, u64 loff1,
2581 struct inode *inode2, u64 loff2, u64 len)
2583 if (inode1 < inode2) {
2584 swap(inode1, inode2);
2588 mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2589 lock_extent_range(inode1, loff1, len);
2590 if (inode1 != inode2) {
2591 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2592 lock_extent_range(inode2, loff2, len);
2596 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2597 u64 dst_loff, u64 len)
2600 struct page *src_page, *dst_page;
2601 unsigned int cmp_len = PAGE_CACHE_SIZE;
2602 void *addr, *dst_addr;
2605 if (len < PAGE_CACHE_SIZE)
2608 src_page = extent_same_get_page(src, loff);
2611 dst_page = extent_same_get_page(dst, dst_loff);
2613 page_cache_release(src_page);
2616 addr = kmap_atomic(src_page);
2617 dst_addr = kmap_atomic(dst_page);
2619 flush_dcache_page(src_page);
2620 flush_dcache_page(dst_page);
2622 if (memcmp(addr, dst_addr, cmp_len))
2623 ret = BTRFS_SAME_DATA_DIFFERS;
2625 kunmap_atomic(addr);
2626 kunmap_atomic(dst_addr);
2627 page_cache_release(src_page);
2628 page_cache_release(dst_page);
2634 dst_loff += cmp_len;
2641 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 len)
2643 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2645 if (off + len > inode->i_size || off + len < off)
2647 /* Check that we are block aligned - btrfs_clone() requires this */
2648 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2654 static int btrfs_extent_same(struct inode *src, u64 loff, u64 len,
2655 struct inode *dst, u64 dst_loff)
2660 * btrfs_clone() can't handle extents in the same file
2661 * yet. Once that works, we can drop this check and replace it
2662 * with a check for the same inode, but overlapping extents.
2667 btrfs_double_lock(src, loff, dst, dst_loff, len);
2669 ret = extent_same_check_offsets(src, loff, len);
2673 ret = extent_same_check_offsets(dst, dst_loff, len);
2677 /* don't make the dst file partly checksummed */
2678 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2679 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
2684 ret = btrfs_cmp_data(src, loff, dst, dst_loff, len);
2686 ret = btrfs_clone(src, dst, loff, len, len, dst_loff);
2689 btrfs_double_unlock(src, loff, dst, dst_loff, len);
2694 #define BTRFS_MAX_DEDUPE_LEN (16 * 1024 * 1024)
2696 static long btrfs_ioctl_file_extent_same(struct file *file,
2699 struct btrfs_ioctl_same_args *args = argp;
2700 struct btrfs_ioctl_same_args same;
2701 struct btrfs_ioctl_same_extent_info info;
2702 struct inode *src = file->f_dentry->d_inode;
2703 struct file *dst_file = NULL;
2709 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
2710 bool is_admin = capable(CAP_SYS_ADMIN);
2712 if (!(file->f_mode & FMODE_READ))
2715 ret = mnt_want_write_file(file);
2719 if (copy_from_user(&same,
2720 (struct btrfs_ioctl_same_args __user *)argp,
2726 off = same.logical_offset;
2730 * Limit the total length we will dedupe for each operation.
2731 * This is intended to bound the total time spent in this
2732 * ioctl to something sane.
2734 if (len > BTRFS_MAX_DEDUPE_LEN)
2735 len = BTRFS_MAX_DEDUPE_LEN;
2737 if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
2739 * Btrfs does not support blocksize < page_size. As a
2740 * result, btrfs_cmp_data() won't correctly handle
2741 * this situation without an update.
2748 if (S_ISDIR(src->i_mode))
2752 if (!S_ISREG(src->i_mode))
2756 for (i = 0; i < same.dest_count; i++) {
2757 if (copy_from_user(&info, &args->info[i], sizeof(info))) {
2762 info.bytes_deduped = 0;
2764 dst_file = fget(info.fd);
2766 info.status = -EBADF;
2770 if (!(is_admin || (dst_file->f_mode & FMODE_WRITE))) {
2771 info.status = -EINVAL;
2775 info.status = -EXDEV;
2776 if (file->f_path.mnt != dst_file->f_path.mnt)
2779 dst = dst_file->f_dentry->d_inode;
2780 if (src->i_sb != dst->i_sb)
2783 if (S_ISDIR(dst->i_mode)) {
2784 info.status = -EISDIR;
2788 if (!S_ISREG(dst->i_mode)) {
2789 info.status = -EACCES;
2793 info.status = btrfs_extent_same(src, off, len, dst,
2794 info.logical_offset);
2795 if (info.status == 0)
2796 info.bytes_deduped += len;
2802 if (__put_user_unaligned(info.status, &args->info[i].status) ||
2803 __put_user_unaligned(info.bytes_deduped,
2804 &args->info[i].bytes_deduped)) {
2811 mnt_drop_write_file(file);
2816 * btrfs_clone() - clone a range from inode file to another
2818 * @src: Inode to clone from
2819 * @inode: Inode to clone to
2820 * @off: Offset within source to start clone from
2821 * @olen: Original length, passed by user, of range to clone
2822 * @olen_aligned: Block-aligned value of olen, extent_same uses
2823 * identical values here
2824 * @destoff: Offset within @inode to start clone
2826 static int btrfs_clone(struct inode *src, struct inode *inode,
2827 u64 off, u64 olen, u64 olen_aligned, u64 destoff)
2829 struct btrfs_root *root = BTRFS_I(inode)->root;
2830 struct btrfs_path *path = NULL;
2831 struct extent_buffer *leaf;
2832 struct btrfs_trans_handle *trans;
2834 struct btrfs_key key;
2838 u64 len = olen_aligned;
2841 buf = vmalloc(btrfs_level_size(root, 0));
2845 path = btrfs_alloc_path();
2853 key.objectid = btrfs_ino(src);
2854 key.type = BTRFS_EXTENT_DATA_KEY;
2859 * note the key will change type as we walk through the
2862 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
2867 nritems = btrfs_header_nritems(path->nodes[0]);
2868 if (path->slots[0] >= nritems) {
2869 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
2874 nritems = btrfs_header_nritems(path->nodes[0]);
2876 leaf = path->nodes[0];
2877 slot = path->slots[0];
2879 btrfs_item_key_to_cpu(leaf, &key, slot);
2880 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
2881 key.objectid != btrfs_ino(src))
2884 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
2885 struct btrfs_file_extent_item *extent;
2888 struct btrfs_key new_key;
2889 u64 disko = 0, diskl = 0;
2890 u64 datao = 0, datal = 0;
2894 size = btrfs_item_size_nr(leaf, slot);
2895 read_extent_buffer(leaf, buf,
2896 btrfs_item_ptr_offset(leaf, slot),
2899 extent = btrfs_item_ptr(leaf, slot,
2900 struct btrfs_file_extent_item);
2901 comp = btrfs_file_extent_compression(leaf, extent);
2902 type = btrfs_file_extent_type(leaf, extent);
2903 if (type == BTRFS_FILE_EXTENT_REG ||
2904 type == BTRFS_FILE_EXTENT_PREALLOC) {
2905 disko = btrfs_file_extent_disk_bytenr(leaf,
2907 diskl = btrfs_file_extent_disk_num_bytes(leaf,
2909 datao = btrfs_file_extent_offset(leaf, extent);
2910 datal = btrfs_file_extent_num_bytes(leaf,
2912 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2913 /* take upper bound, may be compressed */
2914 datal = btrfs_file_extent_ram_bytes(leaf,
2917 btrfs_release_path(path);
2919 if (key.offset + datal <= off ||
2920 key.offset >= off + len - 1)
2923 memcpy(&new_key, &key, sizeof(new_key));
2924 new_key.objectid = btrfs_ino(inode);
2925 if (off <= key.offset)
2926 new_key.offset = key.offset + destoff - off;
2928 new_key.offset = destoff;
2931 * 1 - adjusting old extent (we may have to split it)
2932 * 1 - add new extent
2935 trans = btrfs_start_transaction(root, 3);
2936 if (IS_ERR(trans)) {
2937 ret = PTR_ERR(trans);
2941 if (type == BTRFS_FILE_EXTENT_REG ||
2942 type == BTRFS_FILE_EXTENT_PREALLOC) {
2944 * a | --- range to clone ---| b
2945 * | ------------- extent ------------- |
2948 /* substract range b */
2949 if (key.offset + datal > off + len)
2950 datal = off + len - key.offset;
2952 /* substract range a */
2953 if (off > key.offset) {
2954 datao += off - key.offset;
2955 datal -= off - key.offset;
2958 ret = btrfs_drop_extents(trans, root, inode,
2960 new_key.offset + datal,
2963 btrfs_abort_transaction(trans, root,
2965 btrfs_end_transaction(trans, root);
2969 ret = btrfs_insert_empty_item(trans, root, path,
2972 btrfs_abort_transaction(trans, root,
2974 btrfs_end_transaction(trans, root);
2978 leaf = path->nodes[0];
2979 slot = path->slots[0];
2980 write_extent_buffer(leaf, buf,
2981 btrfs_item_ptr_offset(leaf, slot),
2984 extent = btrfs_item_ptr(leaf, slot,
2985 struct btrfs_file_extent_item);
2987 /* disko == 0 means it's a hole */
2991 btrfs_set_file_extent_offset(leaf, extent,
2993 btrfs_set_file_extent_num_bytes(leaf, extent,
2996 inode_add_bytes(inode, datal);
2997 ret = btrfs_inc_extent_ref(trans, root,
2999 root->root_key.objectid,
3001 new_key.offset - datao,
3004 btrfs_abort_transaction(trans,
3007 btrfs_end_transaction(trans,
3013 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3016 if (off > key.offset) {
3017 skip = off - key.offset;
3018 new_key.offset += skip;
3021 if (key.offset + datal > off + len)
3022 trim = key.offset + datal - (off + len);
3024 if (comp && (skip || trim)) {
3026 btrfs_end_transaction(trans, root);
3029 size -= skip + trim;
3030 datal -= skip + trim;
3032 ret = btrfs_drop_extents(trans, root, inode,
3034 new_key.offset + datal,
3037 btrfs_abort_transaction(trans, root,
3039 btrfs_end_transaction(trans, root);
3043 ret = btrfs_insert_empty_item(trans, root, path,
3046 btrfs_abort_transaction(trans, root,
3048 btrfs_end_transaction(trans, root);
3054 btrfs_file_extent_calc_inline_size(0);
3055 memmove(buf+start, buf+start+skip,
3059 leaf = path->nodes[0];
3060 slot = path->slots[0];
3061 write_extent_buffer(leaf, buf,
3062 btrfs_item_ptr_offset(leaf, slot),
3064 inode_add_bytes(inode, datal);
3067 btrfs_mark_buffer_dirty(leaf);
3068 btrfs_release_path(path);
3070 inode_inc_iversion(inode);
3071 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3074 * we round up to the block size at eof when
3075 * determining which extents to clone above,
3076 * but shouldn't round up the file size
3078 endoff = new_key.offset + datal;
3079 if (endoff > destoff+olen)
3080 endoff = destoff+olen;
3081 if (endoff > inode->i_size)
3082 btrfs_i_size_write(inode, endoff);
3084 ret = btrfs_update_inode(trans, root, inode);
3086 btrfs_abort_transaction(trans, root, ret);
3087 btrfs_end_transaction(trans, root);
3090 ret = btrfs_end_transaction(trans, root);
3093 btrfs_release_path(path);
3099 btrfs_release_path(path);
3100 btrfs_free_path(path);
3105 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
3106 u64 off, u64 olen, u64 destoff)
3108 struct inode *inode = fdentry(file)->d_inode;
3109 struct btrfs_root *root = BTRFS_I(inode)->root;
3114 u64 bs = root->fs_info->sb->s_blocksize;
3119 * - split compressed inline extents. annoying: we need to
3120 * decompress into destination's address_space (the file offset
3121 * may change, so source mapping won't do), then recompress (or
3122 * otherwise reinsert) a subrange.
3123 * - allow ranges within the same file to be cloned (provided
3124 * they don't overlap)?
3127 /* the destination must be opened for writing */
3128 if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
3131 if (btrfs_root_readonly(root))
3134 ret = mnt_want_write_file(file);
3138 src_file = fdget(srcfd);
3139 if (!src_file.file) {
3141 goto out_drop_write;
3145 if (src_file.file->f_path.mnt != file->f_path.mnt)
3148 src = file_inode(src_file.file);
3154 /* the src must be open for reading */
3155 if (!(src_file.file->f_mode & FMODE_READ))
3158 /* don't make the dst file partly checksummed */
3159 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3160 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
3164 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3168 if (src->i_sb != inode->i_sb)
3173 mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
3174 mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
3176 mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
3177 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
3180 mutex_lock(&src->i_mutex);
3183 /* determine range to clone */
3185 if (off + len > src->i_size || off + len < off)
3188 olen = len = src->i_size - off;
3189 /* if we extend to eof, continue to block boundary */
3190 if (off + len == src->i_size)
3191 len = ALIGN(src->i_size, bs) - off;
3193 /* verify the end result is block aligned */
3194 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3195 !IS_ALIGNED(destoff, bs))
3198 /* verify if ranges are overlapped within the same file */
3200 if (destoff + len > off && destoff < off + len)
3204 if (destoff > inode->i_size) {
3205 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3210 /* truncate page cache pages from target inode range */
3211 truncate_inode_pages_range(&inode->i_data, destoff,
3212 PAGE_CACHE_ALIGN(destoff + len) - 1);
3214 lock_extent_range(src, off, len);
3216 ret = btrfs_clone(src, inode, off, olen, len, destoff);
3218 unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
3220 mutex_unlock(&src->i_mutex);
3222 mutex_unlock(&inode->i_mutex);
3226 mnt_drop_write_file(file);
3230 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
3232 struct btrfs_ioctl_clone_range_args args;
3234 if (copy_from_user(&args, argp, sizeof(args)))
3236 return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
3237 args.src_length, args.dest_offset);
3241 * there are many ways the trans_start and trans_end ioctls can lead
3242 * to deadlocks. They should only be used by applications that
3243 * basically own the machine, and have a very in depth understanding
3244 * of all the possible deadlocks and enospc problems.
3246 static long btrfs_ioctl_trans_start(struct file *file)
3248 struct inode *inode = file_inode(file);
3249 struct btrfs_root *root = BTRFS_I(inode)->root;
3250 struct btrfs_trans_handle *trans;
3254 if (!capable(CAP_SYS_ADMIN))
3258 if (file->private_data)
3262 if (btrfs_root_readonly(root))
3265 ret = mnt_want_write_file(file);
3269 atomic_inc(&root->fs_info->open_ioctl_trans);
3272 trans = btrfs_start_ioctl_transaction(root);
3276 file->private_data = trans;
3280 atomic_dec(&root->fs_info->open_ioctl_trans);
3281 mnt_drop_write_file(file);
3286 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3288 struct inode *inode = file_inode(file);
3289 struct btrfs_root *root = BTRFS_I(inode)->root;
3290 struct btrfs_root *new_root;
3291 struct btrfs_dir_item *di;
3292 struct btrfs_trans_handle *trans;
3293 struct btrfs_path *path;
3294 struct btrfs_key location;
3295 struct btrfs_disk_key disk_key;
3300 if (!capable(CAP_SYS_ADMIN))
3303 ret = mnt_want_write_file(file);
3307 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3313 objectid = root->root_key.objectid;
3315 location.objectid = objectid;
3316 location.type = BTRFS_ROOT_ITEM_KEY;
3317 location.offset = (u64)-1;
3319 new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
3320 if (IS_ERR(new_root)) {
3321 ret = PTR_ERR(new_root);
3325 path = btrfs_alloc_path();
3330 path->leave_spinning = 1;
3332 trans = btrfs_start_transaction(root, 1);
3333 if (IS_ERR(trans)) {
3334 btrfs_free_path(path);
3335 ret = PTR_ERR(trans);
3339 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
3340 di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
3341 dir_id, "default", 7, 1);
3342 if (IS_ERR_OR_NULL(di)) {
3343 btrfs_free_path(path);
3344 btrfs_end_transaction(trans, root);
3345 printk(KERN_ERR "Umm, you don't have the default dir item, "
3346 "this isn't going to work\n");
3351 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3352 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3353 btrfs_mark_buffer_dirty(path->nodes[0]);
3354 btrfs_free_path(path);
3356 btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
3357 btrfs_end_transaction(trans, root);
3359 mnt_drop_write_file(file);
3363 void btrfs_get_block_group_info(struct list_head *groups_list,
3364 struct btrfs_ioctl_space_info *space)
3366 struct btrfs_block_group_cache *block_group;
3368 space->total_bytes = 0;
3369 space->used_bytes = 0;
3371 list_for_each_entry(block_group, groups_list, list) {
3372 space->flags = block_group->flags;
3373 space->total_bytes += block_group->key.offset;
3374 space->used_bytes +=
3375 btrfs_block_group_used(&block_group->item);
3379 static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
3381 struct btrfs_ioctl_space_args space_args;
3382 struct btrfs_ioctl_space_info space;
3383 struct btrfs_ioctl_space_info *dest;
3384 struct btrfs_ioctl_space_info *dest_orig;
3385 struct btrfs_ioctl_space_info __user *user_dest;
3386 struct btrfs_space_info *info;
3387 u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
3388 BTRFS_BLOCK_GROUP_SYSTEM,
3389 BTRFS_BLOCK_GROUP_METADATA,
3390 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
3397 if (copy_from_user(&space_args,
3398 (struct btrfs_ioctl_space_args __user *)arg,
3399 sizeof(space_args)))
3402 for (i = 0; i < num_types; i++) {
3403 struct btrfs_space_info *tmp;
3407 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3409 if (tmp->flags == types[i]) {
3419 down_read(&info->groups_sem);
3420 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3421 if (!list_empty(&info->block_groups[c]))
3424 up_read(&info->groups_sem);
3427 /* space_slots == 0 means they are asking for a count */
3428 if (space_args.space_slots == 0) {
3429 space_args.total_spaces = slot_count;
3433 slot_count = min_t(u64, space_args.space_slots, slot_count);
3435 alloc_size = sizeof(*dest) * slot_count;
3437 /* we generally have at most 6 or so space infos, one for each raid
3438 * level. So, a whole page should be more than enough for everyone
3440 if (alloc_size > PAGE_CACHE_SIZE)
3443 space_args.total_spaces = 0;
3444 dest = kmalloc(alloc_size, GFP_NOFS);
3449 /* now we have a buffer to copy into */
3450 for (i = 0; i < num_types; i++) {
3451 struct btrfs_space_info *tmp;
3458 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3460 if (tmp->flags == types[i]) {
3469 down_read(&info->groups_sem);
3470 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3471 if (!list_empty(&info->block_groups[c])) {
3472 btrfs_get_block_group_info(
3473 &info->block_groups[c], &space);
3474 memcpy(dest, &space, sizeof(space));
3476 space_args.total_spaces++;
3482 up_read(&info->groups_sem);
3485 user_dest = (struct btrfs_ioctl_space_info __user *)
3486 (arg + sizeof(struct btrfs_ioctl_space_args));
3488 if (copy_to_user(user_dest, dest_orig, alloc_size))
3493 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3500 * there are many ways the trans_start and trans_end ioctls can lead
3501 * to deadlocks. They should only be used by applications that
3502 * basically own the machine, and have a very in depth understanding
3503 * of all the possible deadlocks and enospc problems.
3505 long btrfs_ioctl_trans_end(struct file *file)
3507 struct inode *inode = file_inode(file);
3508 struct btrfs_root *root = BTRFS_I(inode)->root;
3509 struct btrfs_trans_handle *trans;
3511 trans = file->private_data;
3514 file->private_data = NULL;
3516 btrfs_end_transaction(trans, root);
3518 atomic_dec(&root->fs_info->open_ioctl_trans);
3520 mnt_drop_write_file(file);
3524 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3527 struct btrfs_trans_handle *trans;
3531 trans = btrfs_attach_transaction_barrier(root);
3532 if (IS_ERR(trans)) {
3533 if (PTR_ERR(trans) != -ENOENT)
3534 return PTR_ERR(trans);
3536 /* No running transaction, don't bother */
3537 transid = root->fs_info->last_trans_committed;
3540 transid = trans->transid;
3541 ret = btrfs_commit_transaction_async(trans, root, 0);
3543 btrfs_end_transaction(trans, root);
3548 if (copy_to_user(argp, &transid, sizeof(transid)))
3553 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
3559 if (copy_from_user(&transid, argp, sizeof(transid)))
3562 transid = 0; /* current trans */
3564 return btrfs_wait_for_commit(root, transid);
3567 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3569 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3570 struct btrfs_ioctl_scrub_args *sa;
3573 if (!capable(CAP_SYS_ADMIN))
3576 sa = memdup_user(arg, sizeof(*sa));
3580 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3581 ret = mnt_want_write_file(file);
3586 ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
3587 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3590 if (copy_to_user(arg, sa, sizeof(*sa)))
3593 if (!(sa->flags & BTRFS_SCRUB_READONLY))
3594 mnt_drop_write_file(file);
3600 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
3602 if (!capable(CAP_SYS_ADMIN))
3605 return btrfs_scrub_cancel(root->fs_info);
3608 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
3611 struct btrfs_ioctl_scrub_args *sa;
3614 if (!capable(CAP_SYS_ADMIN))
3617 sa = memdup_user(arg, sizeof(*sa));
3621 ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
3623 if (copy_to_user(arg, sa, sizeof(*sa)))
3630 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
3633 struct btrfs_ioctl_get_dev_stats *sa;
3636 sa = memdup_user(arg, sizeof(*sa));
3640 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3645 ret = btrfs_get_dev_stats(root, sa);
3647 if (copy_to_user(arg, sa, sizeof(*sa)))
3654 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
3656 struct btrfs_ioctl_dev_replace_args *p;
3659 if (!capable(CAP_SYS_ADMIN))
3662 p = memdup_user(arg, sizeof(*p));
3667 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3668 if (root->fs_info->sb->s_flags & MS_RDONLY)
3672 &root->fs_info->mutually_exclusive_operation_running,
3674 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3676 ret = btrfs_dev_replace_start(root, p);
3678 &root->fs_info->mutually_exclusive_operation_running,
3682 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3683 btrfs_dev_replace_status(root->fs_info, p);
3686 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3687 ret = btrfs_dev_replace_cancel(root->fs_info, p);
3694 if (copy_to_user(arg, p, sizeof(*p)))
3701 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3707 struct btrfs_ioctl_ino_path_args *ipa = NULL;
3708 struct inode_fs_paths *ipath = NULL;
3709 struct btrfs_path *path;
3711 if (!capable(CAP_DAC_READ_SEARCH))
3714 path = btrfs_alloc_path();
3720 ipa = memdup_user(arg, sizeof(*ipa));
3727 size = min_t(u32, ipa->size, 4096);
3728 ipath = init_ipath(size, root, path);
3729 if (IS_ERR(ipath)) {
3730 ret = PTR_ERR(ipath);
3735 ret = paths_from_inode(ipa->inum, ipath);
3739 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3740 rel_ptr = ipath->fspath->val[i] -
3741 (u64)(unsigned long)ipath->fspath->val;
3742 ipath->fspath->val[i] = rel_ptr;
3745 ret = copy_to_user((void *)(unsigned long)ipa->fspath,
3746 (void *)(unsigned long)ipath->fspath, size);
3753 btrfs_free_path(path);
3760 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3762 struct btrfs_data_container *inodes = ctx;
3763 const size_t c = 3 * sizeof(u64);
3765 if (inodes->bytes_left >= c) {
3766 inodes->bytes_left -= c;
3767 inodes->val[inodes->elem_cnt] = inum;
3768 inodes->val[inodes->elem_cnt + 1] = offset;
3769 inodes->val[inodes->elem_cnt + 2] = root;
3770 inodes->elem_cnt += 3;
3772 inodes->bytes_missing += c - inodes->bytes_left;
3773 inodes->bytes_left = 0;
3774 inodes->elem_missed += 3;
3780 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
3785 struct btrfs_ioctl_logical_ino_args *loi;
3786 struct btrfs_data_container *inodes = NULL;
3787 struct btrfs_path *path = NULL;
3789 if (!capable(CAP_SYS_ADMIN))
3792 loi = memdup_user(arg, sizeof(*loi));
3799 path = btrfs_alloc_path();
3805 size = min_t(u32, loi->size, 64 * 1024);
3806 inodes = init_data_container(size);
3807 if (IS_ERR(inodes)) {
3808 ret = PTR_ERR(inodes);
3813 ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
3814 build_ino_list, inodes);
3820 ret = copy_to_user((void *)(unsigned long)loi->inodes,
3821 (void *)(unsigned long)inodes, size);
3826 btrfs_free_path(path);
3833 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
3834 struct btrfs_ioctl_balance_args *bargs)
3836 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3838 bargs->flags = bctl->flags;
3840 if (atomic_read(&fs_info->balance_running))
3841 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3842 if (atomic_read(&fs_info->balance_pause_req))
3843 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3844 if (atomic_read(&fs_info->balance_cancel_req))
3845 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3847 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3848 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3849 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3852 spin_lock(&fs_info->balance_lock);
3853 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3854 spin_unlock(&fs_info->balance_lock);
3856 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3860 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3862 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3863 struct btrfs_fs_info *fs_info = root->fs_info;
3864 struct btrfs_ioctl_balance_args *bargs;
3865 struct btrfs_balance_control *bctl;
3866 bool need_unlock; /* for mut. excl. ops lock */
3869 if (!capable(CAP_SYS_ADMIN))
3872 ret = mnt_want_write_file(file);
3877 if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
3878 mutex_lock(&fs_info->volume_mutex);
3879 mutex_lock(&fs_info->balance_mutex);
3885 * mut. excl. ops lock is locked. Three possibilites:
3886 * (1) some other op is running
3887 * (2) balance is running
3888 * (3) balance is paused -- special case (think resume)
3890 mutex_lock(&fs_info->balance_mutex);
3891 if (fs_info->balance_ctl) {
3892 /* this is either (2) or (3) */
3893 if (!atomic_read(&fs_info->balance_running)) {
3894 mutex_unlock(&fs_info->balance_mutex);
3895 if (!mutex_trylock(&fs_info->volume_mutex))
3897 mutex_lock(&fs_info->balance_mutex);
3899 if (fs_info->balance_ctl &&
3900 !atomic_read(&fs_info->balance_running)) {
3902 need_unlock = false;
3906 mutex_unlock(&fs_info->balance_mutex);
3907 mutex_unlock(&fs_info->volume_mutex);
3911 mutex_unlock(&fs_info->balance_mutex);
3917 mutex_unlock(&fs_info->balance_mutex);
3918 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3923 BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
3926 bargs = memdup_user(arg, sizeof(*bargs));
3927 if (IS_ERR(bargs)) {
3928 ret = PTR_ERR(bargs);
3932 if (bargs->flags & BTRFS_BALANCE_RESUME) {
3933 if (!fs_info->balance_ctl) {
3938 bctl = fs_info->balance_ctl;
3939 spin_lock(&fs_info->balance_lock);
3940 bctl->flags |= BTRFS_BALANCE_RESUME;
3941 spin_unlock(&fs_info->balance_lock);
3949 if (fs_info->balance_ctl) {
3954 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3960 bctl->fs_info = fs_info;
3962 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
3963 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
3964 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
3966 bctl->flags = bargs->flags;
3968 /* balance everything - no filters */
3969 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
3974 * Ownership of bctl and mutually_exclusive_operation_running
3975 * goes to to btrfs_balance. bctl is freed in __cancel_balance,
3976 * or, if restriper was paused all the way until unmount, in
3977 * free_fs_info. mutually_exclusive_operation_running is
3978 * cleared in __cancel_balance.
3980 need_unlock = false;
3982 ret = btrfs_balance(bctl, bargs);
3985 if (copy_to_user(arg, bargs, sizeof(*bargs)))
3992 mutex_unlock(&fs_info->balance_mutex);
3993 mutex_unlock(&fs_info->volume_mutex);
3995 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3997 mnt_drop_write_file(file);
4001 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4003 if (!capable(CAP_SYS_ADMIN))
4007 case BTRFS_BALANCE_CTL_PAUSE:
4008 return btrfs_pause_balance(root->fs_info);
4009 case BTRFS_BALANCE_CTL_CANCEL:
4010 return btrfs_cancel_balance(root->fs_info);
4016 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
4019 struct btrfs_fs_info *fs_info = root->fs_info;
4020 struct btrfs_ioctl_balance_args *bargs;
4023 if (!capable(CAP_SYS_ADMIN))
4026 mutex_lock(&fs_info->balance_mutex);
4027 if (!fs_info->balance_ctl) {
4032 bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
4038 update_ioctl_balance_args(fs_info, 1, bargs);
4040 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4045 mutex_unlock(&fs_info->balance_mutex);
4049 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4051 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4052 struct btrfs_ioctl_quota_ctl_args *sa;
4053 struct btrfs_trans_handle *trans = NULL;
4057 if (!capable(CAP_SYS_ADMIN))
4060 ret = mnt_want_write_file(file);
4064 sa = memdup_user(arg, sizeof(*sa));
4070 down_write(&root->fs_info->subvol_sem);
4071 trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
4072 if (IS_ERR(trans)) {
4073 ret = PTR_ERR(trans);
4078 case BTRFS_QUOTA_CTL_ENABLE:
4079 ret = btrfs_quota_enable(trans, root->fs_info);
4081 case BTRFS_QUOTA_CTL_DISABLE:
4082 ret = btrfs_quota_disable(trans, root->fs_info);
4089 err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
4094 up_write(&root->fs_info->subvol_sem);
4096 mnt_drop_write_file(file);
4100 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4102 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4103 struct btrfs_ioctl_qgroup_assign_args *sa;
4104 struct btrfs_trans_handle *trans;
4108 if (!capable(CAP_SYS_ADMIN))
4111 ret = mnt_want_write_file(file);
4115 sa = memdup_user(arg, sizeof(*sa));
4121 trans = btrfs_join_transaction(root);
4122 if (IS_ERR(trans)) {
4123 ret = PTR_ERR(trans);
4127 /* FIXME: check if the IDs really exist */
4129 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
4132 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
4136 err = btrfs_end_transaction(trans, root);
4143 mnt_drop_write_file(file);
4147 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4149 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4150 struct btrfs_ioctl_qgroup_create_args *sa;
4151 struct btrfs_trans_handle *trans;
4155 if (!capable(CAP_SYS_ADMIN))
4158 ret = mnt_want_write_file(file);
4162 sa = memdup_user(arg, sizeof(*sa));
4168 if (!sa->qgroupid) {
4173 trans = btrfs_join_transaction(root);
4174 if (IS_ERR(trans)) {
4175 ret = PTR_ERR(trans);
4179 /* FIXME: check if the IDs really exist */
4181 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid,
4184 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
4187 err = btrfs_end_transaction(trans, root);
4194 mnt_drop_write_file(file);
4198 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4200 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4201 struct btrfs_ioctl_qgroup_limit_args *sa;
4202 struct btrfs_trans_handle *trans;
4207 if (!capable(CAP_SYS_ADMIN))
4210 ret = mnt_want_write_file(file);
4214 sa = memdup_user(arg, sizeof(*sa));
4220 trans = btrfs_join_transaction(root);
4221 if (IS_ERR(trans)) {
4222 ret = PTR_ERR(trans);
4226 qgroupid = sa->qgroupid;
4228 /* take the current subvol as qgroup */
4229 qgroupid = root->root_key.objectid;
4232 /* FIXME: check if the IDs really exist */
4233 ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
4235 err = btrfs_end_transaction(trans, root);
4242 mnt_drop_write_file(file);
4246 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4248 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4249 struct btrfs_ioctl_quota_rescan_args *qsa;
4252 if (!capable(CAP_SYS_ADMIN))
4255 ret = mnt_want_write_file(file);
4259 qsa = memdup_user(arg, sizeof(*qsa));
4270 ret = btrfs_qgroup_rescan(root->fs_info);
4275 mnt_drop_write_file(file);
4279 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
4281 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4282 struct btrfs_ioctl_quota_rescan_args *qsa;
4285 if (!capable(CAP_SYS_ADMIN))
4288 qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
4292 if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4294 qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
4297 if (copy_to_user(arg, qsa, sizeof(*qsa)))
4304 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
4306 struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
4308 if (!capable(CAP_SYS_ADMIN))
4311 return btrfs_qgroup_wait_for_completion(root->fs_info);
4314 static long btrfs_ioctl_set_received_subvol(struct file *file,
4317 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4318 struct inode *inode = file_inode(file);
4319 struct btrfs_root *root = BTRFS_I(inode)->root;
4320 struct btrfs_root_item *root_item = &root->root_item;
4321 struct btrfs_trans_handle *trans;
4322 struct timespec ct = CURRENT_TIME;
4324 int received_uuid_changed;
4326 ret = mnt_want_write_file(file);
4330 down_write(&root->fs_info->subvol_sem);
4332 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
4337 if (btrfs_root_readonly(root)) {
4342 if (!inode_owner_or_capable(inode)) {
4347 sa = memdup_user(arg, sizeof(*sa));
4356 * 2 - uuid items (received uuid + subvol uuid)
4358 trans = btrfs_start_transaction(root, 3);
4359 if (IS_ERR(trans)) {
4360 ret = PTR_ERR(trans);
4365 sa->rtransid = trans->transid;
4366 sa->rtime.sec = ct.tv_sec;
4367 sa->rtime.nsec = ct.tv_nsec;
4369 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4371 if (received_uuid_changed &&
4372 !btrfs_is_empty_uuid(root_item->received_uuid))
4373 btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
4374 root_item->received_uuid,
4375 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4376 root->root_key.objectid);
4377 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4378 btrfs_set_root_stransid(root_item, sa->stransid);
4379 btrfs_set_root_rtransid(root_item, sa->rtransid);
4380 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4381 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4382 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4383 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4385 ret = btrfs_update_root(trans, root->fs_info->tree_root,
4386 &root->root_key, &root->root_item);
4388 btrfs_end_transaction(trans, root);
4391 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4392 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
4394 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4395 root->root_key.objectid);
4396 if (ret < 0 && ret != -EEXIST) {
4397 btrfs_abort_transaction(trans, root, ret);
4401 ret = btrfs_commit_transaction(trans, root);
4403 btrfs_abort_transaction(trans, root, ret);
4407 ret = copy_to_user(arg, sa, sizeof(*sa));
4413 up_write(&root->fs_info->subvol_sem);
4414 mnt_drop_write_file(file);
4418 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
4420 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4423 char label[BTRFS_LABEL_SIZE];
4425 spin_lock(&root->fs_info->super_lock);
4426 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4427 spin_unlock(&root->fs_info->super_lock);
4429 len = strnlen(label, BTRFS_LABEL_SIZE);
4431 if (len == BTRFS_LABEL_SIZE) {
4432 pr_warn("btrfs: label is too long, return the first %zu bytes\n",
4436 ret = copy_to_user(arg, label, len);
4438 return ret ? -EFAULT : 0;
4441 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4443 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4444 struct btrfs_super_block *super_block = root->fs_info->super_copy;
4445 struct btrfs_trans_handle *trans;
4446 char label[BTRFS_LABEL_SIZE];
4449 if (!capable(CAP_SYS_ADMIN))
4452 if (copy_from_user(label, arg, sizeof(label)))
4455 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4456 pr_err("btrfs: unable to set label with more than %d bytes\n",
4457 BTRFS_LABEL_SIZE - 1);
4461 ret = mnt_want_write_file(file);
4465 trans = btrfs_start_transaction(root, 0);
4466 if (IS_ERR(trans)) {
4467 ret = PTR_ERR(trans);
4471 spin_lock(&root->fs_info->super_lock);
4472 strcpy(super_block->label, label);
4473 spin_unlock(&root->fs_info->super_lock);
4474 ret = btrfs_end_transaction(trans, root);
4477 mnt_drop_write_file(file);
4481 long btrfs_ioctl(struct file *file, unsigned int
4482 cmd, unsigned long arg)
4484 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4485 void __user *argp = (void __user *)arg;
4488 case FS_IOC_GETFLAGS:
4489 return btrfs_ioctl_getflags(file, argp);
4490 case FS_IOC_SETFLAGS:
4491 return btrfs_ioctl_setflags(file, argp);
4492 case FS_IOC_GETVERSION:
4493 return btrfs_ioctl_getversion(file, argp);
4495 return btrfs_ioctl_fitrim(file, argp);
4496 case BTRFS_IOC_SNAP_CREATE:
4497 return btrfs_ioctl_snap_create(file, argp, 0);
4498 case BTRFS_IOC_SNAP_CREATE_V2:
4499 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4500 case BTRFS_IOC_SUBVOL_CREATE:
4501 return btrfs_ioctl_snap_create(file, argp, 1);
4502 case BTRFS_IOC_SUBVOL_CREATE_V2:
4503 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4504 case BTRFS_IOC_SNAP_DESTROY:
4505 return btrfs_ioctl_snap_destroy(file, argp);
4506 case BTRFS_IOC_SUBVOL_GETFLAGS:
4507 return btrfs_ioctl_subvol_getflags(file, argp);
4508 case BTRFS_IOC_SUBVOL_SETFLAGS:
4509 return btrfs_ioctl_subvol_setflags(file, argp);
4510 case BTRFS_IOC_DEFAULT_SUBVOL:
4511 return btrfs_ioctl_default_subvol(file, argp);
4512 case BTRFS_IOC_DEFRAG:
4513 return btrfs_ioctl_defrag(file, NULL);
4514 case BTRFS_IOC_DEFRAG_RANGE:
4515 return btrfs_ioctl_defrag(file, argp);
4516 case BTRFS_IOC_RESIZE:
4517 return btrfs_ioctl_resize(file, argp);
4518 case BTRFS_IOC_ADD_DEV:
4519 return btrfs_ioctl_add_dev(root, argp);
4520 case BTRFS_IOC_RM_DEV:
4521 return btrfs_ioctl_rm_dev(file, argp);
4522 case BTRFS_IOC_FS_INFO:
4523 return btrfs_ioctl_fs_info(root, argp);
4524 case BTRFS_IOC_DEV_INFO:
4525 return btrfs_ioctl_dev_info(root, argp);
4526 case BTRFS_IOC_BALANCE:
4527 return btrfs_ioctl_balance(file, NULL);
4528 case BTRFS_IOC_CLONE:
4529 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
4530 case BTRFS_IOC_CLONE_RANGE:
4531 return btrfs_ioctl_clone_range(file, argp);
4532 case BTRFS_IOC_TRANS_START:
4533 return btrfs_ioctl_trans_start(file);
4534 case BTRFS_IOC_TRANS_END:
4535 return btrfs_ioctl_trans_end(file);
4536 case BTRFS_IOC_TREE_SEARCH:
4537 return btrfs_ioctl_tree_search(file, argp);
4538 case BTRFS_IOC_INO_LOOKUP:
4539 return btrfs_ioctl_ino_lookup(file, argp);
4540 case BTRFS_IOC_INO_PATHS:
4541 return btrfs_ioctl_ino_to_path(root, argp);
4542 case BTRFS_IOC_LOGICAL_INO:
4543 return btrfs_ioctl_logical_to_ino(root, argp);
4544 case BTRFS_IOC_SPACE_INFO:
4545 return btrfs_ioctl_space_info(root, argp);
4546 case BTRFS_IOC_SYNC:
4547 btrfs_sync_fs(file->f_dentry->d_sb, 1);
4549 case BTRFS_IOC_START_SYNC:
4550 return btrfs_ioctl_start_sync(root, argp);
4551 case BTRFS_IOC_WAIT_SYNC:
4552 return btrfs_ioctl_wait_sync(root, argp);
4553 case BTRFS_IOC_SCRUB:
4554 return btrfs_ioctl_scrub(file, argp);
4555 case BTRFS_IOC_SCRUB_CANCEL:
4556 return btrfs_ioctl_scrub_cancel(root, argp);
4557 case BTRFS_IOC_SCRUB_PROGRESS:
4558 return btrfs_ioctl_scrub_progress(root, argp);
4559 case BTRFS_IOC_BALANCE_V2:
4560 return btrfs_ioctl_balance(file, argp);
4561 case BTRFS_IOC_BALANCE_CTL:
4562 return btrfs_ioctl_balance_ctl(root, arg);
4563 case BTRFS_IOC_BALANCE_PROGRESS:
4564 return btrfs_ioctl_balance_progress(root, argp);
4565 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4566 return btrfs_ioctl_set_received_subvol(file, argp);
4567 case BTRFS_IOC_SEND:
4568 return btrfs_ioctl_send(file, argp);
4569 case BTRFS_IOC_GET_DEV_STATS:
4570 return btrfs_ioctl_get_dev_stats(root, argp);
4571 case BTRFS_IOC_QUOTA_CTL:
4572 return btrfs_ioctl_quota_ctl(file, argp);
4573 case BTRFS_IOC_QGROUP_ASSIGN:
4574 return btrfs_ioctl_qgroup_assign(file, argp);
4575 case BTRFS_IOC_QGROUP_CREATE:
4576 return btrfs_ioctl_qgroup_create(file, argp);
4577 case BTRFS_IOC_QGROUP_LIMIT:
4578 return btrfs_ioctl_qgroup_limit(file, argp);
4579 case BTRFS_IOC_QUOTA_RESCAN:
4580 return btrfs_ioctl_quota_rescan(file, argp);
4581 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
4582 return btrfs_ioctl_quota_rescan_status(file, argp);
4583 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
4584 return btrfs_ioctl_quota_rescan_wait(file, argp);
4585 case BTRFS_IOC_DEV_REPLACE:
4586 return btrfs_ioctl_dev_replace(root, argp);
4587 case BTRFS_IOC_GET_FSLABEL:
4588 return btrfs_ioctl_get_fslabel(file, argp);
4589 case BTRFS_IOC_SET_FSLABEL:
4590 return btrfs_ioctl_set_fslabel(file, argp);
4591 case BTRFS_IOC_FILE_EXTENT_SAME:
4592 return btrfs_ioctl_file_extent_same(file, argp);