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>
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
54 #include "inode-map.h"
56 #include "rcu-string.h"
58 #include "dev-replace.h"
60 static int btrfs_clone(struct inode *src, struct inode *inode,
61 u64 off, u64 olen, u64 olen_aligned, u64 destoff);
63 /* Mask out flags that are inappropriate for the given type of inode. */
64 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
68 else if (S_ISREG(mode))
69 return flags & ~FS_DIRSYNC_FL;
71 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
75 * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
77 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
79 unsigned int iflags = 0;
81 if (flags & BTRFS_INODE_SYNC)
83 if (flags & BTRFS_INODE_IMMUTABLE)
84 iflags |= FS_IMMUTABLE_FL;
85 if (flags & BTRFS_INODE_APPEND)
86 iflags |= FS_APPEND_FL;
87 if (flags & BTRFS_INODE_NODUMP)
88 iflags |= FS_NODUMP_FL;
89 if (flags & BTRFS_INODE_NOATIME)
90 iflags |= FS_NOATIME_FL;
91 if (flags & BTRFS_INODE_DIRSYNC)
92 iflags |= FS_DIRSYNC_FL;
93 if (flags & BTRFS_INODE_NODATACOW)
94 iflags |= FS_NOCOW_FL;
96 if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
97 iflags |= FS_COMPR_FL;
98 else if (flags & BTRFS_INODE_NOCOMPRESS)
99 iflags |= FS_NOCOMP_FL;
105 * Update inode->i_flags based on the btrfs internal flags.
107 void btrfs_update_iflags(struct inode *inode)
109 struct btrfs_inode *ip = BTRFS_I(inode);
111 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
113 if (ip->flags & BTRFS_INODE_SYNC)
114 inode->i_flags |= S_SYNC;
115 if (ip->flags & BTRFS_INODE_IMMUTABLE)
116 inode->i_flags |= S_IMMUTABLE;
117 if (ip->flags & BTRFS_INODE_APPEND)
118 inode->i_flags |= S_APPEND;
119 if (ip->flags & BTRFS_INODE_NOATIME)
120 inode->i_flags |= S_NOATIME;
121 if (ip->flags & BTRFS_INODE_DIRSYNC)
122 inode->i_flags |= S_DIRSYNC;
126 * Inherit flags from the parent inode.
128 * Currently only the compression flags and the cow flags are inherited.
130 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
137 flags = BTRFS_I(dir)->flags;
139 if (flags & BTRFS_INODE_NOCOMPRESS) {
140 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
141 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
142 } else if (flags & BTRFS_INODE_COMPRESS) {
143 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
144 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
147 if (flags & BTRFS_INODE_NODATACOW) {
148 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
149 if (S_ISREG(inode->i_mode))
150 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
153 btrfs_update_iflags(inode);
156 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
158 struct btrfs_inode *ip = BTRFS_I(file_inode(file));
159 unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
161 if (copy_to_user(arg, &flags, sizeof(flags)))
166 static int check_flags(unsigned int flags)
168 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
169 FS_NOATIME_FL | FS_NODUMP_FL | \
170 FS_SYNC_FL | FS_DIRSYNC_FL | \
171 FS_NOCOMP_FL | FS_COMPR_FL |
175 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
181 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
183 struct inode *inode = file_inode(file);
184 struct btrfs_inode *ip = BTRFS_I(inode);
185 struct btrfs_root *root = ip->root;
186 struct btrfs_trans_handle *trans;
187 unsigned int flags, oldflags;
190 unsigned int i_oldflags;
193 if (btrfs_root_readonly(root))
196 if (copy_from_user(&flags, arg, sizeof(flags)))
199 ret = check_flags(flags);
203 if (!inode_owner_or_capable(inode))
206 ret = mnt_want_write_file(file);
210 mutex_lock(&inode->i_mutex);
212 ip_oldflags = ip->flags;
213 i_oldflags = inode->i_flags;
214 mode = inode->i_mode;
216 flags = btrfs_mask_flags(inode->i_mode, flags);
217 oldflags = btrfs_flags_to_ioctl(ip->flags);
218 if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
219 if (!capable(CAP_LINUX_IMMUTABLE)) {
225 if (flags & FS_SYNC_FL)
226 ip->flags |= BTRFS_INODE_SYNC;
228 ip->flags &= ~BTRFS_INODE_SYNC;
229 if (flags & FS_IMMUTABLE_FL)
230 ip->flags |= BTRFS_INODE_IMMUTABLE;
232 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
233 if (flags & FS_APPEND_FL)
234 ip->flags |= BTRFS_INODE_APPEND;
236 ip->flags &= ~BTRFS_INODE_APPEND;
237 if (flags & FS_NODUMP_FL)
238 ip->flags |= BTRFS_INODE_NODUMP;
240 ip->flags &= ~BTRFS_INODE_NODUMP;
241 if (flags & FS_NOATIME_FL)
242 ip->flags |= BTRFS_INODE_NOATIME;
244 ip->flags &= ~BTRFS_INODE_NOATIME;
245 if (flags & FS_DIRSYNC_FL)
246 ip->flags |= BTRFS_INODE_DIRSYNC;
248 ip->flags &= ~BTRFS_INODE_DIRSYNC;
249 if (flags & FS_NOCOW_FL) {
252 * It's safe to turn csums off here, no extents exist.
253 * Otherwise we want the flag to reflect the real COW
254 * status of the file and will not set it.
256 if (inode->i_size == 0)
257 ip->flags |= BTRFS_INODE_NODATACOW
258 | BTRFS_INODE_NODATASUM;
260 ip->flags |= BTRFS_INODE_NODATACOW;
264 * Revert back under same assuptions as above
267 if (inode->i_size == 0)
268 ip->flags &= ~(BTRFS_INODE_NODATACOW
269 | BTRFS_INODE_NODATASUM);
271 ip->flags &= ~BTRFS_INODE_NODATACOW;
276 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
277 * flag may be changed automatically if compression code won't make
280 if (flags & FS_NOCOMP_FL) {
281 ip->flags &= ~BTRFS_INODE_COMPRESS;
282 ip->flags |= BTRFS_INODE_NOCOMPRESS;
283 } else if (flags & FS_COMPR_FL) {
284 ip->flags |= BTRFS_INODE_COMPRESS;
285 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
287 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
290 trans = btrfs_start_transaction(root, 1);
292 ret = PTR_ERR(trans);
296 btrfs_update_iflags(inode);
297 inode_inc_iversion(inode);
298 inode->i_ctime = CURRENT_TIME;
299 ret = btrfs_update_inode(trans, root, inode);
301 btrfs_end_transaction(trans, root);
304 ip->flags = ip_oldflags;
305 inode->i_flags = i_oldflags;
309 mutex_unlock(&inode->i_mutex);
310 mnt_drop_write_file(file);
314 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
316 struct inode *inode = file_inode(file);
318 return put_user(inode->i_generation, arg);
321 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
323 struct btrfs_fs_info *fs_info = btrfs_sb(fdentry(file)->d_sb);
324 struct btrfs_device *device;
325 struct request_queue *q;
326 struct fstrim_range range;
327 u64 minlen = ULLONG_MAX;
329 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
332 if (!capable(CAP_SYS_ADMIN))
336 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
340 q = bdev_get_queue(device->bdev);
341 if (blk_queue_discard(q)) {
343 minlen = min((u64)q->limits.discard_granularity,
351 if (copy_from_user(&range, arg, sizeof(range)))
353 if (range.start > total_bytes ||
354 range.len < fs_info->sb->s_blocksize)
357 range.len = min(range.len, total_bytes - range.start);
358 range.minlen = max(range.minlen, minlen);
359 ret = btrfs_trim_fs(fs_info->tree_root, &range);
363 if (copy_to_user(arg, &range, sizeof(range)))
369 int btrfs_is_empty_uuid(u8 *uuid)
371 BUILD_BUG_ON(BTRFS_UUID_SIZE > PAGE_SIZE);
372 return !memcmp(uuid, empty_zero_page, BTRFS_UUID_SIZE);
375 static noinline int create_subvol(struct inode *dir,
376 struct dentry *dentry,
377 char *name, int namelen,
379 struct btrfs_qgroup_inherit *inherit)
381 struct btrfs_trans_handle *trans;
382 struct btrfs_key key;
383 struct btrfs_root_item root_item;
384 struct btrfs_inode_item *inode_item;
385 struct extent_buffer *leaf;
386 struct btrfs_root *root = BTRFS_I(dir)->root;
387 struct btrfs_root *new_root;
388 struct btrfs_block_rsv block_rsv;
389 struct timespec cur_time = CURRENT_TIME;
393 u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
398 ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
402 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
404 * The same as the snapshot creation, please see the comment
405 * of create_snapshot().
407 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
408 8, &qgroup_reserved, false);
412 trans = btrfs_start_transaction(root, 0);
414 ret = PTR_ERR(trans);
417 trans->block_rsv = &block_rsv;
418 trans->bytes_reserved = block_rsv.size;
420 ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
424 leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
425 0, objectid, NULL, 0, 0, 0);
431 memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
432 btrfs_set_header_bytenr(leaf, leaf->start);
433 btrfs_set_header_generation(leaf, trans->transid);
434 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
435 btrfs_set_header_owner(leaf, objectid);
437 write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
439 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
440 btrfs_header_chunk_tree_uuid(leaf),
442 btrfs_mark_buffer_dirty(leaf);
444 memset(&root_item, 0, sizeof(root_item));
446 inode_item = &root_item.inode;
447 btrfs_set_stack_inode_generation(inode_item, 1);
448 btrfs_set_stack_inode_size(inode_item, 3);
449 btrfs_set_stack_inode_nlink(inode_item, 1);
450 btrfs_set_stack_inode_nbytes(inode_item, root->leafsize);
451 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
453 btrfs_set_root_flags(&root_item, 0);
454 btrfs_set_root_limit(&root_item, 0);
455 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
457 btrfs_set_root_bytenr(&root_item, leaf->start);
458 btrfs_set_root_generation(&root_item, trans->transid);
459 btrfs_set_root_level(&root_item, 0);
460 btrfs_set_root_refs(&root_item, 1);
461 btrfs_set_root_used(&root_item, leaf->len);
462 btrfs_set_root_last_snapshot(&root_item, 0);
464 btrfs_set_root_generation_v2(&root_item,
465 btrfs_root_generation(&root_item));
466 uuid_le_gen(&new_uuid);
467 memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
468 btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
469 btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
470 root_item.ctime = root_item.otime;
471 btrfs_set_root_ctransid(&root_item, trans->transid);
472 btrfs_set_root_otransid(&root_item, trans->transid);
474 btrfs_tree_unlock(leaf);
475 free_extent_buffer(leaf);
478 btrfs_set_root_dirid(&root_item, new_dirid);
480 key.objectid = objectid;
482 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
483 ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
488 key.offset = (u64)-1;
489 new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
490 if (IS_ERR(new_root)) {
491 btrfs_abort_transaction(trans, root, PTR_ERR(new_root));
492 ret = PTR_ERR(new_root);
496 btrfs_record_root_in_trans(trans, new_root);
498 ret = btrfs_create_subvol_root(trans, new_root, new_dirid);
500 /* We potentially lose an unused inode item here */
501 btrfs_abort_transaction(trans, root, ret);
506 * insert the directory item
508 ret = btrfs_set_inode_index(dir, &index);
510 btrfs_abort_transaction(trans, root, ret);
514 ret = btrfs_insert_dir_item(trans, root,
515 name, namelen, dir, &key,
516 BTRFS_FT_DIR, index);
518 btrfs_abort_transaction(trans, root, ret);
522 btrfs_i_size_write(dir, dir->i_size + namelen * 2);
523 ret = btrfs_update_inode(trans, root, dir);
526 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
527 objectid, root->root_key.objectid,
528 btrfs_ino(dir), index, name, namelen);
531 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
532 root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
535 btrfs_abort_transaction(trans, root, ret);
538 trans->block_rsv = NULL;
539 trans->bytes_reserved = 0;
541 *async_transid = trans->transid;
542 err = btrfs_commit_transaction_async(trans, root, 1);
544 err = btrfs_commit_transaction(trans, root);
546 err = btrfs_commit_transaction(trans, root);
552 d_instantiate(dentry, btrfs_lookup_dentry(dir, dentry));
554 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
558 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
559 struct dentry *dentry, char *name, int namelen,
560 u64 *async_transid, bool readonly,
561 struct btrfs_qgroup_inherit *inherit)
564 struct btrfs_pending_snapshot *pending_snapshot;
565 struct btrfs_trans_handle *trans;
571 ret = btrfs_start_delalloc_inodes(root, 0);
575 btrfs_wait_ordered_extents(root, -1);
577 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
578 if (!pending_snapshot)
581 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
582 BTRFS_BLOCK_RSV_TEMP);
584 * 1 - parent dir inode
587 * 2 - root ref/backref
588 * 1 - root of snapshot
591 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
592 &pending_snapshot->block_rsv, 8,
593 &pending_snapshot->qgroup_reserved,
598 pending_snapshot->dentry = dentry;
599 pending_snapshot->root = root;
600 pending_snapshot->readonly = readonly;
601 pending_snapshot->dir = dir;
602 pending_snapshot->inherit = inherit;
604 trans = btrfs_start_transaction(root, 0);
606 ret = PTR_ERR(trans);
610 spin_lock(&root->fs_info->trans_lock);
611 list_add(&pending_snapshot->list,
612 &trans->transaction->pending_snapshots);
613 spin_unlock(&root->fs_info->trans_lock);
615 *async_transid = trans->transid;
616 ret = btrfs_commit_transaction_async(trans,
617 root->fs_info->extent_root, 1);
619 ret = btrfs_commit_transaction(trans, root);
621 ret = btrfs_commit_transaction(trans,
622 root->fs_info->extent_root);
627 ret = pending_snapshot->error;
631 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
635 inode = btrfs_lookup_dentry(dentry->d_parent->d_inode, dentry);
637 ret = PTR_ERR(inode);
641 d_instantiate(dentry, inode);
644 btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
645 &pending_snapshot->block_rsv,
646 pending_snapshot->qgroup_reserved);
648 kfree(pending_snapshot);
652 /* copy of check_sticky in fs/namei.c()
653 * It's inline, so penalty for filesystems that don't use sticky bit is
656 static inline int btrfs_check_sticky(struct inode *dir, struct inode *inode)
658 kuid_t fsuid = current_fsuid();
660 if (!(dir->i_mode & S_ISVTX))
662 if (uid_eq(inode->i_uid, fsuid))
664 if (uid_eq(dir->i_uid, fsuid))
666 return !capable(CAP_FOWNER);
669 /* copy of may_delete in fs/namei.c()
670 * Check whether we can remove a link victim from directory dir, check
671 * whether the type of victim is right.
672 * 1. We can't do it if dir is read-only (done in permission())
673 * 2. We should have write and exec permissions on dir
674 * 3. We can't remove anything from append-only dir
675 * 4. We can't do anything with immutable dir (done in permission())
676 * 5. If the sticky bit on dir is set we should either
677 * a. be owner of dir, or
678 * b. be owner of victim, or
679 * c. have CAP_FOWNER capability
680 * 6. If the victim is append-only or immutable we can't do antyhing with
681 * links pointing to it.
682 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
683 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
684 * 9. We can't remove a root or mountpoint.
685 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
686 * nfs_async_unlink().
689 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
693 if (!victim->d_inode)
696 BUG_ON(victim->d_parent->d_inode != dir);
697 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
699 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
704 if (btrfs_check_sticky(dir, victim->d_inode)||
705 IS_APPEND(victim->d_inode)||
706 IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
709 if (!S_ISDIR(victim->d_inode->i_mode))
713 } else if (S_ISDIR(victim->d_inode->i_mode))
717 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
722 /* copy of may_create in fs/namei.c() */
723 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
729 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
733 * Create a new subvolume below @parent. This is largely modeled after
734 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
735 * inside this filesystem so it's quite a bit simpler.
737 static noinline int btrfs_mksubvol(struct path *parent,
738 char *name, int namelen,
739 struct btrfs_root *snap_src,
740 u64 *async_transid, bool readonly,
741 struct btrfs_qgroup_inherit *inherit)
743 struct inode *dir = parent->dentry->d_inode;
744 struct dentry *dentry;
747 error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
751 dentry = lookup_one_len(name, parent->dentry, namelen);
752 error = PTR_ERR(dentry);
760 error = btrfs_may_create(dir, dentry);
765 * even if this name doesn't exist, we may get hash collisions.
766 * check for them now when we can safely fail
768 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
774 down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
776 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
780 error = create_snapshot(snap_src, dir, dentry, name, namelen,
781 async_transid, readonly, inherit);
783 error = create_subvol(dir, dentry, name, namelen,
784 async_transid, inherit);
787 fsnotify_mkdir(dir, dentry);
789 up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
793 mutex_unlock(&dir->i_mutex);
798 * When we're defragging a range, we don't want to kick it off again
799 * if it is really just waiting for delalloc to send it down.
800 * If we find a nice big extent or delalloc range for the bytes in the
801 * file you want to defrag, we return 0 to let you know to skip this
804 static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh)
806 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
807 struct extent_map *em = NULL;
808 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
811 read_lock(&em_tree->lock);
812 em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
813 read_unlock(&em_tree->lock);
816 end = extent_map_end(em);
818 if (end - offset > thresh)
821 /* if we already have a nice delalloc here, just stop */
823 end = count_range_bits(io_tree, &offset, offset + thresh,
824 thresh, EXTENT_DELALLOC, 1);
831 * helper function to walk through a file and find extents
832 * newer than a specific transid, and smaller than thresh.
834 * This is used by the defragging code to find new and small
837 static int find_new_extents(struct btrfs_root *root,
838 struct inode *inode, u64 newer_than,
839 u64 *off, int thresh)
841 struct btrfs_path *path;
842 struct btrfs_key min_key;
843 struct extent_buffer *leaf;
844 struct btrfs_file_extent_item *extent;
847 u64 ino = btrfs_ino(inode);
849 path = btrfs_alloc_path();
853 min_key.objectid = ino;
854 min_key.type = BTRFS_EXTENT_DATA_KEY;
855 min_key.offset = *off;
857 path->keep_locks = 1;
860 ret = btrfs_search_forward(root, &min_key, path, newer_than);
863 if (min_key.objectid != ino)
865 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
868 leaf = path->nodes[0];
869 extent = btrfs_item_ptr(leaf, path->slots[0],
870 struct btrfs_file_extent_item);
872 type = btrfs_file_extent_type(leaf, extent);
873 if (type == BTRFS_FILE_EXTENT_REG &&
874 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
875 check_defrag_in_cache(inode, min_key.offset, thresh)) {
876 *off = min_key.offset;
877 btrfs_free_path(path);
881 if (min_key.offset == (u64)-1)
885 btrfs_release_path(path);
888 btrfs_free_path(path);
892 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
894 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
895 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
896 struct extent_map *em;
897 u64 len = PAGE_CACHE_SIZE;
900 * hopefully we have this extent in the tree already, try without
901 * the full extent lock
903 read_lock(&em_tree->lock);
904 em = lookup_extent_mapping(em_tree, start, len);
905 read_unlock(&em_tree->lock);
908 /* get the big lock and read metadata off disk */
909 lock_extent(io_tree, start, start + len - 1);
910 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
911 unlock_extent(io_tree, start, start + len - 1);
920 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
922 struct extent_map *next;
925 /* this is the last extent */
926 if (em->start + em->len >= i_size_read(inode))
929 next = defrag_lookup_extent(inode, em->start + em->len);
930 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
933 free_extent_map(next);
937 static int should_defrag_range(struct inode *inode, u64 start, int thresh,
938 u64 *last_len, u64 *skip, u64 *defrag_end,
941 struct extent_map *em;
943 bool next_mergeable = true;
946 * make sure that once we start defragging an extent, we keep on
949 if (start < *defrag_end)
954 em = defrag_lookup_extent(inode, start);
958 /* this will cover holes, and inline extents */
959 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
964 next_mergeable = defrag_check_next_extent(inode, em);
967 * we hit a real extent, if it is big or the next extent is not a
968 * real extent, don't bother defragging it
970 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
971 (em->len >= thresh || !next_mergeable))
975 * last_len ends up being a counter of how many bytes we've defragged.
976 * every time we choose not to defrag an extent, we reset *last_len
977 * so that the next tiny extent will force a defrag.
979 * The end result of this is that tiny extents before a single big
980 * extent will force at least part of that big extent to be defragged.
983 *defrag_end = extent_map_end(em);
986 *skip = extent_map_end(em);
995 * it doesn't do much good to defrag one or two pages
996 * at a time. This pulls in a nice chunk of pages
999 * It also makes sure the delalloc code has enough
1000 * dirty data to avoid making new small extents as part
1003 * It's a good idea to start RA on this range
1004 * before calling this.
1006 static int cluster_pages_for_defrag(struct inode *inode,
1007 struct page **pages,
1008 unsigned long start_index,
1011 unsigned long file_end;
1012 u64 isize = i_size_read(inode);
1019 struct btrfs_ordered_extent *ordered;
1020 struct extent_state *cached_state = NULL;
1021 struct extent_io_tree *tree;
1022 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1024 file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1025 if (!isize || start_index > file_end)
1028 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1030 ret = btrfs_delalloc_reserve_space(inode,
1031 page_cnt << PAGE_CACHE_SHIFT);
1035 tree = &BTRFS_I(inode)->io_tree;
1037 /* step one, lock all the pages */
1038 for (i = 0; i < page_cnt; i++) {
1041 page = find_or_create_page(inode->i_mapping,
1042 start_index + i, mask);
1046 page_start = page_offset(page);
1047 page_end = page_start + PAGE_CACHE_SIZE - 1;
1049 lock_extent(tree, page_start, page_end);
1050 ordered = btrfs_lookup_ordered_extent(inode,
1052 unlock_extent(tree, page_start, page_end);
1057 btrfs_start_ordered_extent(inode, ordered, 1);
1058 btrfs_put_ordered_extent(ordered);
1061 * we unlocked the page above, so we need check if
1062 * it was released or not.
1064 if (page->mapping != inode->i_mapping) {
1066 page_cache_release(page);
1071 if (!PageUptodate(page)) {
1072 btrfs_readpage(NULL, page);
1074 if (!PageUptodate(page)) {
1076 page_cache_release(page);
1082 if (page->mapping != inode->i_mapping) {
1084 page_cache_release(page);
1094 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1098 * so now we have a nice long stream of locked
1099 * and up to date pages, lets wait on them
1101 for (i = 0; i < i_done; i++)
1102 wait_on_page_writeback(pages[i]);
1104 page_start = page_offset(pages[0]);
1105 page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1107 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1108 page_start, page_end - 1, 0, &cached_state);
1109 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1110 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1111 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1112 &cached_state, GFP_NOFS);
1114 if (i_done != page_cnt) {
1115 spin_lock(&BTRFS_I(inode)->lock);
1116 BTRFS_I(inode)->outstanding_extents++;
1117 spin_unlock(&BTRFS_I(inode)->lock);
1118 btrfs_delalloc_release_space(inode,
1119 (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1123 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1124 &cached_state, GFP_NOFS);
1126 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1127 page_start, page_end - 1, &cached_state,
1130 for (i = 0; i < i_done; i++) {
1131 clear_page_dirty_for_io(pages[i]);
1132 ClearPageChecked(pages[i]);
1133 set_page_extent_mapped(pages[i]);
1134 set_page_dirty(pages[i]);
1135 unlock_page(pages[i]);
1136 page_cache_release(pages[i]);
1140 for (i = 0; i < i_done; i++) {
1141 unlock_page(pages[i]);
1142 page_cache_release(pages[i]);
1144 btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1149 int btrfs_defrag_file(struct inode *inode, struct file *file,
1150 struct btrfs_ioctl_defrag_range_args *range,
1151 u64 newer_than, unsigned long max_to_defrag)
1153 struct btrfs_root *root = BTRFS_I(inode)->root;
1154 struct file_ra_state *ra = NULL;
1155 unsigned long last_index;
1156 u64 isize = i_size_read(inode);
1160 u64 newer_off = range->start;
1162 unsigned long ra_index = 0;
1164 int defrag_count = 0;
1165 int compress_type = BTRFS_COMPRESS_ZLIB;
1166 int extent_thresh = range->extent_thresh;
1167 int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1168 int cluster = max_cluster;
1169 u64 new_align = ~((u64)128 * 1024 - 1);
1170 struct page **pages = NULL;
1175 if (range->start >= isize)
1178 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1179 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1181 if (range->compress_type)
1182 compress_type = range->compress_type;
1185 if (extent_thresh == 0)
1186 extent_thresh = 256 * 1024;
1189 * if we were not given a file, allocate a readahead
1193 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1196 file_ra_state_init(ra, inode->i_mapping);
1201 pages = kmalloc_array(max_cluster, sizeof(struct page *),
1208 /* find the last page to defrag */
1209 if (range->start + range->len > range->start) {
1210 last_index = min_t(u64, isize - 1,
1211 range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1213 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1217 ret = find_new_extents(root, inode, newer_than,
1218 &newer_off, 64 * 1024);
1220 range->start = newer_off;
1222 * we always align our defrag to help keep
1223 * the extents in the file evenly spaced
1225 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1229 i = range->start >> PAGE_CACHE_SHIFT;
1232 max_to_defrag = last_index + 1;
1235 * make writeback starts from i, so the defrag range can be
1236 * written sequentially.
1238 if (i < inode->i_mapping->writeback_index)
1239 inode->i_mapping->writeback_index = i;
1241 while (i <= last_index && defrag_count < max_to_defrag &&
1242 (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
1243 PAGE_CACHE_SHIFT)) {
1245 * make sure we stop running if someone unmounts
1248 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1251 if (btrfs_defrag_cancelled(root->fs_info)) {
1252 printk(KERN_DEBUG "btrfs: defrag_file cancelled\n");
1257 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1258 extent_thresh, &last_len, &skip,
1259 &defrag_end, range->flags &
1260 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1263 * the should_defrag function tells us how much to skip
1264 * bump our counter by the suggested amount
1266 next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1267 i = max(i + 1, next);
1272 cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1273 PAGE_CACHE_SHIFT) - i;
1274 cluster = min(cluster, max_cluster);
1276 cluster = max_cluster;
1279 if (i + cluster > ra_index) {
1280 ra_index = max(i, ra_index);
1281 btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1283 ra_index += max_cluster;
1286 mutex_lock(&inode->i_mutex);
1287 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1288 BTRFS_I(inode)->force_compress = compress_type;
1289 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1291 mutex_unlock(&inode->i_mutex);
1295 defrag_count += ret;
1296 balance_dirty_pages_ratelimited(inode->i_mapping);
1297 mutex_unlock(&inode->i_mutex);
1300 if (newer_off == (u64)-1)
1306 newer_off = max(newer_off + 1,
1307 (u64)i << PAGE_CACHE_SHIFT);
1309 ret = find_new_extents(root, inode,
1310 newer_than, &newer_off,
1313 range->start = newer_off;
1314 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1321 last_len += ret << PAGE_CACHE_SHIFT;
1329 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
1330 filemap_flush(inode->i_mapping);
1332 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1333 /* the filemap_flush will queue IO into the worker threads, but
1334 * we have to make sure the IO is actually started and that
1335 * ordered extents get created before we return
1337 atomic_inc(&root->fs_info->async_submit_draining);
1338 while (atomic_read(&root->fs_info->nr_async_submits) ||
1339 atomic_read(&root->fs_info->async_delalloc_pages)) {
1340 wait_event(root->fs_info->async_submit_wait,
1341 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1342 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1344 atomic_dec(&root->fs_info->async_submit_draining);
1347 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1348 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1354 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1355 mutex_lock(&inode->i_mutex);
1356 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1357 mutex_unlock(&inode->i_mutex);
1365 static noinline int btrfs_ioctl_resize(struct file *file,
1371 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1372 struct btrfs_ioctl_vol_args *vol_args;
1373 struct btrfs_trans_handle *trans;
1374 struct btrfs_device *device = NULL;
1376 char *devstr = NULL;
1380 if (!capable(CAP_SYS_ADMIN))
1383 ret = mnt_want_write_file(file);
1387 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1389 mnt_drop_write_file(file);
1390 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1393 mutex_lock(&root->fs_info->volume_mutex);
1394 vol_args = memdup_user(arg, sizeof(*vol_args));
1395 if (IS_ERR(vol_args)) {
1396 ret = PTR_ERR(vol_args);
1400 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1402 sizestr = vol_args->name;
1403 devstr = strchr(sizestr, ':');
1406 sizestr = devstr + 1;
1408 devstr = vol_args->name;
1409 devid = simple_strtoull(devstr, &end, 10);
1414 printk(KERN_INFO "btrfs: resizing devid %llu\n", devid);
1417 device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1419 printk(KERN_INFO "btrfs: resizer unable to find device %llu\n",
1425 if (!device->writeable) {
1426 printk(KERN_INFO "btrfs: resizer unable to apply on "
1427 "readonly device %llu\n",
1433 if (!strcmp(sizestr, "max"))
1434 new_size = device->bdev->bd_inode->i_size;
1436 if (sizestr[0] == '-') {
1439 } else if (sizestr[0] == '+') {
1443 new_size = memparse(sizestr, NULL);
1444 if (new_size == 0) {
1450 if (device->is_tgtdev_for_dev_replace) {
1455 old_size = device->total_bytes;
1458 if (new_size > old_size) {
1462 new_size = old_size - new_size;
1463 } else if (mod > 0) {
1464 new_size = old_size + new_size;
1467 if (new_size < 256 * 1024 * 1024) {
1471 if (new_size > device->bdev->bd_inode->i_size) {
1476 do_div(new_size, root->sectorsize);
1477 new_size *= root->sectorsize;
1479 printk_in_rcu(KERN_INFO "btrfs: new size for %s is %llu\n",
1480 rcu_str_deref(device->name), new_size);
1482 if (new_size > old_size) {
1483 trans = btrfs_start_transaction(root, 0);
1484 if (IS_ERR(trans)) {
1485 ret = PTR_ERR(trans);
1488 ret = btrfs_grow_device(trans, device, new_size);
1489 btrfs_commit_transaction(trans, root);
1490 } else if (new_size < old_size) {
1491 ret = btrfs_shrink_device(device, new_size);
1492 } /* equal, nothing need to do */
1497 mutex_unlock(&root->fs_info->volume_mutex);
1498 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1499 mnt_drop_write_file(file);
1503 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1504 char *name, unsigned long fd, int subvol,
1505 u64 *transid, bool readonly,
1506 struct btrfs_qgroup_inherit *inherit)
1511 ret = mnt_want_write_file(file);
1515 namelen = strlen(name);
1516 if (strchr(name, '/')) {
1518 goto out_drop_write;
1521 if (name[0] == '.' &&
1522 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1524 goto out_drop_write;
1528 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1529 NULL, transid, readonly, inherit);
1531 struct fd src = fdget(fd);
1532 struct inode *src_inode;
1535 goto out_drop_write;
1538 src_inode = file_inode(src.file);
1539 if (src_inode->i_sb != file_inode(file)->i_sb) {
1540 printk(KERN_INFO "btrfs: Snapshot src from "
1544 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1545 BTRFS_I(src_inode)->root,
1546 transid, readonly, inherit);
1551 mnt_drop_write_file(file);
1556 static noinline int btrfs_ioctl_snap_create(struct file *file,
1557 void __user *arg, int subvol)
1559 struct btrfs_ioctl_vol_args *vol_args;
1562 vol_args = memdup_user(arg, sizeof(*vol_args));
1563 if (IS_ERR(vol_args))
1564 return PTR_ERR(vol_args);
1565 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1567 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1568 vol_args->fd, subvol,
1575 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1576 void __user *arg, int subvol)
1578 struct btrfs_ioctl_vol_args_v2 *vol_args;
1582 bool readonly = false;
1583 struct btrfs_qgroup_inherit *inherit = NULL;
1585 vol_args = memdup_user(arg, sizeof(*vol_args));
1586 if (IS_ERR(vol_args))
1587 return PTR_ERR(vol_args);
1588 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1590 if (vol_args->flags &
1591 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1592 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1597 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1599 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1601 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1602 if (vol_args->size > PAGE_CACHE_SIZE) {
1606 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1607 if (IS_ERR(inherit)) {
1608 ret = PTR_ERR(inherit);
1613 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1614 vol_args->fd, subvol, ptr,
1617 if (ret == 0 && ptr &&
1619 offsetof(struct btrfs_ioctl_vol_args_v2,
1620 transid), ptr, sizeof(*ptr)))
1628 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1631 struct inode *inode = file_inode(file);
1632 struct btrfs_root *root = BTRFS_I(inode)->root;
1636 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1639 down_read(&root->fs_info->subvol_sem);
1640 if (btrfs_root_readonly(root))
1641 flags |= BTRFS_SUBVOL_RDONLY;
1642 up_read(&root->fs_info->subvol_sem);
1644 if (copy_to_user(arg, &flags, sizeof(flags)))
1650 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1653 struct inode *inode = file_inode(file);
1654 struct btrfs_root *root = BTRFS_I(inode)->root;
1655 struct btrfs_trans_handle *trans;
1660 ret = mnt_want_write_file(file);
1664 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1666 goto out_drop_write;
1669 if (copy_from_user(&flags, arg, sizeof(flags))) {
1671 goto out_drop_write;
1674 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1676 goto out_drop_write;
1679 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1681 goto out_drop_write;
1684 if (!inode_owner_or_capable(inode)) {
1686 goto out_drop_write;
1689 down_write(&root->fs_info->subvol_sem);
1692 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1695 root_flags = btrfs_root_flags(&root->root_item);
1696 if (flags & BTRFS_SUBVOL_RDONLY)
1697 btrfs_set_root_flags(&root->root_item,
1698 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1700 btrfs_set_root_flags(&root->root_item,
1701 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1703 trans = btrfs_start_transaction(root, 1);
1704 if (IS_ERR(trans)) {
1705 ret = PTR_ERR(trans);
1709 ret = btrfs_update_root(trans, root->fs_info->tree_root,
1710 &root->root_key, &root->root_item);
1712 btrfs_commit_transaction(trans, root);
1715 btrfs_set_root_flags(&root->root_item, root_flags);
1717 up_write(&root->fs_info->subvol_sem);
1719 mnt_drop_write_file(file);
1725 * helper to check if the subvolume references other subvolumes
1727 static noinline int may_destroy_subvol(struct btrfs_root *root)
1729 struct btrfs_path *path;
1730 struct btrfs_dir_item *di;
1731 struct btrfs_key key;
1735 path = btrfs_alloc_path();
1739 /* Make sure this root isn't set as the default subvol */
1740 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1741 di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1742 dir_id, "default", 7, 0);
1743 if (di && !IS_ERR(di)) {
1744 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1745 if (key.objectid == root->root_key.objectid) {
1749 btrfs_release_path(path);
1752 key.objectid = root->root_key.objectid;
1753 key.type = BTRFS_ROOT_REF_KEY;
1754 key.offset = (u64)-1;
1756 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1763 if (path->slots[0] > 0) {
1765 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1766 if (key.objectid == root->root_key.objectid &&
1767 key.type == BTRFS_ROOT_REF_KEY)
1771 btrfs_free_path(path);
1775 static noinline int key_in_sk(struct btrfs_key *key,
1776 struct btrfs_ioctl_search_key *sk)
1778 struct btrfs_key test;
1781 test.objectid = sk->min_objectid;
1782 test.type = sk->min_type;
1783 test.offset = sk->min_offset;
1785 ret = btrfs_comp_cpu_keys(key, &test);
1789 test.objectid = sk->max_objectid;
1790 test.type = sk->max_type;
1791 test.offset = sk->max_offset;
1793 ret = btrfs_comp_cpu_keys(key, &test);
1799 static noinline int copy_to_sk(struct btrfs_root *root,
1800 struct btrfs_path *path,
1801 struct btrfs_key *key,
1802 struct btrfs_ioctl_search_key *sk,
1804 unsigned long *sk_offset,
1808 struct extent_buffer *leaf;
1809 struct btrfs_ioctl_search_header sh;
1810 unsigned long item_off;
1811 unsigned long item_len;
1817 leaf = path->nodes[0];
1818 slot = path->slots[0];
1819 nritems = btrfs_header_nritems(leaf);
1821 if (btrfs_header_generation(leaf) > sk->max_transid) {
1825 found_transid = btrfs_header_generation(leaf);
1827 for (i = slot; i < nritems; i++) {
1828 item_off = btrfs_item_ptr_offset(leaf, i);
1829 item_len = btrfs_item_size_nr(leaf, i);
1831 btrfs_item_key_to_cpu(leaf, key, i);
1832 if (!key_in_sk(key, sk))
1835 if (sizeof(sh) + item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
1838 if (sizeof(sh) + item_len + *sk_offset >
1839 BTRFS_SEARCH_ARGS_BUFSIZE) {
1844 sh.objectid = key->objectid;
1845 sh.offset = key->offset;
1846 sh.type = key->type;
1848 sh.transid = found_transid;
1850 /* copy search result header */
1851 memcpy(buf + *sk_offset, &sh, sizeof(sh));
1852 *sk_offset += sizeof(sh);
1855 char *p = buf + *sk_offset;
1857 read_extent_buffer(leaf, p,
1858 item_off, item_len);
1859 *sk_offset += item_len;
1863 if (*num_found >= sk->nr_items)
1868 if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1870 else if (key->type < (u8)-1 && key->type < sk->max_type) {
1873 } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1883 static noinline int search_ioctl(struct inode *inode,
1884 struct btrfs_ioctl_search_args *args)
1886 struct btrfs_root *root;
1887 struct btrfs_key key;
1888 struct btrfs_path *path;
1889 struct btrfs_ioctl_search_key *sk = &args->key;
1890 struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1893 unsigned long sk_offset = 0;
1895 path = btrfs_alloc_path();
1899 if (sk->tree_id == 0) {
1900 /* search the root of the inode that was passed */
1901 root = BTRFS_I(inode)->root;
1903 key.objectid = sk->tree_id;
1904 key.type = BTRFS_ROOT_ITEM_KEY;
1905 key.offset = (u64)-1;
1906 root = btrfs_read_fs_root_no_name(info, &key);
1908 printk(KERN_ERR "could not find root %llu\n",
1910 btrfs_free_path(path);
1915 key.objectid = sk->min_objectid;
1916 key.type = sk->min_type;
1917 key.offset = sk->min_offset;
1919 path->keep_locks = 1;
1922 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
1928 ret = copy_to_sk(root, path, &key, sk, args->buf,
1929 &sk_offset, &num_found);
1930 btrfs_release_path(path);
1931 if (ret || num_found >= sk->nr_items)
1937 sk->nr_items = num_found;
1938 btrfs_free_path(path);
1942 static noinline int btrfs_ioctl_tree_search(struct file *file,
1945 struct btrfs_ioctl_search_args *args;
1946 struct inode *inode;
1949 if (!capable(CAP_SYS_ADMIN))
1952 args = memdup_user(argp, sizeof(*args));
1954 return PTR_ERR(args);
1956 inode = file_inode(file);
1957 ret = search_ioctl(inode, args);
1958 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1965 * Search INODE_REFs to identify path name of 'dirid' directory
1966 * in a 'tree_id' tree. and sets path name to 'name'.
1968 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
1969 u64 tree_id, u64 dirid, char *name)
1971 struct btrfs_root *root;
1972 struct btrfs_key key;
1978 struct btrfs_inode_ref *iref;
1979 struct extent_buffer *l;
1980 struct btrfs_path *path;
1982 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
1987 path = btrfs_alloc_path();
1991 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
1993 key.objectid = tree_id;
1994 key.type = BTRFS_ROOT_ITEM_KEY;
1995 key.offset = (u64)-1;
1996 root = btrfs_read_fs_root_no_name(info, &key);
1998 printk(KERN_ERR "could not find root %llu\n", tree_id);
2003 key.objectid = dirid;
2004 key.type = BTRFS_INODE_REF_KEY;
2005 key.offset = (u64)-1;
2008 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2012 ret = btrfs_previous_item(root, path, dirid,
2013 BTRFS_INODE_REF_KEY);
2023 slot = path->slots[0];
2024 btrfs_item_key_to_cpu(l, &key, slot);
2026 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2027 len = btrfs_inode_ref_name_len(l, iref);
2029 total_len += len + 1;
2031 ret = -ENAMETOOLONG;
2036 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2038 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2041 btrfs_release_path(path);
2042 key.objectid = key.offset;
2043 key.offset = (u64)-1;
2044 dirid = key.objectid;
2046 memmove(name, ptr, total_len);
2047 name[total_len] = '\0';
2050 btrfs_free_path(path);
2054 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2057 struct btrfs_ioctl_ino_lookup_args *args;
2058 struct inode *inode;
2061 if (!capable(CAP_SYS_ADMIN))
2064 args = memdup_user(argp, sizeof(*args));
2066 return PTR_ERR(args);
2068 inode = file_inode(file);
2070 if (args->treeid == 0)
2071 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2073 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2074 args->treeid, args->objectid,
2077 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2084 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2087 struct dentry *parent = fdentry(file);
2088 struct dentry *dentry;
2089 struct inode *dir = parent->d_inode;
2090 struct inode *inode;
2091 struct btrfs_root *root = BTRFS_I(dir)->root;
2092 struct btrfs_root *dest = NULL;
2093 struct btrfs_ioctl_vol_args *vol_args;
2094 struct btrfs_trans_handle *trans;
2095 struct btrfs_block_rsv block_rsv;
2096 u64 qgroup_reserved;
2101 vol_args = memdup_user(arg, sizeof(*vol_args));
2102 if (IS_ERR(vol_args))
2103 return PTR_ERR(vol_args);
2105 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2106 namelen = strlen(vol_args->name);
2107 if (strchr(vol_args->name, '/') ||
2108 strncmp(vol_args->name, "..", namelen) == 0) {
2113 err = mnt_want_write_file(file);
2117 err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2120 dentry = lookup_one_len(vol_args->name, parent, namelen);
2121 if (IS_ERR(dentry)) {
2122 err = PTR_ERR(dentry);
2123 goto out_unlock_dir;
2126 if (!dentry->d_inode) {
2131 inode = dentry->d_inode;
2132 dest = BTRFS_I(inode)->root;
2133 if (!capable(CAP_SYS_ADMIN)) {
2135 * Regular user. Only allow this with a special mount
2136 * option, when the user has write+exec access to the
2137 * subvol root, and when rmdir(2) would have been
2140 * Note that this is _not_ check that the subvol is
2141 * empty or doesn't contain data that we wouldn't
2142 * otherwise be able to delete.
2144 * Users who want to delete empty subvols should try
2148 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2152 * Do not allow deletion if the parent dir is the same
2153 * as the dir to be deleted. That means the ioctl
2154 * must be called on the dentry referencing the root
2155 * of the subvol, not a random directory contained
2162 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2167 /* check if subvolume may be deleted by a user */
2168 err = btrfs_may_delete(dir, dentry, 1);
2172 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2177 mutex_lock(&inode->i_mutex);
2178 err = d_invalidate(dentry);
2182 down_write(&root->fs_info->subvol_sem);
2184 err = may_destroy_subvol(dest);
2188 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2190 * One for dir inode, two for dir entries, two for root
2193 err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2194 5, &qgroup_reserved, true);
2198 trans = btrfs_start_transaction(root, 0);
2199 if (IS_ERR(trans)) {
2200 err = PTR_ERR(trans);
2203 trans->block_rsv = &block_rsv;
2204 trans->bytes_reserved = block_rsv.size;
2206 ret = btrfs_unlink_subvol(trans, root, dir,
2207 dest->root_key.objectid,
2208 dentry->d_name.name,
2209 dentry->d_name.len);
2212 btrfs_abort_transaction(trans, root, ret);
2216 btrfs_record_root_in_trans(trans, dest);
2218 memset(&dest->root_item.drop_progress, 0,
2219 sizeof(dest->root_item.drop_progress));
2220 dest->root_item.drop_level = 0;
2221 btrfs_set_root_refs(&dest->root_item, 0);
2223 if (!xchg(&dest->orphan_item_inserted, 1)) {
2224 ret = btrfs_insert_orphan_item(trans,
2225 root->fs_info->tree_root,
2226 dest->root_key.objectid);
2228 btrfs_abort_transaction(trans, root, ret);
2234 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2235 dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2236 dest->root_key.objectid);
2237 if (ret && ret != -ENOENT) {
2238 btrfs_abort_transaction(trans, root, ret);
2242 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2243 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2244 dest->root_item.received_uuid,
2245 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2246 dest->root_key.objectid);
2247 if (ret && ret != -ENOENT) {
2248 btrfs_abort_transaction(trans, root, ret);
2255 trans->block_rsv = NULL;
2256 trans->bytes_reserved = 0;
2257 ret = btrfs_end_transaction(trans, root);
2260 inode->i_flags |= S_DEAD;
2262 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2264 up_write(&root->fs_info->subvol_sem);
2266 mutex_unlock(&inode->i_mutex);
2268 shrink_dcache_sb(root->fs_info->sb);
2269 btrfs_invalidate_inodes(dest);
2273 if (dest->cache_inode) {
2274 iput(dest->cache_inode);
2275 dest->cache_inode = NULL;
2281 mutex_unlock(&dir->i_mutex);
2282 mnt_drop_write_file(file);
2288 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2290 struct inode *inode = file_inode(file);
2291 struct btrfs_root *root = BTRFS_I(inode)->root;
2292 struct btrfs_ioctl_defrag_range_args *range;
2295 ret = mnt_want_write_file(file);
2299 if (btrfs_root_readonly(root)) {
2304 switch (inode->i_mode & S_IFMT) {
2306 if (!capable(CAP_SYS_ADMIN)) {
2310 ret = btrfs_defrag_root(root);
2313 ret = btrfs_defrag_root(root->fs_info->extent_root);
2316 if (!(file->f_mode & FMODE_WRITE)) {
2321 range = kzalloc(sizeof(*range), GFP_KERNEL);
2328 if (copy_from_user(range, argp,
2334 /* compression requires us to start the IO */
2335 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2336 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2337 range->extent_thresh = (u32)-1;
2340 /* the rest are all set to zero by kzalloc */
2341 range->len = (u64)-1;
2343 ret = btrfs_defrag_file(file_inode(file), file,
2353 mnt_drop_write_file(file);
2357 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2359 struct btrfs_ioctl_vol_args *vol_args;
2362 if (!capable(CAP_SYS_ADMIN))
2365 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2367 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2370 mutex_lock(&root->fs_info->volume_mutex);
2371 vol_args = memdup_user(arg, sizeof(*vol_args));
2372 if (IS_ERR(vol_args)) {
2373 ret = PTR_ERR(vol_args);
2377 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2378 ret = btrfs_init_new_device(root, vol_args->name);
2382 mutex_unlock(&root->fs_info->volume_mutex);
2383 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2387 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2389 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2390 struct btrfs_ioctl_vol_args *vol_args;
2393 if (!capable(CAP_SYS_ADMIN))
2396 ret = mnt_want_write_file(file);
2400 vol_args = memdup_user(arg, sizeof(*vol_args));
2401 if (IS_ERR(vol_args)) {
2402 ret = PTR_ERR(vol_args);
2406 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2408 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2410 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2414 mutex_lock(&root->fs_info->volume_mutex);
2415 ret = btrfs_rm_device(root, vol_args->name);
2416 mutex_unlock(&root->fs_info->volume_mutex);
2417 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2421 mnt_drop_write_file(file);
2425 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2427 struct btrfs_ioctl_fs_info_args *fi_args;
2428 struct btrfs_device *device;
2429 struct btrfs_device *next;
2430 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2433 if (!capable(CAP_SYS_ADMIN))
2436 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2440 mutex_lock(&fs_devices->device_list_mutex);
2441 fi_args->num_devices = fs_devices->num_devices;
2442 memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2444 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2445 if (device->devid > fi_args->max_id)
2446 fi_args->max_id = device->devid;
2448 mutex_unlock(&fs_devices->device_list_mutex);
2450 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2457 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2459 struct btrfs_ioctl_dev_info_args *di_args;
2460 struct btrfs_device *dev;
2461 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2463 char *s_uuid = NULL;
2465 if (!capable(CAP_SYS_ADMIN))
2468 di_args = memdup_user(arg, sizeof(*di_args));
2469 if (IS_ERR(di_args))
2470 return PTR_ERR(di_args);
2472 if (!btrfs_is_empty_uuid(di_args->uuid))
2473 s_uuid = di_args->uuid;
2475 mutex_lock(&fs_devices->device_list_mutex);
2476 dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2483 di_args->devid = dev->devid;
2484 di_args->bytes_used = dev->bytes_used;
2485 di_args->total_bytes = dev->total_bytes;
2486 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2488 struct rcu_string *name;
2491 name = rcu_dereference(dev->name);
2492 strncpy(di_args->path, name->str, sizeof(di_args->path));
2494 di_args->path[sizeof(di_args->path) - 1] = 0;
2496 di_args->path[0] = '\0';
2500 mutex_unlock(&fs_devices->device_list_mutex);
2501 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2508 static struct page *extent_same_get_page(struct inode *inode, u64 off)
2512 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2514 index = off >> PAGE_CACHE_SHIFT;
2516 page = grab_cache_page(inode->i_mapping, index);
2520 if (!PageUptodate(page)) {
2521 if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2525 if (!PageUptodate(page)) {
2527 page_cache_release(page);
2536 static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
2538 /* do any pending delalloc/csum calc on src, one way or
2539 another, and lock file content */
2541 struct btrfs_ordered_extent *ordered;
2542 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2543 ordered = btrfs_lookup_first_ordered_extent(inode,
2546 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2547 off + len - 1, EXTENT_DELALLOC, 0, NULL))
2549 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2551 btrfs_put_ordered_extent(ordered);
2552 btrfs_wait_ordered_range(inode, off, len);
2556 static void btrfs_double_unlock(struct inode *inode1, u64 loff1,
2557 struct inode *inode2, u64 loff2, u64 len)
2559 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2560 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2562 mutex_unlock(&inode1->i_mutex);
2563 mutex_unlock(&inode2->i_mutex);
2566 static void btrfs_double_lock(struct inode *inode1, u64 loff1,
2567 struct inode *inode2, u64 loff2, u64 len)
2569 if (inode1 < inode2) {
2570 swap(inode1, inode2);
2574 mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2575 lock_extent_range(inode1, loff1, len);
2576 if (inode1 != inode2) {
2577 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2578 lock_extent_range(inode2, loff2, len);
2582 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2583 u64 dst_loff, u64 len)
2586 struct page *src_page, *dst_page;
2587 unsigned int cmp_len = PAGE_CACHE_SIZE;
2588 void *addr, *dst_addr;
2591 if (len < PAGE_CACHE_SIZE)
2594 src_page = extent_same_get_page(src, loff);
2597 dst_page = extent_same_get_page(dst, dst_loff);
2599 page_cache_release(src_page);
2602 addr = kmap_atomic(src_page);
2603 dst_addr = kmap_atomic(dst_page);
2605 flush_dcache_page(src_page);
2606 flush_dcache_page(dst_page);
2608 if (memcmp(addr, dst_addr, cmp_len))
2609 ret = BTRFS_SAME_DATA_DIFFERS;
2611 kunmap_atomic(addr);
2612 kunmap_atomic(dst_addr);
2613 page_cache_release(src_page);
2614 page_cache_release(dst_page);
2620 dst_loff += cmp_len;
2627 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 len)
2629 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2631 if (off + len > inode->i_size || off + len < off)
2633 /* Check that we are block aligned - btrfs_clone() requires this */
2634 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2640 static int btrfs_extent_same(struct inode *src, u64 loff, u64 len,
2641 struct inode *dst, u64 dst_loff)
2646 * btrfs_clone() can't handle extents in the same file
2647 * yet. Once that works, we can drop this check and replace it
2648 * with a check for the same inode, but overlapping extents.
2653 btrfs_double_lock(src, loff, dst, dst_loff, len);
2655 ret = extent_same_check_offsets(src, loff, len);
2659 ret = extent_same_check_offsets(dst, dst_loff, len);
2663 /* don't make the dst file partly checksummed */
2664 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2665 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
2670 ret = btrfs_cmp_data(src, loff, dst, dst_loff, len);
2672 ret = btrfs_clone(src, dst, loff, len, len, dst_loff);
2675 btrfs_double_unlock(src, loff, dst, dst_loff, len);
2680 #define BTRFS_MAX_DEDUPE_LEN (16 * 1024 * 1024)
2682 static long btrfs_ioctl_file_extent_same(struct file *file,
2685 struct btrfs_ioctl_same_args tmp;
2686 struct btrfs_ioctl_same_args *same;
2687 struct btrfs_ioctl_same_extent_info *info;
2688 struct inode *src = file->f_dentry->d_inode;
2689 struct file *dst_file = NULL;
2696 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
2697 bool is_admin = capable(CAP_SYS_ADMIN);
2699 if (!(file->f_mode & FMODE_READ))
2702 ret = mnt_want_write_file(file);
2706 if (copy_from_user(&tmp,
2707 (struct btrfs_ioctl_same_args __user *)argp,
2713 size = sizeof(tmp) +
2714 tmp.dest_count * sizeof(struct btrfs_ioctl_same_extent_info);
2716 same = memdup_user((struct btrfs_ioctl_same_args __user *)argp, size);
2719 ret = PTR_ERR(same);
2723 off = same->logical_offset;
2727 * Limit the total length we will dedupe for each operation.
2728 * This is intended to bound the total time spent in this
2729 * ioctl to something sane.
2731 if (len > BTRFS_MAX_DEDUPE_LEN)
2732 len = BTRFS_MAX_DEDUPE_LEN;
2734 if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
2736 * Btrfs does not support blocksize < page_size. As a
2737 * result, btrfs_cmp_data() won't correctly handle
2738 * this situation without an update.
2745 if (S_ISDIR(src->i_mode))
2749 if (!S_ISREG(src->i_mode))
2752 /* pre-format output fields to sane values */
2753 for (i = 0; i < same->dest_count; i++) {
2754 same->info[i].bytes_deduped = 0ULL;
2755 same->info[i].status = 0;
2759 for (i = 0; i < same->dest_count; i++) {
2760 info = &same->info[i];
2762 dst_file = fget(info->fd);
2764 info->status = -EBADF;
2768 if (!(is_admin || (dst_file->f_mode & FMODE_WRITE))) {
2769 info->status = -EINVAL;
2773 info->status = -EXDEV;
2774 if (file->f_path.mnt != dst_file->f_path.mnt)
2777 dst = dst_file->f_dentry->d_inode;
2778 if (src->i_sb != dst->i_sb)
2781 if (S_ISDIR(dst->i_mode)) {
2782 info->status = -EISDIR;
2786 if (!S_ISREG(dst->i_mode)) {
2787 info->status = -EACCES;
2791 info->status = btrfs_extent_same(src, off, len, dst,
2792 info->logical_offset);
2793 if (info->status == 0)
2794 info->bytes_deduped += len;
2801 ret = copy_to_user(argp, same, size);
2806 mnt_drop_write_file(file);
2811 * btrfs_clone() - clone a range from inode file to another
2813 * @src: Inode to clone from
2814 * @inode: Inode to clone to
2815 * @off: Offset within source to start clone from
2816 * @olen: Original length, passed by user, of range to clone
2817 * @olen_aligned: Block-aligned value of olen, extent_same uses
2818 * identical values here
2819 * @destoff: Offset within @inode to start clone
2821 static int btrfs_clone(struct inode *src, struct inode *inode,
2822 u64 off, u64 olen, u64 olen_aligned, u64 destoff)
2824 struct btrfs_root *root = BTRFS_I(inode)->root;
2825 struct btrfs_path *path = NULL;
2826 struct extent_buffer *leaf;
2827 struct btrfs_trans_handle *trans;
2829 struct btrfs_key key;
2833 u64 len = olen_aligned;
2836 buf = vmalloc(btrfs_level_size(root, 0));
2840 path = btrfs_alloc_path();
2848 key.objectid = btrfs_ino(src);
2849 key.type = BTRFS_EXTENT_DATA_KEY;
2854 * note the key will change type as we walk through the
2857 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
2862 nritems = btrfs_header_nritems(path->nodes[0]);
2863 if (path->slots[0] >= nritems) {
2864 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
2869 nritems = btrfs_header_nritems(path->nodes[0]);
2871 leaf = path->nodes[0];
2872 slot = path->slots[0];
2874 btrfs_item_key_to_cpu(leaf, &key, slot);
2875 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
2876 key.objectid != btrfs_ino(src))
2879 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
2880 struct btrfs_file_extent_item *extent;
2883 struct btrfs_key new_key;
2884 u64 disko = 0, diskl = 0;
2885 u64 datao = 0, datal = 0;
2889 size = btrfs_item_size_nr(leaf, slot);
2890 read_extent_buffer(leaf, buf,
2891 btrfs_item_ptr_offset(leaf, slot),
2894 extent = btrfs_item_ptr(leaf, slot,
2895 struct btrfs_file_extent_item);
2896 comp = btrfs_file_extent_compression(leaf, extent);
2897 type = btrfs_file_extent_type(leaf, extent);
2898 if (type == BTRFS_FILE_EXTENT_REG ||
2899 type == BTRFS_FILE_EXTENT_PREALLOC) {
2900 disko = btrfs_file_extent_disk_bytenr(leaf,
2902 diskl = btrfs_file_extent_disk_num_bytes(leaf,
2904 datao = btrfs_file_extent_offset(leaf, extent);
2905 datal = btrfs_file_extent_num_bytes(leaf,
2907 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2908 /* take upper bound, may be compressed */
2909 datal = btrfs_file_extent_ram_bytes(leaf,
2912 btrfs_release_path(path);
2914 if (key.offset + datal <= off ||
2915 key.offset >= off + len - 1)
2918 memcpy(&new_key, &key, sizeof(new_key));
2919 new_key.objectid = btrfs_ino(inode);
2920 if (off <= key.offset)
2921 new_key.offset = key.offset + destoff - off;
2923 new_key.offset = destoff;
2926 * 1 - adjusting old extent (we may have to split it)
2927 * 1 - add new extent
2930 trans = btrfs_start_transaction(root, 3);
2931 if (IS_ERR(trans)) {
2932 ret = PTR_ERR(trans);
2936 if (type == BTRFS_FILE_EXTENT_REG ||
2937 type == BTRFS_FILE_EXTENT_PREALLOC) {
2939 * a | --- range to clone ---| b
2940 * | ------------- extent ------------- |
2943 /* substract range b */
2944 if (key.offset + datal > off + len)
2945 datal = off + len - key.offset;
2947 /* substract range a */
2948 if (off > key.offset) {
2949 datao += off - key.offset;
2950 datal -= off - key.offset;
2953 ret = btrfs_drop_extents(trans, root, inode,
2955 new_key.offset + datal,
2958 btrfs_abort_transaction(trans, root,
2960 btrfs_end_transaction(trans, root);
2964 ret = btrfs_insert_empty_item(trans, root, path,
2967 btrfs_abort_transaction(trans, root,
2969 btrfs_end_transaction(trans, root);
2973 leaf = path->nodes[0];
2974 slot = path->slots[0];
2975 write_extent_buffer(leaf, buf,
2976 btrfs_item_ptr_offset(leaf, slot),
2979 extent = btrfs_item_ptr(leaf, slot,
2980 struct btrfs_file_extent_item);
2982 /* disko == 0 means it's a hole */
2986 btrfs_set_file_extent_offset(leaf, extent,
2988 btrfs_set_file_extent_num_bytes(leaf, extent,
2991 inode_add_bytes(inode, datal);
2992 ret = btrfs_inc_extent_ref(trans, root,
2994 root->root_key.objectid,
2996 new_key.offset - datao,
2999 btrfs_abort_transaction(trans,
3002 btrfs_end_transaction(trans,
3008 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3011 if (off > key.offset) {
3012 skip = off - key.offset;
3013 new_key.offset += skip;
3016 if (key.offset + datal > off + len)
3017 trim = key.offset + datal - (off + len);
3019 if (comp && (skip || trim)) {
3021 btrfs_end_transaction(trans, root);
3024 size -= skip + trim;
3025 datal -= skip + trim;
3027 ret = btrfs_drop_extents(trans, root, inode,
3029 new_key.offset + datal,
3032 btrfs_abort_transaction(trans, root,
3034 btrfs_end_transaction(trans, root);
3038 ret = btrfs_insert_empty_item(trans, root, path,
3041 btrfs_abort_transaction(trans, root,
3043 btrfs_end_transaction(trans, root);
3049 btrfs_file_extent_calc_inline_size(0);
3050 memmove(buf+start, buf+start+skip,
3054 leaf = path->nodes[0];
3055 slot = path->slots[0];
3056 write_extent_buffer(leaf, buf,
3057 btrfs_item_ptr_offset(leaf, slot),
3059 inode_add_bytes(inode, datal);
3062 btrfs_mark_buffer_dirty(leaf);
3063 btrfs_release_path(path);
3065 inode_inc_iversion(inode);
3066 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3069 * we round up to the block size at eof when
3070 * determining which extents to clone above,
3071 * but shouldn't round up the file size
3073 endoff = new_key.offset + datal;
3074 if (endoff > destoff+olen)
3075 endoff = destoff+olen;
3076 if (endoff > inode->i_size)
3077 btrfs_i_size_write(inode, endoff);
3079 ret = btrfs_update_inode(trans, root, inode);
3081 btrfs_abort_transaction(trans, root, ret);
3082 btrfs_end_transaction(trans, root);
3085 ret = btrfs_end_transaction(trans, root);
3088 btrfs_release_path(path);
3094 btrfs_release_path(path);
3095 btrfs_free_path(path);
3100 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
3101 u64 off, u64 olen, u64 destoff)
3103 struct inode *inode = fdentry(file)->d_inode;
3104 struct btrfs_root *root = BTRFS_I(inode)->root;
3109 u64 bs = root->fs_info->sb->s_blocksize;
3114 * - split compressed inline extents. annoying: we need to
3115 * decompress into destination's address_space (the file offset
3116 * may change, so source mapping won't do), then recompress (or
3117 * otherwise reinsert) a subrange.
3118 * - allow ranges within the same file to be cloned (provided
3119 * they don't overlap)?
3122 /* the destination must be opened for writing */
3123 if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
3126 if (btrfs_root_readonly(root))
3129 ret = mnt_want_write_file(file);
3133 src_file = fdget(srcfd);
3134 if (!src_file.file) {
3136 goto out_drop_write;
3140 if (src_file.file->f_path.mnt != file->f_path.mnt)
3143 src = file_inode(src_file.file);
3149 /* the src must be open for reading */
3150 if (!(src_file.file->f_mode & FMODE_READ))
3153 /* don't make the dst file partly checksummed */
3154 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3155 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
3159 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3163 if (src->i_sb != inode->i_sb)
3168 mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
3169 mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
3171 mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
3172 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
3175 mutex_lock(&src->i_mutex);
3178 /* determine range to clone */
3180 if (off + len > src->i_size || off + len < off)
3183 olen = len = src->i_size - off;
3184 /* if we extend to eof, continue to block boundary */
3185 if (off + len == src->i_size)
3186 len = ALIGN(src->i_size, bs) - off;
3188 /* verify the end result is block aligned */
3189 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3190 !IS_ALIGNED(destoff, bs))
3193 /* verify if ranges are overlapped within the same file */
3195 if (destoff + len > off && destoff < off + len)
3199 if (destoff > inode->i_size) {
3200 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3205 /* truncate page cache pages from target inode range */
3206 truncate_inode_pages_range(&inode->i_data, destoff,
3207 PAGE_CACHE_ALIGN(destoff + len) - 1);
3209 lock_extent_range(src, off, len);
3211 ret = btrfs_clone(src, inode, off, olen, len, destoff);
3213 unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
3215 mutex_unlock(&src->i_mutex);
3217 mutex_unlock(&inode->i_mutex);
3221 mnt_drop_write_file(file);
3225 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
3227 struct btrfs_ioctl_clone_range_args args;
3229 if (copy_from_user(&args, argp, sizeof(args)))
3231 return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
3232 args.src_length, args.dest_offset);
3236 * there are many ways the trans_start and trans_end ioctls can lead
3237 * to deadlocks. They should only be used by applications that
3238 * basically own the machine, and have a very in depth understanding
3239 * of all the possible deadlocks and enospc problems.
3241 static long btrfs_ioctl_trans_start(struct file *file)
3243 struct inode *inode = file_inode(file);
3244 struct btrfs_root *root = BTRFS_I(inode)->root;
3245 struct btrfs_trans_handle *trans;
3249 if (!capable(CAP_SYS_ADMIN))
3253 if (file->private_data)
3257 if (btrfs_root_readonly(root))
3260 ret = mnt_want_write_file(file);
3264 atomic_inc(&root->fs_info->open_ioctl_trans);
3267 trans = btrfs_start_ioctl_transaction(root);
3271 file->private_data = trans;
3275 atomic_dec(&root->fs_info->open_ioctl_trans);
3276 mnt_drop_write_file(file);
3281 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3283 struct inode *inode = file_inode(file);
3284 struct btrfs_root *root = BTRFS_I(inode)->root;
3285 struct btrfs_root *new_root;
3286 struct btrfs_dir_item *di;
3287 struct btrfs_trans_handle *trans;
3288 struct btrfs_path *path;
3289 struct btrfs_key location;
3290 struct btrfs_disk_key disk_key;
3295 if (!capable(CAP_SYS_ADMIN))
3298 ret = mnt_want_write_file(file);
3302 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3308 objectid = BTRFS_FS_TREE_OBJECTID;
3310 location.objectid = objectid;
3311 location.type = BTRFS_ROOT_ITEM_KEY;
3312 location.offset = (u64)-1;
3314 new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
3315 if (IS_ERR(new_root)) {
3316 ret = PTR_ERR(new_root);
3320 path = btrfs_alloc_path();
3325 path->leave_spinning = 1;
3327 trans = btrfs_start_transaction(root, 1);
3328 if (IS_ERR(trans)) {
3329 btrfs_free_path(path);
3330 ret = PTR_ERR(trans);
3334 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
3335 di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
3336 dir_id, "default", 7, 1);
3337 if (IS_ERR_OR_NULL(di)) {
3338 btrfs_free_path(path);
3339 btrfs_end_transaction(trans, root);
3340 printk(KERN_ERR "Umm, you don't have the default dir item, "
3341 "this isn't going to work\n");
3346 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3347 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3348 btrfs_mark_buffer_dirty(path->nodes[0]);
3349 btrfs_free_path(path);
3351 btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
3352 btrfs_end_transaction(trans, root);
3354 mnt_drop_write_file(file);
3358 void btrfs_get_block_group_info(struct list_head *groups_list,
3359 struct btrfs_ioctl_space_info *space)
3361 struct btrfs_block_group_cache *block_group;
3363 space->total_bytes = 0;
3364 space->used_bytes = 0;
3366 list_for_each_entry(block_group, groups_list, list) {
3367 space->flags = block_group->flags;
3368 space->total_bytes += block_group->key.offset;
3369 space->used_bytes +=
3370 btrfs_block_group_used(&block_group->item);
3374 static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
3376 struct btrfs_ioctl_space_args space_args;
3377 struct btrfs_ioctl_space_info space;
3378 struct btrfs_ioctl_space_info *dest;
3379 struct btrfs_ioctl_space_info *dest_orig;
3380 struct btrfs_ioctl_space_info __user *user_dest;
3381 struct btrfs_space_info *info;
3382 u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
3383 BTRFS_BLOCK_GROUP_SYSTEM,
3384 BTRFS_BLOCK_GROUP_METADATA,
3385 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
3392 if (copy_from_user(&space_args,
3393 (struct btrfs_ioctl_space_args __user *)arg,
3394 sizeof(space_args)))
3397 for (i = 0; i < num_types; i++) {
3398 struct btrfs_space_info *tmp;
3402 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3404 if (tmp->flags == types[i]) {
3414 down_read(&info->groups_sem);
3415 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3416 if (!list_empty(&info->block_groups[c]))
3419 up_read(&info->groups_sem);
3422 /* space_slots == 0 means they are asking for a count */
3423 if (space_args.space_slots == 0) {
3424 space_args.total_spaces = slot_count;
3428 slot_count = min_t(u64, space_args.space_slots, slot_count);
3430 alloc_size = sizeof(*dest) * slot_count;
3432 /* we generally have at most 6 or so space infos, one for each raid
3433 * level. So, a whole page should be more than enough for everyone
3435 if (alloc_size > PAGE_CACHE_SIZE)
3438 space_args.total_spaces = 0;
3439 dest = kmalloc(alloc_size, GFP_NOFS);
3444 /* now we have a buffer to copy into */
3445 for (i = 0; i < num_types; i++) {
3446 struct btrfs_space_info *tmp;
3453 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3455 if (tmp->flags == types[i]) {
3464 down_read(&info->groups_sem);
3465 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3466 if (!list_empty(&info->block_groups[c])) {
3467 btrfs_get_block_group_info(
3468 &info->block_groups[c], &space);
3469 memcpy(dest, &space, sizeof(space));
3471 space_args.total_spaces++;
3477 up_read(&info->groups_sem);
3480 user_dest = (struct btrfs_ioctl_space_info __user *)
3481 (arg + sizeof(struct btrfs_ioctl_space_args));
3483 if (copy_to_user(user_dest, dest_orig, alloc_size))
3488 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3495 * there are many ways the trans_start and trans_end ioctls can lead
3496 * to deadlocks. They should only be used by applications that
3497 * basically own the machine, and have a very in depth understanding
3498 * of all the possible deadlocks and enospc problems.
3500 long btrfs_ioctl_trans_end(struct file *file)
3502 struct inode *inode = file_inode(file);
3503 struct btrfs_root *root = BTRFS_I(inode)->root;
3504 struct btrfs_trans_handle *trans;
3506 trans = file->private_data;
3509 file->private_data = NULL;
3511 btrfs_end_transaction(trans, root);
3513 atomic_dec(&root->fs_info->open_ioctl_trans);
3515 mnt_drop_write_file(file);
3519 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3522 struct btrfs_trans_handle *trans;
3526 trans = btrfs_attach_transaction_barrier(root);
3527 if (IS_ERR(trans)) {
3528 if (PTR_ERR(trans) != -ENOENT)
3529 return PTR_ERR(trans);
3531 /* No running transaction, don't bother */
3532 transid = root->fs_info->last_trans_committed;
3535 transid = trans->transid;
3536 ret = btrfs_commit_transaction_async(trans, root, 0);
3538 btrfs_end_transaction(trans, root);
3543 if (copy_to_user(argp, &transid, sizeof(transid)))
3548 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
3554 if (copy_from_user(&transid, argp, sizeof(transid)))
3557 transid = 0; /* current trans */
3559 return btrfs_wait_for_commit(root, transid);
3562 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3564 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3565 struct btrfs_ioctl_scrub_args *sa;
3568 if (!capable(CAP_SYS_ADMIN))
3571 sa = memdup_user(arg, sizeof(*sa));
3575 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3576 ret = mnt_want_write_file(file);
3581 ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
3582 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3585 if (copy_to_user(arg, sa, sizeof(*sa)))
3588 if (!(sa->flags & BTRFS_SCRUB_READONLY))
3589 mnt_drop_write_file(file);
3595 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
3597 if (!capable(CAP_SYS_ADMIN))
3600 return btrfs_scrub_cancel(root->fs_info);
3603 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
3606 struct btrfs_ioctl_scrub_args *sa;
3609 if (!capable(CAP_SYS_ADMIN))
3612 sa = memdup_user(arg, sizeof(*sa));
3616 ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
3618 if (copy_to_user(arg, sa, sizeof(*sa)))
3625 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
3628 struct btrfs_ioctl_get_dev_stats *sa;
3631 sa = memdup_user(arg, sizeof(*sa));
3635 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3640 ret = btrfs_get_dev_stats(root, sa);
3642 if (copy_to_user(arg, sa, sizeof(*sa)))
3649 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
3651 struct btrfs_ioctl_dev_replace_args *p;
3654 if (!capable(CAP_SYS_ADMIN))
3657 p = memdup_user(arg, sizeof(*p));
3662 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3663 if (root->fs_info->sb->s_flags & MS_RDONLY) {
3668 &root->fs_info->mutually_exclusive_operation_running,
3670 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3672 ret = btrfs_dev_replace_start(root, p);
3674 &root->fs_info->mutually_exclusive_operation_running,
3678 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3679 btrfs_dev_replace_status(root->fs_info, p);
3682 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3683 ret = btrfs_dev_replace_cancel(root->fs_info, p);
3690 if (copy_to_user(arg, p, sizeof(*p)))
3697 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3703 struct btrfs_ioctl_ino_path_args *ipa = NULL;
3704 struct inode_fs_paths *ipath = NULL;
3705 struct btrfs_path *path;
3707 if (!capable(CAP_DAC_READ_SEARCH))
3710 path = btrfs_alloc_path();
3716 ipa = memdup_user(arg, sizeof(*ipa));
3723 size = min_t(u32, ipa->size, 4096);
3724 ipath = init_ipath(size, root, path);
3725 if (IS_ERR(ipath)) {
3726 ret = PTR_ERR(ipath);
3731 ret = paths_from_inode(ipa->inum, ipath);
3735 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3736 rel_ptr = ipath->fspath->val[i] -
3737 (u64)(unsigned long)ipath->fspath->val;
3738 ipath->fspath->val[i] = rel_ptr;
3741 ret = copy_to_user((void *)(unsigned long)ipa->fspath,
3742 (void *)(unsigned long)ipath->fspath, size);
3749 btrfs_free_path(path);
3756 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3758 struct btrfs_data_container *inodes = ctx;
3759 const size_t c = 3 * sizeof(u64);
3761 if (inodes->bytes_left >= c) {
3762 inodes->bytes_left -= c;
3763 inodes->val[inodes->elem_cnt] = inum;
3764 inodes->val[inodes->elem_cnt + 1] = offset;
3765 inodes->val[inodes->elem_cnt + 2] = root;
3766 inodes->elem_cnt += 3;
3768 inodes->bytes_missing += c - inodes->bytes_left;
3769 inodes->bytes_left = 0;
3770 inodes->elem_missed += 3;
3776 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
3781 struct btrfs_ioctl_logical_ino_args *loi;
3782 struct btrfs_data_container *inodes = NULL;
3783 struct btrfs_path *path = NULL;
3785 if (!capable(CAP_SYS_ADMIN))
3788 loi = memdup_user(arg, sizeof(*loi));
3795 path = btrfs_alloc_path();
3801 size = min_t(u32, loi->size, 64 * 1024);
3802 inodes = init_data_container(size);
3803 if (IS_ERR(inodes)) {
3804 ret = PTR_ERR(inodes);
3809 ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
3810 build_ino_list, inodes);
3816 ret = copy_to_user((void *)(unsigned long)loi->inodes,
3817 (void *)(unsigned long)inodes, size);
3822 btrfs_free_path(path);
3829 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
3830 struct btrfs_ioctl_balance_args *bargs)
3832 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3834 bargs->flags = bctl->flags;
3836 if (atomic_read(&fs_info->balance_running))
3837 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3838 if (atomic_read(&fs_info->balance_pause_req))
3839 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3840 if (atomic_read(&fs_info->balance_cancel_req))
3841 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3843 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3844 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3845 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3848 spin_lock(&fs_info->balance_lock);
3849 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3850 spin_unlock(&fs_info->balance_lock);
3852 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3856 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3858 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3859 struct btrfs_fs_info *fs_info = root->fs_info;
3860 struct btrfs_ioctl_balance_args *bargs;
3861 struct btrfs_balance_control *bctl;
3862 bool need_unlock; /* for mut. excl. ops lock */
3865 if (!capable(CAP_SYS_ADMIN))
3868 ret = mnt_want_write_file(file);
3873 if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
3874 mutex_lock(&fs_info->volume_mutex);
3875 mutex_lock(&fs_info->balance_mutex);
3881 * mut. excl. ops lock is locked. Three possibilites:
3882 * (1) some other op is running
3883 * (2) balance is running
3884 * (3) balance is paused -- special case (think resume)
3886 mutex_lock(&fs_info->balance_mutex);
3887 if (fs_info->balance_ctl) {
3888 /* this is either (2) or (3) */
3889 if (!atomic_read(&fs_info->balance_running)) {
3890 mutex_unlock(&fs_info->balance_mutex);
3891 if (!mutex_trylock(&fs_info->volume_mutex))
3893 mutex_lock(&fs_info->balance_mutex);
3895 if (fs_info->balance_ctl &&
3896 !atomic_read(&fs_info->balance_running)) {
3898 need_unlock = false;
3902 mutex_unlock(&fs_info->balance_mutex);
3903 mutex_unlock(&fs_info->volume_mutex);
3907 mutex_unlock(&fs_info->balance_mutex);
3913 mutex_unlock(&fs_info->balance_mutex);
3914 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3919 BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
3922 bargs = memdup_user(arg, sizeof(*bargs));
3923 if (IS_ERR(bargs)) {
3924 ret = PTR_ERR(bargs);
3928 if (bargs->flags & BTRFS_BALANCE_RESUME) {
3929 if (!fs_info->balance_ctl) {
3934 bctl = fs_info->balance_ctl;
3935 spin_lock(&fs_info->balance_lock);
3936 bctl->flags |= BTRFS_BALANCE_RESUME;
3937 spin_unlock(&fs_info->balance_lock);
3945 if (fs_info->balance_ctl) {
3950 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3956 bctl->fs_info = fs_info;
3958 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
3959 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
3960 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
3962 bctl->flags = bargs->flags;
3964 /* balance everything - no filters */
3965 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
3970 * Ownership of bctl and mutually_exclusive_operation_running
3971 * goes to to btrfs_balance. bctl is freed in __cancel_balance,
3972 * or, if restriper was paused all the way until unmount, in
3973 * free_fs_info. mutually_exclusive_operation_running is
3974 * cleared in __cancel_balance.
3976 need_unlock = false;
3978 ret = btrfs_balance(bctl, bargs);
3981 if (copy_to_user(arg, bargs, sizeof(*bargs)))
3988 mutex_unlock(&fs_info->balance_mutex);
3989 mutex_unlock(&fs_info->volume_mutex);
3991 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3993 mnt_drop_write_file(file);
3997 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
3999 if (!capable(CAP_SYS_ADMIN))
4003 case BTRFS_BALANCE_CTL_PAUSE:
4004 return btrfs_pause_balance(root->fs_info);
4005 case BTRFS_BALANCE_CTL_CANCEL:
4006 return btrfs_cancel_balance(root->fs_info);
4012 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
4015 struct btrfs_fs_info *fs_info = root->fs_info;
4016 struct btrfs_ioctl_balance_args *bargs;
4019 if (!capable(CAP_SYS_ADMIN))
4022 mutex_lock(&fs_info->balance_mutex);
4023 if (!fs_info->balance_ctl) {
4028 bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
4034 update_ioctl_balance_args(fs_info, 1, bargs);
4036 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4041 mutex_unlock(&fs_info->balance_mutex);
4045 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4047 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4048 struct btrfs_ioctl_quota_ctl_args *sa;
4049 struct btrfs_trans_handle *trans = NULL;
4053 if (!capable(CAP_SYS_ADMIN))
4056 ret = mnt_want_write_file(file);
4060 sa = memdup_user(arg, sizeof(*sa));
4066 down_write(&root->fs_info->subvol_sem);
4067 trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
4068 if (IS_ERR(trans)) {
4069 ret = PTR_ERR(trans);
4074 case BTRFS_QUOTA_CTL_ENABLE:
4075 ret = btrfs_quota_enable(trans, root->fs_info);
4077 case BTRFS_QUOTA_CTL_DISABLE:
4078 ret = btrfs_quota_disable(trans, root->fs_info);
4085 err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
4090 up_write(&root->fs_info->subvol_sem);
4092 mnt_drop_write_file(file);
4096 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4098 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4099 struct btrfs_ioctl_qgroup_assign_args *sa;
4100 struct btrfs_trans_handle *trans;
4104 if (!capable(CAP_SYS_ADMIN))
4107 ret = mnt_want_write_file(file);
4111 sa = memdup_user(arg, sizeof(*sa));
4117 trans = btrfs_join_transaction(root);
4118 if (IS_ERR(trans)) {
4119 ret = PTR_ERR(trans);
4123 /* FIXME: check if the IDs really exist */
4125 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
4128 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
4132 err = btrfs_end_transaction(trans, root);
4139 mnt_drop_write_file(file);
4143 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4145 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4146 struct btrfs_ioctl_qgroup_create_args *sa;
4147 struct btrfs_trans_handle *trans;
4151 if (!capable(CAP_SYS_ADMIN))
4154 ret = mnt_want_write_file(file);
4158 sa = memdup_user(arg, sizeof(*sa));
4164 if (!sa->qgroupid) {
4169 trans = btrfs_join_transaction(root);
4170 if (IS_ERR(trans)) {
4171 ret = PTR_ERR(trans);
4175 /* FIXME: check if the IDs really exist */
4177 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid,
4180 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
4183 err = btrfs_end_transaction(trans, root);
4190 mnt_drop_write_file(file);
4194 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4196 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4197 struct btrfs_ioctl_qgroup_limit_args *sa;
4198 struct btrfs_trans_handle *trans;
4203 if (!capable(CAP_SYS_ADMIN))
4206 ret = mnt_want_write_file(file);
4210 sa = memdup_user(arg, sizeof(*sa));
4216 trans = btrfs_join_transaction(root);
4217 if (IS_ERR(trans)) {
4218 ret = PTR_ERR(trans);
4222 qgroupid = sa->qgroupid;
4224 /* take the current subvol as qgroup */
4225 qgroupid = root->root_key.objectid;
4228 /* FIXME: check if the IDs really exist */
4229 ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
4231 err = btrfs_end_transaction(trans, root);
4238 mnt_drop_write_file(file);
4242 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4244 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4245 struct btrfs_ioctl_quota_rescan_args *qsa;
4248 if (!capable(CAP_SYS_ADMIN))
4251 ret = mnt_want_write_file(file);
4255 qsa = memdup_user(arg, sizeof(*qsa));
4266 ret = btrfs_qgroup_rescan(root->fs_info);
4271 mnt_drop_write_file(file);
4275 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
4277 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4278 struct btrfs_ioctl_quota_rescan_args *qsa;
4281 if (!capable(CAP_SYS_ADMIN))
4284 qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
4288 if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4290 qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
4293 if (copy_to_user(arg, qsa, sizeof(*qsa)))
4300 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
4302 struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
4304 if (!capable(CAP_SYS_ADMIN))
4307 return btrfs_qgroup_wait_for_completion(root->fs_info);
4310 static long btrfs_ioctl_set_received_subvol(struct file *file,
4313 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4314 struct inode *inode = file_inode(file);
4315 struct btrfs_root *root = BTRFS_I(inode)->root;
4316 struct btrfs_root_item *root_item = &root->root_item;
4317 struct btrfs_trans_handle *trans;
4318 struct timespec ct = CURRENT_TIME;
4320 int received_uuid_changed;
4322 ret = mnt_want_write_file(file);
4326 down_write(&root->fs_info->subvol_sem);
4328 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
4333 if (btrfs_root_readonly(root)) {
4338 if (!inode_owner_or_capable(inode)) {
4343 sa = memdup_user(arg, sizeof(*sa));
4352 * 2 - uuid items (received uuid + subvol uuid)
4354 trans = btrfs_start_transaction(root, 3);
4355 if (IS_ERR(trans)) {
4356 ret = PTR_ERR(trans);
4361 sa->rtransid = trans->transid;
4362 sa->rtime.sec = ct.tv_sec;
4363 sa->rtime.nsec = ct.tv_nsec;
4365 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4367 if (received_uuid_changed &&
4368 !btrfs_is_empty_uuid(root_item->received_uuid))
4369 btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
4370 root_item->received_uuid,
4371 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4372 root->root_key.objectid);
4373 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4374 btrfs_set_root_stransid(root_item, sa->stransid);
4375 btrfs_set_root_rtransid(root_item, sa->rtransid);
4376 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4377 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4378 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4379 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4381 ret = btrfs_update_root(trans, root->fs_info->tree_root,
4382 &root->root_key, &root->root_item);
4384 btrfs_end_transaction(trans, root);
4387 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4388 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
4390 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4391 root->root_key.objectid);
4392 if (ret < 0 && ret != -EEXIST) {
4393 btrfs_abort_transaction(trans, root, ret);
4397 ret = btrfs_commit_transaction(trans, root);
4399 btrfs_abort_transaction(trans, root, ret);
4403 ret = copy_to_user(arg, sa, sizeof(*sa));
4409 up_write(&root->fs_info->subvol_sem);
4410 mnt_drop_write_file(file);
4414 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
4416 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4419 char label[BTRFS_LABEL_SIZE];
4421 spin_lock(&root->fs_info->super_lock);
4422 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4423 spin_unlock(&root->fs_info->super_lock);
4425 len = strnlen(label, BTRFS_LABEL_SIZE);
4427 if (len == BTRFS_LABEL_SIZE) {
4428 pr_warn("btrfs: label is too long, return the first %zu bytes\n",
4432 ret = copy_to_user(arg, label, len);
4434 return ret ? -EFAULT : 0;
4437 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4439 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4440 struct btrfs_super_block *super_block = root->fs_info->super_copy;
4441 struct btrfs_trans_handle *trans;
4442 char label[BTRFS_LABEL_SIZE];
4445 if (!capable(CAP_SYS_ADMIN))
4448 if (copy_from_user(label, arg, sizeof(label)))
4451 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4452 pr_err("btrfs: unable to set label with more than %d bytes\n",
4453 BTRFS_LABEL_SIZE - 1);
4457 ret = mnt_want_write_file(file);
4461 trans = btrfs_start_transaction(root, 0);
4462 if (IS_ERR(trans)) {
4463 ret = PTR_ERR(trans);
4467 spin_lock(&root->fs_info->super_lock);
4468 strcpy(super_block->label, label);
4469 spin_unlock(&root->fs_info->super_lock);
4470 ret = btrfs_end_transaction(trans, root);
4473 mnt_drop_write_file(file);
4477 long btrfs_ioctl(struct file *file, unsigned int
4478 cmd, unsigned long arg)
4480 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4481 void __user *argp = (void __user *)arg;
4484 case FS_IOC_GETFLAGS:
4485 return btrfs_ioctl_getflags(file, argp);
4486 case FS_IOC_SETFLAGS:
4487 return btrfs_ioctl_setflags(file, argp);
4488 case FS_IOC_GETVERSION:
4489 return btrfs_ioctl_getversion(file, argp);
4491 return btrfs_ioctl_fitrim(file, argp);
4492 case BTRFS_IOC_SNAP_CREATE:
4493 return btrfs_ioctl_snap_create(file, argp, 0);
4494 case BTRFS_IOC_SNAP_CREATE_V2:
4495 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4496 case BTRFS_IOC_SUBVOL_CREATE:
4497 return btrfs_ioctl_snap_create(file, argp, 1);
4498 case BTRFS_IOC_SUBVOL_CREATE_V2:
4499 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4500 case BTRFS_IOC_SNAP_DESTROY:
4501 return btrfs_ioctl_snap_destroy(file, argp);
4502 case BTRFS_IOC_SUBVOL_GETFLAGS:
4503 return btrfs_ioctl_subvol_getflags(file, argp);
4504 case BTRFS_IOC_SUBVOL_SETFLAGS:
4505 return btrfs_ioctl_subvol_setflags(file, argp);
4506 case BTRFS_IOC_DEFAULT_SUBVOL:
4507 return btrfs_ioctl_default_subvol(file, argp);
4508 case BTRFS_IOC_DEFRAG:
4509 return btrfs_ioctl_defrag(file, NULL);
4510 case BTRFS_IOC_DEFRAG_RANGE:
4511 return btrfs_ioctl_defrag(file, argp);
4512 case BTRFS_IOC_RESIZE:
4513 return btrfs_ioctl_resize(file, argp);
4514 case BTRFS_IOC_ADD_DEV:
4515 return btrfs_ioctl_add_dev(root, argp);
4516 case BTRFS_IOC_RM_DEV:
4517 return btrfs_ioctl_rm_dev(file, argp);
4518 case BTRFS_IOC_FS_INFO:
4519 return btrfs_ioctl_fs_info(root, argp);
4520 case BTRFS_IOC_DEV_INFO:
4521 return btrfs_ioctl_dev_info(root, argp);
4522 case BTRFS_IOC_BALANCE:
4523 return btrfs_ioctl_balance(file, NULL);
4524 case BTRFS_IOC_CLONE:
4525 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
4526 case BTRFS_IOC_CLONE_RANGE:
4527 return btrfs_ioctl_clone_range(file, argp);
4528 case BTRFS_IOC_TRANS_START:
4529 return btrfs_ioctl_trans_start(file);
4530 case BTRFS_IOC_TRANS_END:
4531 return btrfs_ioctl_trans_end(file);
4532 case BTRFS_IOC_TREE_SEARCH:
4533 return btrfs_ioctl_tree_search(file, argp);
4534 case BTRFS_IOC_INO_LOOKUP:
4535 return btrfs_ioctl_ino_lookup(file, argp);
4536 case BTRFS_IOC_INO_PATHS:
4537 return btrfs_ioctl_ino_to_path(root, argp);
4538 case BTRFS_IOC_LOGICAL_INO:
4539 return btrfs_ioctl_logical_to_ino(root, argp);
4540 case BTRFS_IOC_SPACE_INFO:
4541 return btrfs_ioctl_space_info(root, argp);
4542 case BTRFS_IOC_SYNC: {
4545 ret = btrfs_start_delalloc_roots(root->fs_info, 0);
4548 ret = btrfs_sync_fs(file->f_dentry->d_sb, 1);
4551 case BTRFS_IOC_START_SYNC:
4552 return btrfs_ioctl_start_sync(root, argp);
4553 case BTRFS_IOC_WAIT_SYNC:
4554 return btrfs_ioctl_wait_sync(root, argp);
4555 case BTRFS_IOC_SCRUB:
4556 return btrfs_ioctl_scrub(file, argp);
4557 case BTRFS_IOC_SCRUB_CANCEL:
4558 return btrfs_ioctl_scrub_cancel(root, argp);
4559 case BTRFS_IOC_SCRUB_PROGRESS:
4560 return btrfs_ioctl_scrub_progress(root, argp);
4561 case BTRFS_IOC_BALANCE_V2:
4562 return btrfs_ioctl_balance(file, argp);
4563 case BTRFS_IOC_BALANCE_CTL:
4564 return btrfs_ioctl_balance_ctl(root, arg);
4565 case BTRFS_IOC_BALANCE_PROGRESS:
4566 return btrfs_ioctl_balance_progress(root, argp);
4567 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4568 return btrfs_ioctl_set_received_subvol(file, argp);
4569 case BTRFS_IOC_SEND:
4570 return btrfs_ioctl_send(file, argp);
4571 case BTRFS_IOC_GET_DEV_STATS:
4572 return btrfs_ioctl_get_dev_stats(root, argp);
4573 case BTRFS_IOC_QUOTA_CTL:
4574 return btrfs_ioctl_quota_ctl(file, argp);
4575 case BTRFS_IOC_QGROUP_ASSIGN:
4576 return btrfs_ioctl_qgroup_assign(file, argp);
4577 case BTRFS_IOC_QGROUP_CREATE:
4578 return btrfs_ioctl_qgroup_create(file, argp);
4579 case BTRFS_IOC_QGROUP_LIMIT:
4580 return btrfs_ioctl_qgroup_limit(file, argp);
4581 case BTRFS_IOC_QUOTA_RESCAN:
4582 return btrfs_ioctl_quota_rescan(file, argp);
4583 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
4584 return btrfs_ioctl_quota_rescan_status(file, argp);
4585 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
4586 return btrfs_ioctl_quota_rescan_wait(file, argp);
4587 case BTRFS_IOC_DEV_REPLACE:
4588 return btrfs_ioctl_dev_replace(root, argp);
4589 case BTRFS_IOC_GET_FSLABEL:
4590 return btrfs_ioctl_get_fslabel(file, argp);
4591 case BTRFS_IOC_SET_FSLABEL:
4592 return btrfs_ioctl_set_fslabel(file, argp);
4593 case BTRFS_IOC_FILE_EXTENT_SAME:
4594 return btrfs_ioctl_file_extent_same(file, argp);