ext4: fix a potential fiemap/page fault deadlock w/ inline_data
[linux/fpc-iii.git] / fs / btrfs / ioctl.c
blob3379490ce54daa49f4a8058da01bd8e7034dd4d4
1 /*
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>
23 #include <linux/fs.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>
47 #include "ctree.h"
48 #include "disk-io.h"
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "volumes.h"
53 #include "locking.h"
54 #include "inode-map.h"
55 #include "backref.h"
56 #include "rcu-string.h"
57 #include "send.h"
58 #include "dev-replace.h"
59 #include "props.h"
60 #include "sysfs.h"
61 #include "qgroup.h"
63 #ifdef CONFIG_64BIT
64 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
65 * structures are incorrect, as the timespec structure from userspace
66 * is 4 bytes too small. We define these alternatives here to teach
67 * the kernel about the 32-bit struct packing.
69 struct btrfs_ioctl_timespec_32 {
70 __u64 sec;
71 __u32 nsec;
72 } __attribute__ ((__packed__));
74 struct btrfs_ioctl_received_subvol_args_32 {
75 char uuid[BTRFS_UUID_SIZE]; /* in */
76 __u64 stransid; /* in */
77 __u64 rtransid; /* out */
78 struct btrfs_ioctl_timespec_32 stime; /* in */
79 struct btrfs_ioctl_timespec_32 rtime; /* out */
80 __u64 flags; /* in */
81 __u64 reserved[16]; /* in */
82 } __attribute__ ((__packed__));
84 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
85 struct btrfs_ioctl_received_subvol_args_32)
86 #endif
89 static int btrfs_clone(struct inode *src, struct inode *inode,
90 u64 off, u64 olen, u64 olen_aligned, u64 destoff,
91 int no_time_update);
93 /* Mask out flags that are inappropriate for the given type of inode. */
94 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
96 if (S_ISDIR(mode))
97 return flags;
98 else if (S_ISREG(mode))
99 return flags & ~FS_DIRSYNC_FL;
100 else
101 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
105 * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
107 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
109 unsigned int iflags = 0;
111 if (flags & BTRFS_INODE_SYNC)
112 iflags |= FS_SYNC_FL;
113 if (flags & BTRFS_INODE_IMMUTABLE)
114 iflags |= FS_IMMUTABLE_FL;
115 if (flags & BTRFS_INODE_APPEND)
116 iflags |= FS_APPEND_FL;
117 if (flags & BTRFS_INODE_NODUMP)
118 iflags |= FS_NODUMP_FL;
119 if (flags & BTRFS_INODE_NOATIME)
120 iflags |= FS_NOATIME_FL;
121 if (flags & BTRFS_INODE_DIRSYNC)
122 iflags |= FS_DIRSYNC_FL;
123 if (flags & BTRFS_INODE_NODATACOW)
124 iflags |= FS_NOCOW_FL;
126 if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
127 iflags |= FS_COMPR_FL;
128 else if (flags & BTRFS_INODE_NOCOMPRESS)
129 iflags |= FS_NOCOMP_FL;
131 return iflags;
135 * Update inode->i_flags based on the btrfs internal flags.
137 void btrfs_update_iflags(struct inode *inode)
139 struct btrfs_inode *ip = BTRFS_I(inode);
140 unsigned int new_fl = 0;
142 if (ip->flags & BTRFS_INODE_SYNC)
143 new_fl |= S_SYNC;
144 if (ip->flags & BTRFS_INODE_IMMUTABLE)
145 new_fl |= S_IMMUTABLE;
146 if (ip->flags & BTRFS_INODE_APPEND)
147 new_fl |= S_APPEND;
148 if (ip->flags & BTRFS_INODE_NOATIME)
149 new_fl |= S_NOATIME;
150 if (ip->flags & BTRFS_INODE_DIRSYNC)
151 new_fl |= S_DIRSYNC;
153 set_mask_bits(&inode->i_flags,
154 S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
155 new_fl);
159 * Inherit flags from the parent inode.
161 * Currently only the compression flags and the cow flags are inherited.
163 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
165 unsigned int flags;
167 if (!dir)
168 return;
170 flags = BTRFS_I(dir)->flags;
172 if (flags & BTRFS_INODE_NOCOMPRESS) {
173 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
174 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
175 } else if (flags & BTRFS_INODE_COMPRESS) {
176 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
177 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
180 if (flags & BTRFS_INODE_NODATACOW) {
181 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
182 if (S_ISREG(inode->i_mode))
183 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
186 btrfs_update_iflags(inode);
189 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
191 struct btrfs_inode *ip = BTRFS_I(file_inode(file));
192 unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
194 if (copy_to_user(arg, &flags, sizeof(flags)))
195 return -EFAULT;
196 return 0;
199 static int check_flags(unsigned int flags)
201 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
202 FS_NOATIME_FL | FS_NODUMP_FL | \
203 FS_SYNC_FL | FS_DIRSYNC_FL | \
204 FS_NOCOMP_FL | FS_COMPR_FL |
205 FS_NOCOW_FL))
206 return -EOPNOTSUPP;
208 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
209 return -EINVAL;
211 return 0;
214 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
216 struct inode *inode = file_inode(file);
217 struct btrfs_inode *ip = BTRFS_I(inode);
218 struct btrfs_root *root = ip->root;
219 struct btrfs_trans_handle *trans;
220 unsigned int flags, oldflags;
221 int ret;
222 u64 ip_oldflags;
223 unsigned int i_oldflags;
224 umode_t mode;
226 if (!inode_owner_or_capable(inode))
227 return -EPERM;
229 if (btrfs_root_readonly(root))
230 return -EROFS;
232 if (copy_from_user(&flags, arg, sizeof(flags)))
233 return -EFAULT;
235 ret = check_flags(flags);
236 if (ret)
237 return ret;
239 ret = mnt_want_write_file(file);
240 if (ret)
241 return ret;
243 mutex_lock(&inode->i_mutex);
245 ip_oldflags = ip->flags;
246 i_oldflags = inode->i_flags;
247 mode = inode->i_mode;
249 flags = btrfs_mask_flags(inode->i_mode, flags);
250 oldflags = btrfs_flags_to_ioctl(ip->flags);
251 if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
252 if (!capable(CAP_LINUX_IMMUTABLE)) {
253 ret = -EPERM;
254 goto out_unlock;
258 if (flags & FS_SYNC_FL)
259 ip->flags |= BTRFS_INODE_SYNC;
260 else
261 ip->flags &= ~BTRFS_INODE_SYNC;
262 if (flags & FS_IMMUTABLE_FL)
263 ip->flags |= BTRFS_INODE_IMMUTABLE;
264 else
265 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
266 if (flags & FS_APPEND_FL)
267 ip->flags |= BTRFS_INODE_APPEND;
268 else
269 ip->flags &= ~BTRFS_INODE_APPEND;
270 if (flags & FS_NODUMP_FL)
271 ip->flags |= BTRFS_INODE_NODUMP;
272 else
273 ip->flags &= ~BTRFS_INODE_NODUMP;
274 if (flags & FS_NOATIME_FL)
275 ip->flags |= BTRFS_INODE_NOATIME;
276 else
277 ip->flags &= ~BTRFS_INODE_NOATIME;
278 if (flags & FS_DIRSYNC_FL)
279 ip->flags |= BTRFS_INODE_DIRSYNC;
280 else
281 ip->flags &= ~BTRFS_INODE_DIRSYNC;
282 if (flags & FS_NOCOW_FL) {
283 if (S_ISREG(mode)) {
285 * It's safe to turn csums off here, no extents exist.
286 * Otherwise we want the flag to reflect the real COW
287 * status of the file and will not set it.
289 if (inode->i_size == 0)
290 ip->flags |= BTRFS_INODE_NODATACOW
291 | BTRFS_INODE_NODATASUM;
292 } else {
293 ip->flags |= BTRFS_INODE_NODATACOW;
295 } else {
297 * Revert back under same assuptions as above
299 if (S_ISREG(mode)) {
300 if (inode->i_size == 0)
301 ip->flags &= ~(BTRFS_INODE_NODATACOW
302 | BTRFS_INODE_NODATASUM);
303 } else {
304 ip->flags &= ~BTRFS_INODE_NODATACOW;
309 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
310 * flag may be changed automatically if compression code won't make
311 * things smaller.
313 if (flags & FS_NOCOMP_FL) {
314 ip->flags &= ~BTRFS_INODE_COMPRESS;
315 ip->flags |= BTRFS_INODE_NOCOMPRESS;
317 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
318 if (ret && ret != -ENODATA)
319 goto out_drop;
320 } else if (flags & FS_COMPR_FL) {
321 const char *comp;
323 ip->flags |= BTRFS_INODE_COMPRESS;
324 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
326 if (root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
327 comp = "lzo";
328 else
329 comp = "zlib";
330 ret = btrfs_set_prop(inode, "btrfs.compression",
331 comp, strlen(comp), 0);
332 if (ret)
333 goto out_drop;
335 } else {
336 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
337 if (ret && ret != -ENODATA)
338 goto out_drop;
339 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
342 trans = btrfs_start_transaction(root, 1);
343 if (IS_ERR(trans)) {
344 ret = PTR_ERR(trans);
345 goto out_drop;
348 btrfs_update_iflags(inode);
349 inode_inc_iversion(inode);
350 inode->i_ctime = CURRENT_TIME;
351 ret = btrfs_update_inode(trans, root, inode);
353 btrfs_end_transaction(trans, root);
354 out_drop:
355 if (ret) {
356 ip->flags = ip_oldflags;
357 inode->i_flags = i_oldflags;
360 out_unlock:
361 mutex_unlock(&inode->i_mutex);
362 mnt_drop_write_file(file);
363 return ret;
366 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
368 struct inode *inode = file_inode(file);
370 return put_user(inode->i_generation, arg);
373 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
375 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
376 struct btrfs_device *device;
377 struct request_queue *q;
378 struct fstrim_range range;
379 u64 minlen = ULLONG_MAX;
380 u64 num_devices = 0;
381 int ret;
383 if (!capable(CAP_SYS_ADMIN))
384 return -EPERM;
386 rcu_read_lock();
387 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
388 dev_list) {
389 if (!device->bdev)
390 continue;
391 q = bdev_get_queue(device->bdev);
392 if (blk_queue_discard(q)) {
393 num_devices++;
394 minlen = min((u64)q->limits.discard_granularity,
395 minlen);
398 rcu_read_unlock();
400 if (!num_devices)
401 return -EOPNOTSUPP;
402 if (copy_from_user(&range, arg, sizeof(range)))
403 return -EFAULT;
406 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
407 * block group is in the logical address space, which can be any
408 * sectorsize aligned bytenr in the range [0, U64_MAX].
410 if (range.len < fs_info->sb->s_blocksize)
411 return -EINVAL;
413 range.minlen = max(range.minlen, minlen);
414 ret = btrfs_trim_fs(fs_info->tree_root, &range);
415 if (ret < 0)
416 return ret;
418 if (copy_to_user(arg, &range, sizeof(range)))
419 return -EFAULT;
421 return 0;
424 int btrfs_is_empty_uuid(u8 *uuid)
426 int i;
428 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
429 if (uuid[i])
430 return 0;
432 return 1;
435 static noinline int create_subvol(struct inode *dir,
436 struct dentry *dentry,
437 char *name, int namelen,
438 u64 *async_transid,
439 struct btrfs_qgroup_inherit *inherit)
441 struct btrfs_trans_handle *trans;
442 struct btrfs_key key;
443 struct btrfs_root_item root_item;
444 struct btrfs_inode_item *inode_item;
445 struct extent_buffer *leaf;
446 struct btrfs_root *root = BTRFS_I(dir)->root;
447 struct btrfs_root *new_root;
448 struct btrfs_block_rsv block_rsv;
449 struct timespec cur_time = CURRENT_TIME;
450 struct inode *inode;
451 int ret;
452 int err;
453 u64 objectid;
454 u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
455 u64 index = 0;
456 u64 qgroup_reserved;
457 uuid_le new_uuid;
459 ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
460 if (ret)
461 return ret;
464 * Don't create subvolume whose level is not zero. Or qgroup will be
465 * screwed up since it assume subvolme qgroup's level to be 0.
467 if (btrfs_qgroup_level(objectid))
468 return -ENOSPC;
470 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
472 * The same as the snapshot creation, please see the comment
473 * of create_snapshot().
475 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
476 8, &qgroup_reserved, false);
477 if (ret)
478 return ret;
480 trans = btrfs_start_transaction(root, 0);
481 if (IS_ERR(trans)) {
482 ret = PTR_ERR(trans);
483 btrfs_subvolume_release_metadata(root, &block_rsv,
484 qgroup_reserved);
485 return ret;
487 trans->block_rsv = &block_rsv;
488 trans->bytes_reserved = block_rsv.size;
490 ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
491 if (ret)
492 goto fail;
494 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
495 if (IS_ERR(leaf)) {
496 ret = PTR_ERR(leaf);
497 goto fail;
500 memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
501 btrfs_set_header_bytenr(leaf, leaf->start);
502 btrfs_set_header_generation(leaf, trans->transid);
503 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
504 btrfs_set_header_owner(leaf, objectid);
506 write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
507 BTRFS_FSID_SIZE);
508 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
509 btrfs_header_chunk_tree_uuid(leaf),
510 BTRFS_UUID_SIZE);
511 btrfs_mark_buffer_dirty(leaf);
513 memset(&root_item, 0, sizeof(root_item));
515 inode_item = &root_item.inode;
516 btrfs_set_stack_inode_generation(inode_item, 1);
517 btrfs_set_stack_inode_size(inode_item, 3);
518 btrfs_set_stack_inode_nlink(inode_item, 1);
519 btrfs_set_stack_inode_nbytes(inode_item, root->nodesize);
520 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
522 btrfs_set_root_flags(&root_item, 0);
523 btrfs_set_root_limit(&root_item, 0);
524 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
526 btrfs_set_root_bytenr(&root_item, leaf->start);
527 btrfs_set_root_generation(&root_item, trans->transid);
528 btrfs_set_root_level(&root_item, 0);
529 btrfs_set_root_refs(&root_item, 1);
530 btrfs_set_root_used(&root_item, leaf->len);
531 btrfs_set_root_last_snapshot(&root_item, 0);
533 btrfs_set_root_generation_v2(&root_item,
534 btrfs_root_generation(&root_item));
535 uuid_le_gen(&new_uuid);
536 memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
537 btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
538 btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
539 root_item.ctime = root_item.otime;
540 btrfs_set_root_ctransid(&root_item, trans->transid);
541 btrfs_set_root_otransid(&root_item, trans->transid);
543 btrfs_tree_unlock(leaf);
544 free_extent_buffer(leaf);
545 leaf = NULL;
547 btrfs_set_root_dirid(&root_item, new_dirid);
549 key.objectid = objectid;
550 key.offset = 0;
551 key.type = BTRFS_ROOT_ITEM_KEY;
552 ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
553 &root_item);
554 if (ret)
555 goto fail;
557 key.offset = (u64)-1;
558 new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
559 if (IS_ERR(new_root)) {
560 ret = PTR_ERR(new_root);
561 btrfs_abort_transaction(trans, root, ret);
562 goto fail;
565 btrfs_record_root_in_trans(trans, new_root);
567 ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
568 if (ret) {
569 /* We potentially lose an unused inode item here */
570 btrfs_abort_transaction(trans, root, ret);
571 goto fail;
574 mutex_lock(&new_root->objectid_mutex);
575 new_root->highest_objectid = new_dirid;
576 mutex_unlock(&new_root->objectid_mutex);
579 * insert the directory item
581 ret = btrfs_set_inode_index(dir, &index);
582 if (ret) {
583 btrfs_abort_transaction(trans, root, ret);
584 goto fail;
587 ret = btrfs_insert_dir_item(trans, root,
588 name, namelen, dir, &key,
589 BTRFS_FT_DIR, index);
590 if (ret) {
591 btrfs_abort_transaction(trans, root, ret);
592 goto fail;
595 btrfs_i_size_write(dir, dir->i_size + namelen * 2);
596 ret = btrfs_update_inode(trans, root, dir);
597 BUG_ON(ret);
599 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
600 objectid, root->root_key.objectid,
601 btrfs_ino(dir), index, name, namelen);
602 BUG_ON(ret);
604 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
605 root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
606 objectid);
607 if (ret)
608 btrfs_abort_transaction(trans, root, ret);
610 fail:
611 trans->block_rsv = NULL;
612 trans->bytes_reserved = 0;
613 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
615 if (async_transid) {
616 *async_transid = trans->transid;
617 err = btrfs_commit_transaction_async(trans, root, 1);
618 if (err)
619 err = btrfs_commit_transaction(trans, root);
620 } else {
621 err = btrfs_commit_transaction(trans, root);
623 if (err && !ret)
624 ret = err;
626 if (!ret) {
627 inode = btrfs_lookup_dentry(dir, dentry);
628 if (IS_ERR(inode))
629 return PTR_ERR(inode);
630 d_instantiate(dentry, inode);
632 return ret;
635 static void btrfs_wait_for_no_snapshoting_writes(struct btrfs_root *root)
637 s64 writers;
638 DEFINE_WAIT(wait);
640 do {
641 prepare_to_wait(&root->subv_writers->wait, &wait,
642 TASK_UNINTERRUPTIBLE);
644 writers = percpu_counter_sum(&root->subv_writers->counter);
645 if (writers)
646 schedule();
648 finish_wait(&root->subv_writers->wait, &wait);
649 } while (writers);
652 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
653 struct dentry *dentry, char *name, int namelen,
654 u64 *async_transid, bool readonly,
655 struct btrfs_qgroup_inherit *inherit)
657 struct inode *inode;
658 struct btrfs_pending_snapshot *pending_snapshot;
659 struct btrfs_trans_handle *trans;
660 int ret;
662 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
663 return -EINVAL;
665 atomic_inc(&root->will_be_snapshoted);
666 smp_mb__after_atomic();
667 btrfs_wait_for_no_snapshoting_writes(root);
669 ret = btrfs_start_delalloc_inodes(root, 0);
670 if (ret)
671 goto out;
673 btrfs_wait_ordered_extents(root, -1);
675 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
676 if (!pending_snapshot) {
677 ret = -ENOMEM;
678 goto out;
681 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
682 BTRFS_BLOCK_RSV_TEMP);
684 * 1 - parent dir inode
685 * 2 - dir entries
686 * 1 - root item
687 * 2 - root ref/backref
688 * 1 - root of snapshot
689 * 1 - UUID item
691 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
692 &pending_snapshot->block_rsv, 8,
693 &pending_snapshot->qgroup_reserved,
694 false);
695 if (ret)
696 goto free;
698 pending_snapshot->dentry = dentry;
699 pending_snapshot->root = root;
700 pending_snapshot->readonly = readonly;
701 pending_snapshot->dir = dir;
702 pending_snapshot->inherit = inherit;
704 trans = btrfs_start_transaction(root, 0);
705 if (IS_ERR(trans)) {
706 ret = PTR_ERR(trans);
707 goto fail;
710 spin_lock(&root->fs_info->trans_lock);
711 list_add(&pending_snapshot->list,
712 &trans->transaction->pending_snapshots);
713 spin_unlock(&root->fs_info->trans_lock);
714 if (async_transid) {
715 *async_transid = trans->transid;
716 ret = btrfs_commit_transaction_async(trans,
717 root->fs_info->extent_root, 1);
718 if (ret)
719 ret = btrfs_commit_transaction(trans, root);
720 } else {
721 ret = btrfs_commit_transaction(trans,
722 root->fs_info->extent_root);
724 if (ret)
725 goto fail;
727 ret = pending_snapshot->error;
728 if (ret)
729 goto fail;
731 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
732 if (ret)
733 goto fail;
735 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
736 if (IS_ERR(inode)) {
737 ret = PTR_ERR(inode);
738 goto fail;
741 d_instantiate(dentry, inode);
742 ret = 0;
743 fail:
744 btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
745 &pending_snapshot->block_rsv,
746 pending_snapshot->qgroup_reserved);
747 free:
748 kfree(pending_snapshot);
749 out:
750 if (atomic_dec_and_test(&root->will_be_snapshoted))
751 wake_up_atomic_t(&root->will_be_snapshoted);
752 return ret;
755 /* copy of may_delete in fs/namei.c()
756 * Check whether we can remove a link victim from directory dir, check
757 * whether the type of victim is right.
758 * 1. We can't do it if dir is read-only (done in permission())
759 * 2. We should have write and exec permissions on dir
760 * 3. We can't remove anything from append-only dir
761 * 4. We can't do anything with immutable dir (done in permission())
762 * 5. If the sticky bit on dir is set we should either
763 * a. be owner of dir, or
764 * b. be owner of victim, or
765 * c. have CAP_FOWNER capability
766 * 6. If the victim is append-only or immutable we can't do antyhing with
767 * links pointing to it.
768 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
769 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
770 * 9. We can't remove a root or mountpoint.
771 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
772 * nfs_async_unlink().
775 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
777 int error;
779 if (d_really_is_negative(victim))
780 return -ENOENT;
782 BUG_ON(d_inode(victim->d_parent) != dir);
783 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
785 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
786 if (error)
787 return error;
788 if (IS_APPEND(dir))
789 return -EPERM;
790 if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
791 IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
792 return -EPERM;
793 if (isdir) {
794 if (!d_is_dir(victim))
795 return -ENOTDIR;
796 if (IS_ROOT(victim))
797 return -EBUSY;
798 } else if (d_is_dir(victim))
799 return -EISDIR;
800 if (IS_DEADDIR(dir))
801 return -ENOENT;
802 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
803 return -EBUSY;
804 return 0;
807 /* copy of may_create in fs/namei.c() */
808 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
810 if (d_really_is_positive(child))
811 return -EEXIST;
812 if (IS_DEADDIR(dir))
813 return -ENOENT;
814 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
818 * Create a new subvolume below @parent. This is largely modeled after
819 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
820 * inside this filesystem so it's quite a bit simpler.
822 static noinline int btrfs_mksubvol(struct path *parent,
823 char *name, int namelen,
824 struct btrfs_root *snap_src,
825 u64 *async_transid, bool readonly,
826 struct btrfs_qgroup_inherit *inherit)
828 struct inode *dir = d_inode(parent->dentry);
829 struct dentry *dentry;
830 int error;
832 error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
833 if (error == -EINTR)
834 return error;
836 dentry = lookup_one_len(name, parent->dentry, namelen);
837 error = PTR_ERR(dentry);
838 if (IS_ERR(dentry))
839 goto out_unlock;
841 error = -EEXIST;
842 if (d_really_is_positive(dentry))
843 goto out_dput;
845 error = btrfs_may_create(dir, dentry);
846 if (error)
847 goto out_dput;
850 * even if this name doesn't exist, we may get hash collisions.
851 * check for them now when we can safely fail
853 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
854 dir->i_ino, name,
855 namelen);
856 if (error)
857 goto out_dput;
859 down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
861 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
862 goto out_up_read;
864 if (snap_src) {
865 error = create_snapshot(snap_src, dir, dentry, name, namelen,
866 async_transid, readonly, inherit);
867 } else {
868 error = create_subvol(dir, dentry, name, namelen,
869 async_transid, inherit);
871 if (!error)
872 fsnotify_mkdir(dir, dentry);
873 out_up_read:
874 up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
875 out_dput:
876 dput(dentry);
877 out_unlock:
878 mutex_unlock(&dir->i_mutex);
879 return error;
883 * When we're defragging a range, we don't want to kick it off again
884 * if it is really just waiting for delalloc to send it down.
885 * If we find a nice big extent or delalloc range for the bytes in the
886 * file you want to defrag, we return 0 to let you know to skip this
887 * part of the file
889 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
891 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
892 struct extent_map *em = NULL;
893 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
894 u64 end;
896 read_lock(&em_tree->lock);
897 em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
898 read_unlock(&em_tree->lock);
900 if (em) {
901 end = extent_map_end(em);
902 free_extent_map(em);
903 if (end - offset > thresh)
904 return 0;
906 /* if we already have a nice delalloc here, just stop */
907 thresh /= 2;
908 end = count_range_bits(io_tree, &offset, offset + thresh,
909 thresh, EXTENT_DELALLOC, 1);
910 if (end >= thresh)
911 return 0;
912 return 1;
916 * helper function to walk through a file and find extents
917 * newer than a specific transid, and smaller than thresh.
919 * This is used by the defragging code to find new and small
920 * extents
922 static int find_new_extents(struct btrfs_root *root,
923 struct inode *inode, u64 newer_than,
924 u64 *off, u32 thresh)
926 struct btrfs_path *path;
927 struct btrfs_key min_key;
928 struct extent_buffer *leaf;
929 struct btrfs_file_extent_item *extent;
930 int type;
931 int ret;
932 u64 ino = btrfs_ino(inode);
934 path = btrfs_alloc_path();
935 if (!path)
936 return -ENOMEM;
938 min_key.objectid = ino;
939 min_key.type = BTRFS_EXTENT_DATA_KEY;
940 min_key.offset = *off;
942 while (1) {
943 ret = btrfs_search_forward(root, &min_key, path, newer_than);
944 if (ret != 0)
945 goto none;
946 process_slot:
947 if (min_key.objectid != ino)
948 goto none;
949 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
950 goto none;
952 leaf = path->nodes[0];
953 extent = btrfs_item_ptr(leaf, path->slots[0],
954 struct btrfs_file_extent_item);
956 type = btrfs_file_extent_type(leaf, extent);
957 if (type == BTRFS_FILE_EXTENT_REG &&
958 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
959 check_defrag_in_cache(inode, min_key.offset, thresh)) {
960 *off = min_key.offset;
961 btrfs_free_path(path);
962 return 0;
965 path->slots[0]++;
966 if (path->slots[0] < btrfs_header_nritems(leaf)) {
967 btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
968 goto process_slot;
971 if (min_key.offset == (u64)-1)
972 goto none;
974 min_key.offset++;
975 btrfs_release_path(path);
977 none:
978 btrfs_free_path(path);
979 return -ENOENT;
982 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
984 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
985 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
986 struct extent_map *em;
987 u64 len = PAGE_CACHE_SIZE;
990 * hopefully we have this extent in the tree already, try without
991 * the full extent lock
993 read_lock(&em_tree->lock);
994 em = lookup_extent_mapping(em_tree, start, len);
995 read_unlock(&em_tree->lock);
997 if (!em) {
998 struct extent_state *cached = NULL;
999 u64 end = start + len - 1;
1001 /* get the big lock and read metadata off disk */
1002 lock_extent_bits(io_tree, start, end, 0, &cached);
1003 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
1004 unlock_extent_cached(io_tree, start, end, &cached, GFP_NOFS);
1006 if (IS_ERR(em))
1007 return NULL;
1010 return em;
1013 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1015 struct extent_map *next;
1016 bool ret = true;
1018 /* this is the last extent */
1019 if (em->start + em->len >= i_size_read(inode))
1020 return false;
1022 next = defrag_lookup_extent(inode, em->start + em->len);
1023 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1024 ret = false;
1025 else if ((em->block_start + em->block_len == next->block_start) &&
1026 (em->block_len > 128 * 1024 && next->block_len > 128 * 1024))
1027 ret = false;
1029 free_extent_map(next);
1030 return ret;
1033 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1034 u64 *last_len, u64 *skip, u64 *defrag_end,
1035 int compress)
1037 struct extent_map *em;
1038 int ret = 1;
1039 bool next_mergeable = true;
1040 bool prev_mergeable = true;
1043 * make sure that once we start defragging an extent, we keep on
1044 * defragging it
1046 if (start < *defrag_end)
1047 return 1;
1049 *skip = 0;
1051 em = defrag_lookup_extent(inode, start);
1052 if (!em)
1053 return 0;
1055 /* this will cover holes, and inline extents */
1056 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1057 ret = 0;
1058 goto out;
1061 if (!*defrag_end)
1062 prev_mergeable = false;
1064 next_mergeable = defrag_check_next_extent(inode, em);
1066 * we hit a real extent, if it is big or the next extent is not a
1067 * real extent, don't bother defragging it
1069 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1070 (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1071 ret = 0;
1072 out:
1074 * last_len ends up being a counter of how many bytes we've defragged.
1075 * every time we choose not to defrag an extent, we reset *last_len
1076 * so that the next tiny extent will force a defrag.
1078 * The end result of this is that tiny extents before a single big
1079 * extent will force at least part of that big extent to be defragged.
1081 if (ret) {
1082 *defrag_end = extent_map_end(em);
1083 } else {
1084 *last_len = 0;
1085 *skip = extent_map_end(em);
1086 *defrag_end = 0;
1089 free_extent_map(em);
1090 return ret;
1094 * it doesn't do much good to defrag one or two pages
1095 * at a time. This pulls in a nice chunk of pages
1096 * to COW and defrag.
1098 * It also makes sure the delalloc code has enough
1099 * dirty data to avoid making new small extents as part
1100 * of the defrag
1102 * It's a good idea to start RA on this range
1103 * before calling this.
1105 static int cluster_pages_for_defrag(struct inode *inode,
1106 struct page **pages,
1107 unsigned long start_index,
1108 unsigned long num_pages)
1110 unsigned long file_end;
1111 u64 isize = i_size_read(inode);
1112 u64 page_start;
1113 u64 page_end;
1114 u64 page_cnt;
1115 int ret;
1116 int i;
1117 int i_done;
1118 struct btrfs_ordered_extent *ordered;
1119 struct extent_state *cached_state = NULL;
1120 struct extent_io_tree *tree;
1121 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1123 file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1124 if (!isize || start_index > file_end)
1125 return 0;
1127 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1129 ret = btrfs_delalloc_reserve_space(inode,
1130 start_index << PAGE_CACHE_SHIFT,
1131 page_cnt << PAGE_CACHE_SHIFT);
1132 if (ret)
1133 return ret;
1134 i_done = 0;
1135 tree = &BTRFS_I(inode)->io_tree;
1137 /* step one, lock all the pages */
1138 for (i = 0; i < page_cnt; i++) {
1139 struct page *page;
1140 again:
1141 page = find_or_create_page(inode->i_mapping,
1142 start_index + i, mask);
1143 if (!page)
1144 break;
1146 page_start = page_offset(page);
1147 page_end = page_start + PAGE_CACHE_SIZE - 1;
1148 while (1) {
1149 lock_extent_bits(tree, page_start, page_end,
1150 0, &cached_state);
1151 ordered = btrfs_lookup_ordered_extent(inode,
1152 page_start);
1153 unlock_extent_cached(tree, page_start, page_end,
1154 &cached_state, GFP_NOFS);
1155 if (!ordered)
1156 break;
1158 unlock_page(page);
1159 btrfs_start_ordered_extent(inode, ordered, 1);
1160 btrfs_put_ordered_extent(ordered);
1161 lock_page(page);
1163 * we unlocked the page above, so we need check if
1164 * it was released or not.
1166 if (page->mapping != inode->i_mapping) {
1167 unlock_page(page);
1168 page_cache_release(page);
1169 goto again;
1173 if (!PageUptodate(page)) {
1174 btrfs_readpage(NULL, page);
1175 lock_page(page);
1176 if (!PageUptodate(page)) {
1177 unlock_page(page);
1178 page_cache_release(page);
1179 ret = -EIO;
1180 break;
1184 if (page->mapping != inode->i_mapping) {
1185 unlock_page(page);
1186 page_cache_release(page);
1187 goto again;
1190 pages[i] = page;
1191 i_done++;
1193 if (!i_done || ret)
1194 goto out;
1196 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1197 goto out;
1200 * so now we have a nice long stream of locked
1201 * and up to date pages, lets wait on them
1203 for (i = 0; i < i_done; i++)
1204 wait_on_page_writeback(pages[i]);
1206 page_start = page_offset(pages[0]);
1207 page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1209 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1210 page_start, page_end - 1, 0, &cached_state);
1211 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1212 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1213 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1214 &cached_state, GFP_NOFS);
1216 if (i_done != page_cnt) {
1217 spin_lock(&BTRFS_I(inode)->lock);
1218 BTRFS_I(inode)->outstanding_extents++;
1219 spin_unlock(&BTRFS_I(inode)->lock);
1220 btrfs_delalloc_release_space(inode,
1221 start_index << PAGE_CACHE_SHIFT,
1222 (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1226 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1227 &cached_state, GFP_NOFS);
1229 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1230 page_start, page_end - 1, &cached_state,
1231 GFP_NOFS);
1233 for (i = 0; i < i_done; i++) {
1234 clear_page_dirty_for_io(pages[i]);
1235 ClearPageChecked(pages[i]);
1236 set_page_extent_mapped(pages[i]);
1237 set_page_dirty(pages[i]);
1238 unlock_page(pages[i]);
1239 page_cache_release(pages[i]);
1241 return i_done;
1242 out:
1243 for (i = 0; i < i_done; i++) {
1244 unlock_page(pages[i]);
1245 page_cache_release(pages[i]);
1247 btrfs_delalloc_release_space(inode,
1248 start_index << PAGE_CACHE_SHIFT,
1249 page_cnt << PAGE_CACHE_SHIFT);
1250 return ret;
1254 int btrfs_defrag_file(struct inode *inode, struct file *file,
1255 struct btrfs_ioctl_defrag_range_args *range,
1256 u64 newer_than, unsigned long max_to_defrag)
1258 struct btrfs_root *root = BTRFS_I(inode)->root;
1259 struct file_ra_state *ra = NULL;
1260 unsigned long last_index;
1261 u64 isize = i_size_read(inode);
1262 u64 last_len = 0;
1263 u64 skip = 0;
1264 u64 defrag_end = 0;
1265 u64 newer_off = range->start;
1266 unsigned long i;
1267 unsigned long ra_index = 0;
1268 int ret;
1269 int defrag_count = 0;
1270 int compress_type = BTRFS_COMPRESS_ZLIB;
1271 u32 extent_thresh = range->extent_thresh;
1272 unsigned long max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1273 unsigned long cluster = max_cluster;
1274 u64 new_align = ~((u64)128 * 1024 - 1);
1275 struct page **pages = NULL;
1277 if (isize == 0)
1278 return 0;
1280 if (range->start >= isize)
1281 return -EINVAL;
1283 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1284 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1285 return -EINVAL;
1286 if (range->compress_type)
1287 compress_type = range->compress_type;
1290 if (extent_thresh == 0)
1291 extent_thresh = 256 * 1024;
1294 * if we were not given a file, allocate a readahead
1295 * context
1297 if (!file) {
1298 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1299 if (!ra)
1300 return -ENOMEM;
1301 file_ra_state_init(ra, inode->i_mapping);
1302 } else {
1303 ra = &file->f_ra;
1306 pages = kmalloc_array(max_cluster, sizeof(struct page *),
1307 GFP_NOFS);
1308 if (!pages) {
1309 ret = -ENOMEM;
1310 goto out_ra;
1313 /* find the last page to defrag */
1314 if (range->start + range->len > range->start) {
1315 last_index = min_t(u64, isize - 1,
1316 range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1317 } else {
1318 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1321 if (newer_than) {
1322 ret = find_new_extents(root, inode, newer_than,
1323 &newer_off, 64 * 1024);
1324 if (!ret) {
1325 range->start = newer_off;
1327 * we always align our defrag to help keep
1328 * the extents in the file evenly spaced
1330 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1331 } else
1332 goto out_ra;
1333 } else {
1334 i = range->start >> PAGE_CACHE_SHIFT;
1336 if (!max_to_defrag)
1337 max_to_defrag = last_index - i + 1;
1340 * make writeback starts from i, so the defrag range can be
1341 * written sequentially.
1343 if (i < inode->i_mapping->writeback_index)
1344 inode->i_mapping->writeback_index = i;
1346 while (i <= last_index && defrag_count < max_to_defrag &&
1347 (i < DIV_ROUND_UP(i_size_read(inode), PAGE_CACHE_SIZE))) {
1349 * make sure we stop running if someone unmounts
1350 * the FS
1352 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1353 break;
1355 if (btrfs_defrag_cancelled(root->fs_info)) {
1356 btrfs_debug(root->fs_info, "defrag_file cancelled");
1357 ret = -EAGAIN;
1358 break;
1361 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1362 extent_thresh, &last_len, &skip,
1363 &defrag_end, range->flags &
1364 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1365 unsigned long next;
1367 * the should_defrag function tells us how much to skip
1368 * bump our counter by the suggested amount
1370 next = DIV_ROUND_UP(skip, PAGE_CACHE_SIZE);
1371 i = max(i + 1, next);
1372 continue;
1375 if (!newer_than) {
1376 cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1377 PAGE_CACHE_SHIFT) - i;
1378 cluster = min(cluster, max_cluster);
1379 } else {
1380 cluster = max_cluster;
1383 if (i + cluster > ra_index) {
1384 ra_index = max(i, ra_index);
1385 btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1386 cluster);
1387 ra_index += cluster;
1390 mutex_lock(&inode->i_mutex);
1391 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1392 BTRFS_I(inode)->force_compress = compress_type;
1393 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1394 if (ret < 0) {
1395 mutex_unlock(&inode->i_mutex);
1396 goto out_ra;
1399 defrag_count += ret;
1400 balance_dirty_pages_ratelimited(inode->i_mapping);
1401 mutex_unlock(&inode->i_mutex);
1403 if (newer_than) {
1404 if (newer_off == (u64)-1)
1405 break;
1407 if (ret > 0)
1408 i += ret;
1410 newer_off = max(newer_off + 1,
1411 (u64)i << PAGE_CACHE_SHIFT);
1413 ret = find_new_extents(root, inode,
1414 newer_than, &newer_off,
1415 64 * 1024);
1416 if (!ret) {
1417 range->start = newer_off;
1418 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1419 } else {
1420 break;
1422 } else {
1423 if (ret > 0) {
1424 i += ret;
1425 last_len += ret << PAGE_CACHE_SHIFT;
1426 } else {
1427 i++;
1428 last_len = 0;
1433 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1434 filemap_flush(inode->i_mapping);
1435 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1436 &BTRFS_I(inode)->runtime_flags))
1437 filemap_flush(inode->i_mapping);
1440 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1441 /* the filemap_flush will queue IO into the worker threads, but
1442 * we have to make sure the IO is actually started and that
1443 * ordered extents get created before we return
1445 atomic_inc(&root->fs_info->async_submit_draining);
1446 while (atomic_read(&root->fs_info->nr_async_submits) ||
1447 atomic_read(&root->fs_info->async_delalloc_pages)) {
1448 wait_event(root->fs_info->async_submit_wait,
1449 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1450 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1452 atomic_dec(&root->fs_info->async_submit_draining);
1455 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1456 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1459 ret = defrag_count;
1461 out_ra:
1462 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1463 mutex_lock(&inode->i_mutex);
1464 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1465 mutex_unlock(&inode->i_mutex);
1467 if (!file)
1468 kfree(ra);
1469 kfree(pages);
1470 return ret;
1473 static noinline int btrfs_ioctl_resize(struct file *file,
1474 void __user *arg)
1476 u64 new_size;
1477 u64 old_size;
1478 u64 devid = 1;
1479 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1480 struct btrfs_ioctl_vol_args *vol_args;
1481 struct btrfs_trans_handle *trans;
1482 struct btrfs_device *device = NULL;
1483 char *sizestr;
1484 char *retptr;
1485 char *devstr = NULL;
1486 int ret = 0;
1487 int mod = 0;
1489 if (!capable(CAP_SYS_ADMIN))
1490 return -EPERM;
1492 ret = mnt_want_write_file(file);
1493 if (ret)
1494 return ret;
1496 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1497 1)) {
1498 mnt_drop_write_file(file);
1499 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1502 mutex_lock(&root->fs_info->volume_mutex);
1503 vol_args = memdup_user(arg, sizeof(*vol_args));
1504 if (IS_ERR(vol_args)) {
1505 ret = PTR_ERR(vol_args);
1506 goto out;
1509 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1511 sizestr = vol_args->name;
1512 devstr = strchr(sizestr, ':');
1513 if (devstr) {
1514 sizestr = devstr + 1;
1515 *devstr = '\0';
1516 devstr = vol_args->name;
1517 ret = kstrtoull(devstr, 10, &devid);
1518 if (ret)
1519 goto out_free;
1520 if (!devid) {
1521 ret = -EINVAL;
1522 goto out_free;
1524 btrfs_info(root->fs_info, "resizing devid %llu", devid);
1527 device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1528 if (!device) {
1529 btrfs_info(root->fs_info, "resizer unable to find device %llu",
1530 devid);
1531 ret = -ENODEV;
1532 goto out_free;
1535 if (!device->writeable) {
1536 btrfs_info(root->fs_info,
1537 "resizer unable to apply on readonly device %llu",
1538 devid);
1539 ret = -EPERM;
1540 goto out_free;
1543 if (!strcmp(sizestr, "max"))
1544 new_size = device->bdev->bd_inode->i_size;
1545 else {
1546 if (sizestr[0] == '-') {
1547 mod = -1;
1548 sizestr++;
1549 } else if (sizestr[0] == '+') {
1550 mod = 1;
1551 sizestr++;
1553 new_size = memparse(sizestr, &retptr);
1554 if (*retptr != '\0' || new_size == 0) {
1555 ret = -EINVAL;
1556 goto out_free;
1560 if (device->is_tgtdev_for_dev_replace) {
1561 ret = -EPERM;
1562 goto out_free;
1565 old_size = btrfs_device_get_total_bytes(device);
1567 if (mod < 0) {
1568 if (new_size > old_size) {
1569 ret = -EINVAL;
1570 goto out_free;
1572 new_size = old_size - new_size;
1573 } else if (mod > 0) {
1574 if (new_size > ULLONG_MAX - old_size) {
1575 ret = -ERANGE;
1576 goto out_free;
1578 new_size = old_size + new_size;
1581 if (new_size < 256 * 1024 * 1024) {
1582 ret = -EINVAL;
1583 goto out_free;
1585 if (new_size > device->bdev->bd_inode->i_size) {
1586 ret = -EFBIG;
1587 goto out_free;
1590 new_size = div_u64(new_size, root->sectorsize);
1591 new_size *= root->sectorsize;
1593 btrfs_info_in_rcu(root->fs_info, "new size for %s is %llu",
1594 rcu_str_deref(device->name), new_size);
1596 if (new_size > old_size) {
1597 trans = btrfs_start_transaction(root, 0);
1598 if (IS_ERR(trans)) {
1599 ret = PTR_ERR(trans);
1600 goto out_free;
1602 ret = btrfs_grow_device(trans, device, new_size);
1603 btrfs_commit_transaction(trans, root);
1604 } else if (new_size < old_size) {
1605 ret = btrfs_shrink_device(device, new_size);
1606 } /* equal, nothing need to do */
1608 out_free:
1609 kfree(vol_args);
1610 out:
1611 mutex_unlock(&root->fs_info->volume_mutex);
1612 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1613 mnt_drop_write_file(file);
1614 return ret;
1617 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1618 char *name, unsigned long fd, int subvol,
1619 u64 *transid, bool readonly,
1620 struct btrfs_qgroup_inherit *inherit)
1622 int namelen;
1623 int ret = 0;
1625 if (!S_ISDIR(file_inode(file)->i_mode))
1626 return -ENOTDIR;
1628 ret = mnt_want_write_file(file);
1629 if (ret)
1630 goto out;
1632 namelen = strlen(name);
1633 if (strchr(name, '/')) {
1634 ret = -EINVAL;
1635 goto out_drop_write;
1638 if (name[0] == '.' &&
1639 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1640 ret = -EEXIST;
1641 goto out_drop_write;
1644 if (subvol) {
1645 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1646 NULL, transid, readonly, inherit);
1647 } else {
1648 struct fd src = fdget(fd);
1649 struct inode *src_inode;
1650 if (!src.file) {
1651 ret = -EINVAL;
1652 goto out_drop_write;
1655 src_inode = file_inode(src.file);
1656 if (src_inode->i_sb != file_inode(file)->i_sb) {
1657 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1658 "Snapshot src from another FS");
1659 ret = -EXDEV;
1660 } else if (!inode_owner_or_capable(src_inode)) {
1662 * Subvolume creation is not restricted, but snapshots
1663 * are limited to own subvolumes only
1665 ret = -EPERM;
1666 } else {
1667 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1668 BTRFS_I(src_inode)->root,
1669 transid, readonly, inherit);
1671 fdput(src);
1673 out_drop_write:
1674 mnt_drop_write_file(file);
1675 out:
1676 return ret;
1679 static noinline int btrfs_ioctl_snap_create(struct file *file,
1680 void __user *arg, int subvol)
1682 struct btrfs_ioctl_vol_args *vol_args;
1683 int ret;
1685 if (!S_ISDIR(file_inode(file)->i_mode))
1686 return -ENOTDIR;
1688 vol_args = memdup_user(arg, sizeof(*vol_args));
1689 if (IS_ERR(vol_args))
1690 return PTR_ERR(vol_args);
1691 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1693 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1694 vol_args->fd, subvol,
1695 NULL, false, NULL);
1697 kfree(vol_args);
1698 return ret;
1701 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1702 void __user *arg, int subvol)
1704 struct btrfs_ioctl_vol_args_v2 *vol_args;
1705 int ret;
1706 u64 transid = 0;
1707 u64 *ptr = NULL;
1708 bool readonly = false;
1709 struct btrfs_qgroup_inherit *inherit = NULL;
1711 if (!S_ISDIR(file_inode(file)->i_mode))
1712 return -ENOTDIR;
1714 vol_args = memdup_user(arg, sizeof(*vol_args));
1715 if (IS_ERR(vol_args))
1716 return PTR_ERR(vol_args);
1717 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1719 if (vol_args->flags &
1720 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1721 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1722 ret = -EOPNOTSUPP;
1723 goto free_args;
1726 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1727 ptr = &transid;
1728 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1729 readonly = true;
1730 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1731 if (vol_args->size > PAGE_CACHE_SIZE) {
1732 ret = -EINVAL;
1733 goto free_args;
1735 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1736 if (IS_ERR(inherit)) {
1737 ret = PTR_ERR(inherit);
1738 goto free_args;
1742 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1743 vol_args->fd, subvol, ptr,
1744 readonly, inherit);
1745 if (ret)
1746 goto free_inherit;
1748 if (ptr && copy_to_user(arg +
1749 offsetof(struct btrfs_ioctl_vol_args_v2,
1750 transid),
1751 ptr, sizeof(*ptr)))
1752 ret = -EFAULT;
1754 free_inherit:
1755 kfree(inherit);
1756 free_args:
1757 kfree(vol_args);
1758 return ret;
1761 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1762 void __user *arg)
1764 struct inode *inode = file_inode(file);
1765 struct btrfs_root *root = BTRFS_I(inode)->root;
1766 int ret = 0;
1767 u64 flags = 0;
1769 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1770 return -EINVAL;
1772 down_read(&root->fs_info->subvol_sem);
1773 if (btrfs_root_readonly(root))
1774 flags |= BTRFS_SUBVOL_RDONLY;
1775 up_read(&root->fs_info->subvol_sem);
1777 if (copy_to_user(arg, &flags, sizeof(flags)))
1778 ret = -EFAULT;
1780 return ret;
1783 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1784 void __user *arg)
1786 struct inode *inode = file_inode(file);
1787 struct btrfs_root *root = BTRFS_I(inode)->root;
1788 struct btrfs_trans_handle *trans;
1789 u64 root_flags;
1790 u64 flags;
1791 int ret = 0;
1793 if (!inode_owner_or_capable(inode))
1794 return -EPERM;
1796 ret = mnt_want_write_file(file);
1797 if (ret)
1798 goto out;
1800 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1801 ret = -EINVAL;
1802 goto out_drop_write;
1805 if (copy_from_user(&flags, arg, sizeof(flags))) {
1806 ret = -EFAULT;
1807 goto out_drop_write;
1810 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1811 ret = -EINVAL;
1812 goto out_drop_write;
1815 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1816 ret = -EOPNOTSUPP;
1817 goto out_drop_write;
1820 down_write(&root->fs_info->subvol_sem);
1822 /* nothing to do */
1823 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1824 goto out_drop_sem;
1826 root_flags = btrfs_root_flags(&root->root_item);
1827 if (flags & BTRFS_SUBVOL_RDONLY) {
1828 btrfs_set_root_flags(&root->root_item,
1829 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1830 } else {
1832 * Block RO -> RW transition if this subvolume is involved in
1833 * send
1835 spin_lock(&root->root_item_lock);
1836 if (root->send_in_progress == 0) {
1837 btrfs_set_root_flags(&root->root_item,
1838 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1839 spin_unlock(&root->root_item_lock);
1840 } else {
1841 spin_unlock(&root->root_item_lock);
1842 btrfs_warn(root->fs_info,
1843 "Attempt to set subvolume %llu read-write during send",
1844 root->root_key.objectid);
1845 ret = -EPERM;
1846 goto out_drop_sem;
1850 trans = btrfs_start_transaction(root, 1);
1851 if (IS_ERR(trans)) {
1852 ret = PTR_ERR(trans);
1853 goto out_reset;
1856 ret = btrfs_update_root(trans, root->fs_info->tree_root,
1857 &root->root_key, &root->root_item);
1859 btrfs_commit_transaction(trans, root);
1860 out_reset:
1861 if (ret)
1862 btrfs_set_root_flags(&root->root_item, root_flags);
1863 out_drop_sem:
1864 up_write(&root->fs_info->subvol_sem);
1865 out_drop_write:
1866 mnt_drop_write_file(file);
1867 out:
1868 return ret;
1872 * helper to check if the subvolume references other subvolumes
1874 static noinline int may_destroy_subvol(struct btrfs_root *root)
1876 struct btrfs_path *path;
1877 struct btrfs_dir_item *di;
1878 struct btrfs_key key;
1879 u64 dir_id;
1880 int ret;
1882 path = btrfs_alloc_path();
1883 if (!path)
1884 return -ENOMEM;
1886 /* Make sure this root isn't set as the default subvol */
1887 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1888 di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1889 dir_id, "default", 7, 0);
1890 if (di && !IS_ERR(di)) {
1891 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1892 if (key.objectid == root->root_key.objectid) {
1893 ret = -EPERM;
1894 btrfs_err(root->fs_info, "deleting default subvolume "
1895 "%llu is not allowed", key.objectid);
1896 goto out;
1898 btrfs_release_path(path);
1901 key.objectid = root->root_key.objectid;
1902 key.type = BTRFS_ROOT_REF_KEY;
1903 key.offset = (u64)-1;
1905 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1906 &key, path, 0, 0);
1907 if (ret < 0)
1908 goto out;
1909 BUG_ON(ret == 0);
1911 ret = 0;
1912 if (path->slots[0] > 0) {
1913 path->slots[0]--;
1914 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1915 if (key.objectid == root->root_key.objectid &&
1916 key.type == BTRFS_ROOT_REF_KEY)
1917 ret = -ENOTEMPTY;
1919 out:
1920 btrfs_free_path(path);
1921 return ret;
1924 static noinline int key_in_sk(struct btrfs_key *key,
1925 struct btrfs_ioctl_search_key *sk)
1927 struct btrfs_key test;
1928 int ret;
1930 test.objectid = sk->min_objectid;
1931 test.type = sk->min_type;
1932 test.offset = sk->min_offset;
1934 ret = btrfs_comp_cpu_keys(key, &test);
1935 if (ret < 0)
1936 return 0;
1938 test.objectid = sk->max_objectid;
1939 test.type = sk->max_type;
1940 test.offset = sk->max_offset;
1942 ret = btrfs_comp_cpu_keys(key, &test);
1943 if (ret > 0)
1944 return 0;
1945 return 1;
1948 static noinline int copy_to_sk(struct btrfs_root *root,
1949 struct btrfs_path *path,
1950 struct btrfs_key *key,
1951 struct btrfs_ioctl_search_key *sk,
1952 size_t *buf_size,
1953 char __user *ubuf,
1954 unsigned long *sk_offset,
1955 int *num_found)
1957 u64 found_transid;
1958 struct extent_buffer *leaf;
1959 struct btrfs_ioctl_search_header sh;
1960 struct btrfs_key test;
1961 unsigned long item_off;
1962 unsigned long item_len;
1963 int nritems;
1964 int i;
1965 int slot;
1966 int ret = 0;
1968 leaf = path->nodes[0];
1969 slot = path->slots[0];
1970 nritems = btrfs_header_nritems(leaf);
1972 if (btrfs_header_generation(leaf) > sk->max_transid) {
1973 i = nritems;
1974 goto advance_key;
1976 found_transid = btrfs_header_generation(leaf);
1978 for (i = slot; i < nritems; i++) {
1979 item_off = btrfs_item_ptr_offset(leaf, i);
1980 item_len = btrfs_item_size_nr(leaf, i);
1982 btrfs_item_key_to_cpu(leaf, key, i);
1983 if (!key_in_sk(key, sk))
1984 continue;
1986 if (sizeof(sh) + item_len > *buf_size) {
1987 if (*num_found) {
1988 ret = 1;
1989 goto out;
1993 * return one empty item back for v1, which does not
1994 * handle -EOVERFLOW
1997 *buf_size = sizeof(sh) + item_len;
1998 item_len = 0;
1999 ret = -EOVERFLOW;
2002 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2003 ret = 1;
2004 goto out;
2007 sh.objectid = key->objectid;
2008 sh.offset = key->offset;
2009 sh.type = key->type;
2010 sh.len = item_len;
2011 sh.transid = found_transid;
2013 /* copy search result header */
2014 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2015 ret = -EFAULT;
2016 goto out;
2019 *sk_offset += sizeof(sh);
2021 if (item_len) {
2022 char __user *up = ubuf + *sk_offset;
2023 /* copy the item */
2024 if (read_extent_buffer_to_user(leaf, up,
2025 item_off, item_len)) {
2026 ret = -EFAULT;
2027 goto out;
2030 *sk_offset += item_len;
2032 (*num_found)++;
2034 if (ret) /* -EOVERFLOW from above */
2035 goto out;
2037 if (*num_found >= sk->nr_items) {
2038 ret = 1;
2039 goto out;
2042 advance_key:
2043 ret = 0;
2044 test.objectid = sk->max_objectid;
2045 test.type = sk->max_type;
2046 test.offset = sk->max_offset;
2047 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2048 ret = 1;
2049 else if (key->offset < (u64)-1)
2050 key->offset++;
2051 else if (key->type < (u8)-1) {
2052 key->offset = 0;
2053 key->type++;
2054 } else if (key->objectid < (u64)-1) {
2055 key->offset = 0;
2056 key->type = 0;
2057 key->objectid++;
2058 } else
2059 ret = 1;
2060 out:
2062 * 0: all items from this leaf copied, continue with next
2063 * 1: * more items can be copied, but unused buffer is too small
2064 * * all items were found
2065 * Either way, it will stops the loop which iterates to the next
2066 * leaf
2067 * -EOVERFLOW: item was to large for buffer
2068 * -EFAULT: could not copy extent buffer back to userspace
2070 return ret;
2073 static noinline int search_ioctl(struct inode *inode,
2074 struct btrfs_ioctl_search_key *sk,
2075 size_t *buf_size,
2076 char __user *ubuf)
2078 struct btrfs_root *root;
2079 struct btrfs_key key;
2080 struct btrfs_path *path;
2081 struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
2082 int ret;
2083 int num_found = 0;
2084 unsigned long sk_offset = 0;
2086 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2087 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2088 return -EOVERFLOW;
2091 path = btrfs_alloc_path();
2092 if (!path)
2093 return -ENOMEM;
2095 if (sk->tree_id == 0) {
2096 /* search the root of the inode that was passed */
2097 root = BTRFS_I(inode)->root;
2098 } else {
2099 key.objectid = sk->tree_id;
2100 key.type = BTRFS_ROOT_ITEM_KEY;
2101 key.offset = (u64)-1;
2102 root = btrfs_read_fs_root_no_name(info, &key);
2103 if (IS_ERR(root)) {
2104 btrfs_err(info, "could not find root %llu",
2105 sk->tree_id);
2106 btrfs_free_path(path);
2107 return -ENOENT;
2111 key.objectid = sk->min_objectid;
2112 key.type = sk->min_type;
2113 key.offset = sk->min_offset;
2115 while (1) {
2116 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2117 if (ret != 0) {
2118 if (ret > 0)
2119 ret = 0;
2120 goto err;
2122 ret = copy_to_sk(root, path, &key, sk, buf_size, ubuf,
2123 &sk_offset, &num_found);
2124 btrfs_release_path(path);
2125 if (ret)
2126 break;
2129 if (ret > 0)
2130 ret = 0;
2131 err:
2132 sk->nr_items = num_found;
2133 btrfs_free_path(path);
2134 return ret;
2137 static noinline int btrfs_ioctl_tree_search(struct file *file,
2138 void __user *argp)
2140 struct btrfs_ioctl_search_args __user *uargs;
2141 struct btrfs_ioctl_search_key sk;
2142 struct inode *inode;
2143 int ret;
2144 size_t buf_size;
2146 if (!capable(CAP_SYS_ADMIN))
2147 return -EPERM;
2149 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2151 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2152 return -EFAULT;
2154 buf_size = sizeof(uargs->buf);
2156 inode = file_inode(file);
2157 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2160 * In the origin implementation an overflow is handled by returning a
2161 * search header with a len of zero, so reset ret.
2163 if (ret == -EOVERFLOW)
2164 ret = 0;
2166 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2167 ret = -EFAULT;
2168 return ret;
2171 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2172 void __user *argp)
2174 struct btrfs_ioctl_search_args_v2 __user *uarg;
2175 struct btrfs_ioctl_search_args_v2 args;
2176 struct inode *inode;
2177 int ret;
2178 size_t buf_size;
2179 const size_t buf_limit = 16 * 1024 * 1024;
2181 if (!capable(CAP_SYS_ADMIN))
2182 return -EPERM;
2184 /* copy search header and buffer size */
2185 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2186 if (copy_from_user(&args, uarg, sizeof(args)))
2187 return -EFAULT;
2189 buf_size = args.buf_size;
2191 if (buf_size < sizeof(struct btrfs_ioctl_search_header))
2192 return -EOVERFLOW;
2194 /* limit result size to 16MB */
2195 if (buf_size > buf_limit)
2196 buf_size = buf_limit;
2198 inode = file_inode(file);
2199 ret = search_ioctl(inode, &args.key, &buf_size,
2200 (char *)(&uarg->buf[0]));
2201 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2202 ret = -EFAULT;
2203 else if (ret == -EOVERFLOW &&
2204 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2205 ret = -EFAULT;
2207 return ret;
2211 * Search INODE_REFs to identify path name of 'dirid' directory
2212 * in a 'tree_id' tree. and sets path name to 'name'.
2214 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2215 u64 tree_id, u64 dirid, char *name)
2217 struct btrfs_root *root;
2218 struct btrfs_key key;
2219 char *ptr;
2220 int ret = -1;
2221 int slot;
2222 int len;
2223 int total_len = 0;
2224 struct btrfs_inode_ref *iref;
2225 struct extent_buffer *l;
2226 struct btrfs_path *path;
2228 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2229 name[0]='\0';
2230 return 0;
2233 path = btrfs_alloc_path();
2234 if (!path)
2235 return -ENOMEM;
2237 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2239 key.objectid = tree_id;
2240 key.type = BTRFS_ROOT_ITEM_KEY;
2241 key.offset = (u64)-1;
2242 root = btrfs_read_fs_root_no_name(info, &key);
2243 if (IS_ERR(root)) {
2244 btrfs_err(info, "could not find root %llu", tree_id);
2245 ret = -ENOENT;
2246 goto out;
2249 key.objectid = dirid;
2250 key.type = BTRFS_INODE_REF_KEY;
2251 key.offset = (u64)-1;
2253 while (1) {
2254 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2255 if (ret < 0)
2256 goto out;
2257 else if (ret > 0) {
2258 ret = btrfs_previous_item(root, path, dirid,
2259 BTRFS_INODE_REF_KEY);
2260 if (ret < 0)
2261 goto out;
2262 else if (ret > 0) {
2263 ret = -ENOENT;
2264 goto out;
2268 l = path->nodes[0];
2269 slot = path->slots[0];
2270 btrfs_item_key_to_cpu(l, &key, slot);
2272 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2273 len = btrfs_inode_ref_name_len(l, iref);
2274 ptr -= len + 1;
2275 total_len += len + 1;
2276 if (ptr < name) {
2277 ret = -ENAMETOOLONG;
2278 goto out;
2281 *(ptr + len) = '/';
2282 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2284 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2285 break;
2287 btrfs_release_path(path);
2288 key.objectid = key.offset;
2289 key.offset = (u64)-1;
2290 dirid = key.objectid;
2292 memmove(name, ptr, total_len);
2293 name[total_len] = '\0';
2294 ret = 0;
2295 out:
2296 btrfs_free_path(path);
2297 return ret;
2300 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2301 void __user *argp)
2303 struct btrfs_ioctl_ino_lookup_args *args;
2304 struct inode *inode;
2305 int ret = 0;
2307 args = memdup_user(argp, sizeof(*args));
2308 if (IS_ERR(args))
2309 return PTR_ERR(args);
2311 inode = file_inode(file);
2314 * Unprivileged query to obtain the containing subvolume root id. The
2315 * path is reset so it's consistent with btrfs_search_path_in_tree.
2317 if (args->treeid == 0)
2318 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2320 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2321 args->name[0] = 0;
2322 goto out;
2325 if (!capable(CAP_SYS_ADMIN)) {
2326 ret = -EPERM;
2327 goto out;
2330 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2331 args->treeid, args->objectid,
2332 args->name);
2334 out:
2335 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2336 ret = -EFAULT;
2338 kfree(args);
2339 return ret;
2342 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2343 void __user *arg)
2345 struct dentry *parent = file->f_path.dentry;
2346 struct dentry *dentry;
2347 struct inode *dir = d_inode(parent);
2348 struct inode *inode;
2349 struct btrfs_root *root = BTRFS_I(dir)->root;
2350 struct btrfs_root *dest = NULL;
2351 struct btrfs_ioctl_vol_args *vol_args;
2352 struct btrfs_trans_handle *trans;
2353 struct btrfs_block_rsv block_rsv;
2354 u64 root_flags;
2355 u64 qgroup_reserved;
2356 int namelen;
2357 int ret;
2358 int err = 0;
2360 if (!S_ISDIR(dir->i_mode))
2361 return -ENOTDIR;
2363 vol_args = memdup_user(arg, sizeof(*vol_args));
2364 if (IS_ERR(vol_args))
2365 return PTR_ERR(vol_args);
2367 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2368 namelen = strlen(vol_args->name);
2369 if (strchr(vol_args->name, '/') ||
2370 strncmp(vol_args->name, "..", namelen) == 0) {
2371 err = -EINVAL;
2372 goto out;
2375 err = mnt_want_write_file(file);
2376 if (err)
2377 goto out;
2380 err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2381 if (err == -EINTR)
2382 goto out_drop_write;
2383 dentry = lookup_one_len(vol_args->name, parent, namelen);
2384 if (IS_ERR(dentry)) {
2385 err = PTR_ERR(dentry);
2386 goto out_unlock_dir;
2389 if (d_really_is_negative(dentry)) {
2390 err = -ENOENT;
2391 goto out_dput;
2394 inode = d_inode(dentry);
2395 dest = BTRFS_I(inode)->root;
2396 if (!capable(CAP_SYS_ADMIN)) {
2398 * Regular user. Only allow this with a special mount
2399 * option, when the user has write+exec access to the
2400 * subvol root, and when rmdir(2) would have been
2401 * allowed.
2403 * Note that this is _not_ check that the subvol is
2404 * empty or doesn't contain data that we wouldn't
2405 * otherwise be able to delete.
2407 * Users who want to delete empty subvols should try
2408 * rmdir(2).
2410 err = -EPERM;
2411 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2412 goto out_dput;
2415 * Do not allow deletion if the parent dir is the same
2416 * as the dir to be deleted. That means the ioctl
2417 * must be called on the dentry referencing the root
2418 * of the subvol, not a random directory contained
2419 * within it.
2421 err = -EINVAL;
2422 if (root == dest)
2423 goto out_dput;
2425 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2426 if (err)
2427 goto out_dput;
2430 /* check if subvolume may be deleted by a user */
2431 err = btrfs_may_delete(dir, dentry, 1);
2432 if (err)
2433 goto out_dput;
2435 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2436 err = -EINVAL;
2437 goto out_dput;
2440 mutex_lock(&inode->i_mutex);
2443 * Don't allow to delete a subvolume with send in progress. This is
2444 * inside the i_mutex so the error handling that has to drop the bit
2445 * again is not run concurrently.
2447 spin_lock(&dest->root_item_lock);
2448 root_flags = btrfs_root_flags(&dest->root_item);
2449 if (dest->send_in_progress == 0) {
2450 btrfs_set_root_flags(&dest->root_item,
2451 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2452 spin_unlock(&dest->root_item_lock);
2453 } else {
2454 spin_unlock(&dest->root_item_lock);
2455 btrfs_warn(root->fs_info,
2456 "Attempt to delete subvolume %llu during send",
2457 dest->root_key.objectid);
2458 err = -EPERM;
2459 goto out_unlock_inode;
2462 down_write(&root->fs_info->subvol_sem);
2464 err = may_destroy_subvol(dest);
2465 if (err)
2466 goto out_up_write;
2468 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2470 * One for dir inode, two for dir entries, two for root
2471 * ref/backref.
2473 err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2474 5, &qgroup_reserved, true);
2475 if (err)
2476 goto out_up_write;
2478 trans = btrfs_start_transaction(root, 0);
2479 if (IS_ERR(trans)) {
2480 err = PTR_ERR(trans);
2481 goto out_release;
2483 trans->block_rsv = &block_rsv;
2484 trans->bytes_reserved = block_rsv.size;
2486 ret = btrfs_unlink_subvol(trans, root, dir,
2487 dest->root_key.objectid,
2488 dentry->d_name.name,
2489 dentry->d_name.len);
2490 if (ret) {
2491 err = ret;
2492 btrfs_abort_transaction(trans, root, ret);
2493 goto out_end_trans;
2496 btrfs_record_root_in_trans(trans, dest);
2498 memset(&dest->root_item.drop_progress, 0,
2499 sizeof(dest->root_item.drop_progress));
2500 dest->root_item.drop_level = 0;
2501 btrfs_set_root_refs(&dest->root_item, 0);
2503 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
2504 ret = btrfs_insert_orphan_item(trans,
2505 root->fs_info->tree_root,
2506 dest->root_key.objectid);
2507 if (ret) {
2508 btrfs_abort_transaction(trans, root, ret);
2509 err = ret;
2510 goto out_end_trans;
2514 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2515 dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2516 dest->root_key.objectid);
2517 if (ret && ret != -ENOENT) {
2518 btrfs_abort_transaction(trans, root, ret);
2519 err = ret;
2520 goto out_end_trans;
2522 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2523 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2524 dest->root_item.received_uuid,
2525 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2526 dest->root_key.objectid);
2527 if (ret && ret != -ENOENT) {
2528 btrfs_abort_transaction(trans, root, ret);
2529 err = ret;
2530 goto out_end_trans;
2534 out_end_trans:
2535 trans->block_rsv = NULL;
2536 trans->bytes_reserved = 0;
2537 ret = btrfs_end_transaction(trans, root);
2538 if (ret && !err)
2539 err = ret;
2540 inode->i_flags |= S_DEAD;
2541 out_release:
2542 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2543 out_up_write:
2544 up_write(&root->fs_info->subvol_sem);
2545 if (err) {
2546 spin_lock(&dest->root_item_lock);
2547 root_flags = btrfs_root_flags(&dest->root_item);
2548 btrfs_set_root_flags(&dest->root_item,
2549 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2550 spin_unlock(&dest->root_item_lock);
2552 out_unlock_inode:
2553 mutex_unlock(&inode->i_mutex);
2554 if (!err) {
2555 d_invalidate(dentry);
2556 btrfs_invalidate_inodes(dest);
2557 d_delete(dentry);
2558 ASSERT(dest->send_in_progress == 0);
2560 /* the last ref */
2561 if (dest->ino_cache_inode) {
2562 iput(dest->ino_cache_inode);
2563 dest->ino_cache_inode = NULL;
2566 out_dput:
2567 dput(dentry);
2568 out_unlock_dir:
2569 mutex_unlock(&dir->i_mutex);
2570 out_drop_write:
2571 mnt_drop_write_file(file);
2572 out:
2573 kfree(vol_args);
2574 return err;
2577 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2579 struct inode *inode = file_inode(file);
2580 struct btrfs_root *root = BTRFS_I(inode)->root;
2581 struct btrfs_ioctl_defrag_range_args *range;
2582 int ret;
2584 ret = mnt_want_write_file(file);
2585 if (ret)
2586 return ret;
2588 if (btrfs_root_readonly(root)) {
2589 ret = -EROFS;
2590 goto out;
2593 switch (inode->i_mode & S_IFMT) {
2594 case S_IFDIR:
2595 if (!capable(CAP_SYS_ADMIN)) {
2596 ret = -EPERM;
2597 goto out;
2599 ret = btrfs_defrag_root(root);
2600 if (ret)
2601 goto out;
2602 ret = btrfs_defrag_root(root->fs_info->extent_root);
2603 break;
2604 case S_IFREG:
2605 if (!(file->f_mode & FMODE_WRITE)) {
2606 ret = -EINVAL;
2607 goto out;
2610 range = kzalloc(sizeof(*range), GFP_KERNEL);
2611 if (!range) {
2612 ret = -ENOMEM;
2613 goto out;
2616 if (argp) {
2617 if (copy_from_user(range, argp,
2618 sizeof(*range))) {
2619 ret = -EFAULT;
2620 kfree(range);
2621 goto out;
2623 /* compression requires us to start the IO */
2624 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2625 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2626 range->extent_thresh = (u32)-1;
2628 } else {
2629 /* the rest are all set to zero by kzalloc */
2630 range->len = (u64)-1;
2632 ret = btrfs_defrag_file(file_inode(file), file,
2633 range, 0, 0);
2634 if (ret > 0)
2635 ret = 0;
2636 kfree(range);
2637 break;
2638 default:
2639 ret = -EINVAL;
2641 out:
2642 mnt_drop_write_file(file);
2643 return ret;
2646 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2648 struct btrfs_ioctl_vol_args *vol_args;
2649 int ret;
2651 if (!capable(CAP_SYS_ADMIN))
2652 return -EPERM;
2654 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2655 1)) {
2656 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2659 mutex_lock(&root->fs_info->volume_mutex);
2660 vol_args = memdup_user(arg, sizeof(*vol_args));
2661 if (IS_ERR(vol_args)) {
2662 ret = PTR_ERR(vol_args);
2663 goto out;
2666 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2667 ret = btrfs_init_new_device(root, vol_args->name);
2669 if (!ret)
2670 btrfs_info(root->fs_info, "disk added %s",vol_args->name);
2672 kfree(vol_args);
2673 out:
2674 mutex_unlock(&root->fs_info->volume_mutex);
2675 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2676 return ret;
2679 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2681 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2682 struct btrfs_ioctl_vol_args *vol_args;
2683 int ret;
2685 if (!capable(CAP_SYS_ADMIN))
2686 return -EPERM;
2688 ret = mnt_want_write_file(file);
2689 if (ret)
2690 return ret;
2692 vol_args = memdup_user(arg, sizeof(*vol_args));
2693 if (IS_ERR(vol_args)) {
2694 ret = PTR_ERR(vol_args);
2695 goto err_drop;
2698 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2700 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2701 1)) {
2702 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2703 goto out;
2706 mutex_lock(&root->fs_info->volume_mutex);
2707 ret = btrfs_rm_device(root, vol_args->name);
2708 mutex_unlock(&root->fs_info->volume_mutex);
2709 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2711 if (!ret)
2712 btrfs_info(root->fs_info, "disk deleted %s",vol_args->name);
2714 out:
2715 kfree(vol_args);
2716 err_drop:
2717 mnt_drop_write_file(file);
2718 return ret;
2721 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2723 struct btrfs_ioctl_fs_info_args *fi_args;
2724 struct btrfs_device *device;
2725 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2726 int ret = 0;
2728 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2729 if (!fi_args)
2730 return -ENOMEM;
2732 mutex_lock(&fs_devices->device_list_mutex);
2733 fi_args->num_devices = fs_devices->num_devices;
2734 memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2736 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2737 if (device->devid > fi_args->max_id)
2738 fi_args->max_id = device->devid;
2740 mutex_unlock(&fs_devices->device_list_mutex);
2742 fi_args->nodesize = root->fs_info->super_copy->nodesize;
2743 fi_args->sectorsize = root->fs_info->super_copy->sectorsize;
2744 fi_args->clone_alignment = root->fs_info->super_copy->sectorsize;
2746 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2747 ret = -EFAULT;
2749 kfree(fi_args);
2750 return ret;
2753 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2755 struct btrfs_ioctl_dev_info_args *di_args;
2756 struct btrfs_device *dev;
2757 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2758 int ret = 0;
2759 char *s_uuid = NULL;
2761 di_args = memdup_user(arg, sizeof(*di_args));
2762 if (IS_ERR(di_args))
2763 return PTR_ERR(di_args);
2765 if (!btrfs_is_empty_uuid(di_args->uuid))
2766 s_uuid = di_args->uuid;
2768 mutex_lock(&fs_devices->device_list_mutex);
2769 dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2771 if (!dev) {
2772 ret = -ENODEV;
2773 goto out;
2776 di_args->devid = dev->devid;
2777 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
2778 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2779 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2780 if (dev->name) {
2781 struct rcu_string *name;
2783 rcu_read_lock();
2784 name = rcu_dereference(dev->name);
2785 strncpy(di_args->path, name->str, sizeof(di_args->path));
2786 rcu_read_unlock();
2787 di_args->path[sizeof(di_args->path) - 1] = 0;
2788 } else {
2789 di_args->path[0] = '\0';
2792 out:
2793 mutex_unlock(&fs_devices->device_list_mutex);
2794 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2795 ret = -EFAULT;
2797 kfree(di_args);
2798 return ret;
2801 static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2803 struct page *page;
2805 page = grab_cache_page(inode->i_mapping, index);
2806 if (!page)
2807 return ERR_PTR(-ENOMEM);
2809 if (!PageUptodate(page)) {
2810 int ret;
2812 ret = btrfs_readpage(NULL, page);
2813 if (ret)
2814 return ERR_PTR(ret);
2815 lock_page(page);
2816 if (!PageUptodate(page)) {
2817 unlock_page(page);
2818 page_cache_release(page);
2819 return ERR_PTR(-EIO);
2821 if (page->mapping != inode->i_mapping) {
2822 unlock_page(page);
2823 page_cache_release(page);
2824 return ERR_PTR(-EAGAIN);
2828 return page;
2831 static int gather_extent_pages(struct inode *inode, struct page **pages,
2832 int num_pages, u64 off)
2834 int i;
2835 pgoff_t index = off >> PAGE_CACHE_SHIFT;
2837 for (i = 0; i < num_pages; i++) {
2838 again:
2839 pages[i] = extent_same_get_page(inode, index + i);
2840 if (IS_ERR(pages[i])) {
2841 int err = PTR_ERR(pages[i]);
2843 if (err == -EAGAIN)
2844 goto again;
2845 pages[i] = NULL;
2846 return err;
2849 return 0;
2852 static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2853 bool retry_range_locking)
2856 * Do any pending delalloc/csum calculations on inode, one way or
2857 * another, and lock file content.
2858 * The locking order is:
2860 * 1) pages
2861 * 2) range in the inode's io tree
2863 while (1) {
2864 struct btrfs_ordered_extent *ordered;
2865 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2866 ordered = btrfs_lookup_first_ordered_extent(inode,
2867 off + len - 1);
2868 if ((!ordered ||
2869 ordered->file_offset + ordered->len <= off ||
2870 ordered->file_offset >= off + len) &&
2871 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2872 off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2873 if (ordered)
2874 btrfs_put_ordered_extent(ordered);
2875 break;
2877 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2878 if (ordered)
2879 btrfs_put_ordered_extent(ordered);
2880 if (!retry_range_locking)
2881 return -EAGAIN;
2882 btrfs_wait_ordered_range(inode, off, len);
2884 return 0;
2887 static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2889 mutex_unlock(&inode1->i_mutex);
2890 mutex_unlock(&inode2->i_mutex);
2893 static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2895 if (inode1 < inode2)
2896 swap(inode1, inode2);
2898 mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2899 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2902 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2903 struct inode *inode2, u64 loff2, u64 len)
2905 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2906 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2909 static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2910 struct inode *inode2, u64 loff2, u64 len,
2911 bool retry_range_locking)
2913 int ret;
2915 if (inode1 < inode2) {
2916 swap(inode1, inode2);
2917 swap(loff1, loff2);
2919 ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2920 if (ret)
2921 return ret;
2922 ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2923 if (ret)
2924 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2925 loff1 + len - 1);
2926 return ret;
2929 struct cmp_pages {
2930 int num_pages;
2931 struct page **src_pages;
2932 struct page **dst_pages;
2935 static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2937 int i;
2938 struct page *pg;
2940 for (i = 0; i < cmp->num_pages; i++) {
2941 pg = cmp->src_pages[i];
2942 if (pg) {
2943 unlock_page(pg);
2944 page_cache_release(pg);
2946 pg = cmp->dst_pages[i];
2947 if (pg) {
2948 unlock_page(pg);
2949 page_cache_release(pg);
2952 kfree(cmp->src_pages);
2953 kfree(cmp->dst_pages);
2956 static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2957 struct inode *dst, u64 dst_loff,
2958 u64 len, struct cmp_pages *cmp)
2960 int ret;
2961 int num_pages = PAGE_CACHE_ALIGN(len) >> PAGE_CACHE_SHIFT;
2962 struct page **src_pgarr, **dst_pgarr;
2965 * We must gather up all the pages before we initiate our
2966 * extent locking. We use an array for the page pointers. Size
2967 * of the array is bounded by len, which is in turn bounded by
2968 * BTRFS_MAX_DEDUPE_LEN.
2970 src_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2971 dst_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2972 if (!src_pgarr || !dst_pgarr) {
2973 kfree(src_pgarr);
2974 kfree(dst_pgarr);
2975 return -ENOMEM;
2977 cmp->num_pages = num_pages;
2978 cmp->src_pages = src_pgarr;
2979 cmp->dst_pages = dst_pgarr;
2981 ret = gather_extent_pages(src, cmp->src_pages, cmp->num_pages, loff);
2982 if (ret)
2983 goto out;
2985 ret = gather_extent_pages(dst, cmp->dst_pages, cmp->num_pages, dst_loff);
2987 out:
2988 if (ret)
2989 btrfs_cmp_data_free(cmp);
2990 return ret;
2993 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2994 u64 dst_loff, u64 len, struct cmp_pages *cmp)
2996 int ret = 0;
2997 int i;
2998 struct page *src_page, *dst_page;
2999 unsigned int cmp_len = PAGE_CACHE_SIZE;
3000 void *addr, *dst_addr;
3002 i = 0;
3003 while (len) {
3004 if (len < PAGE_CACHE_SIZE)
3005 cmp_len = len;
3007 BUG_ON(i >= cmp->num_pages);
3009 src_page = cmp->src_pages[i];
3010 dst_page = cmp->dst_pages[i];
3011 ASSERT(PageLocked(src_page));
3012 ASSERT(PageLocked(dst_page));
3014 addr = kmap_atomic(src_page);
3015 dst_addr = kmap_atomic(dst_page);
3017 flush_dcache_page(src_page);
3018 flush_dcache_page(dst_page);
3020 if (memcmp(addr, dst_addr, cmp_len))
3021 ret = BTRFS_SAME_DATA_DIFFERS;
3023 kunmap_atomic(addr);
3024 kunmap_atomic(dst_addr);
3026 if (ret)
3027 break;
3029 len -= cmp_len;
3030 i++;
3033 return ret;
3036 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3037 u64 olen)
3039 u64 len = *plen;
3040 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3042 if (off + olen > inode->i_size || off + olen < off)
3043 return -EINVAL;
3045 /* if we extend to eof, continue to block boundary */
3046 if (off + len == inode->i_size)
3047 *plen = len = ALIGN(inode->i_size, bs) - off;
3049 /* Check that we are block aligned - btrfs_clone() requires this */
3050 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3051 return -EINVAL;
3053 return 0;
3056 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3057 struct inode *dst, u64 dst_loff)
3059 int ret;
3060 u64 len = olen;
3061 struct cmp_pages cmp;
3062 int same_inode = 0;
3063 u64 same_lock_start = 0;
3064 u64 same_lock_len = 0;
3066 if (src == dst)
3067 same_inode = 1;
3069 if (len == 0)
3070 return 0;
3072 if (same_inode) {
3073 mutex_lock(&src->i_mutex);
3075 ret = extent_same_check_offsets(src, loff, &len, olen);
3076 if (ret)
3077 goto out_unlock;
3080 * Single inode case wants the same checks, except we
3081 * don't want our length pushed out past i_size as
3082 * comparing that data range makes no sense.
3084 * extent_same_check_offsets() will do this for an
3085 * unaligned length at i_size, so catch it here and
3086 * reject the request.
3088 * This effectively means we require aligned extents
3089 * for the single-inode case, whereas the other cases
3090 * allow an unaligned length so long as it ends at
3091 * i_size.
3093 if (len != olen) {
3094 ret = -EINVAL;
3095 goto out_unlock;
3098 /* Check for overlapping ranges */
3099 if (dst_loff + len > loff && dst_loff < loff + len) {
3100 ret = -EINVAL;
3101 goto out_unlock;
3104 same_lock_start = min_t(u64, loff, dst_loff);
3105 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
3106 } else {
3107 btrfs_double_inode_lock(src, dst);
3109 ret = extent_same_check_offsets(src, loff, &len, olen);
3110 if (ret)
3111 goto out_unlock;
3113 ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3114 if (ret)
3115 goto out_unlock;
3118 /* don't make the dst file partly checksummed */
3119 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3120 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3121 ret = -EINVAL;
3122 goto out_unlock;
3125 again:
3126 ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3127 if (ret)
3128 goto out_unlock;
3130 if (same_inode)
3131 ret = lock_extent_range(src, same_lock_start, same_lock_len,
3132 false);
3133 else
3134 ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3135 false);
3137 * If one of the inodes has dirty pages in the respective range or
3138 * ordered extents, we need to flush dellaloc and wait for all ordered
3139 * extents in the range. We must unlock the pages and the ranges in the
3140 * io trees to avoid deadlocks when flushing delalloc (requires locking
3141 * pages) and when waiting for ordered extents to complete (they require
3142 * range locking).
3144 if (ret == -EAGAIN) {
3146 * Ranges in the io trees already unlocked. Now unlock all
3147 * pages before waiting for all IO to complete.
3149 btrfs_cmp_data_free(&cmp);
3150 if (same_inode) {
3151 btrfs_wait_ordered_range(src, same_lock_start,
3152 same_lock_len);
3153 } else {
3154 btrfs_wait_ordered_range(src, loff, len);
3155 btrfs_wait_ordered_range(dst, dst_loff, len);
3157 goto again;
3159 ASSERT(ret == 0);
3160 if (WARN_ON(ret)) {
3161 /* ranges in the io trees already unlocked */
3162 btrfs_cmp_data_free(&cmp);
3163 return ret;
3166 /* pass original length for comparison so we stay within i_size */
3167 ret = btrfs_cmp_data(src, loff, dst, dst_loff, olen, &cmp);
3168 if (ret == 0)
3169 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3171 if (same_inode)
3172 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3173 same_lock_start + same_lock_len - 1);
3174 else
3175 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3177 btrfs_cmp_data_free(&cmp);
3178 out_unlock:
3179 if (same_inode)
3180 mutex_unlock(&src->i_mutex);
3181 else
3182 btrfs_double_inode_unlock(src, dst);
3184 return ret;
3187 #define BTRFS_MAX_DEDUPE_LEN (16 * 1024 * 1024)
3189 static long btrfs_ioctl_file_extent_same(struct file *file,
3190 struct btrfs_ioctl_same_args __user *argp)
3192 struct btrfs_ioctl_same_args *same = NULL;
3193 struct btrfs_ioctl_same_extent_info *info;
3194 struct inode *src = file_inode(file);
3195 u64 off;
3196 u64 len;
3197 int i;
3198 int ret;
3199 unsigned long size;
3200 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3201 bool is_admin = capable(CAP_SYS_ADMIN);
3202 u16 count;
3204 if (!(file->f_mode & FMODE_READ))
3205 return -EINVAL;
3207 ret = mnt_want_write_file(file);
3208 if (ret)
3209 return ret;
3211 if (get_user(count, &argp->dest_count)) {
3212 ret = -EFAULT;
3213 goto out;
3216 size = offsetof(struct btrfs_ioctl_same_args __user, info[count]);
3218 same = memdup_user(argp, size);
3220 if (IS_ERR(same)) {
3221 ret = PTR_ERR(same);
3222 same = NULL;
3223 goto out;
3226 off = same->logical_offset;
3227 len = same->length;
3230 * Limit the total length we will dedupe for each operation.
3231 * This is intended to bound the total time spent in this
3232 * ioctl to something sane.
3234 if (len > BTRFS_MAX_DEDUPE_LEN)
3235 len = BTRFS_MAX_DEDUPE_LEN;
3237 if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
3239 * Btrfs does not support blocksize < page_size. As a
3240 * result, btrfs_cmp_data() won't correctly handle
3241 * this situation without an update.
3243 ret = -EINVAL;
3244 goto out;
3247 ret = -EISDIR;
3248 if (S_ISDIR(src->i_mode))
3249 goto out;
3251 ret = -EACCES;
3252 if (!S_ISREG(src->i_mode))
3253 goto out;
3255 /* pre-format output fields to sane values */
3256 for (i = 0; i < count; i++) {
3257 same->info[i].bytes_deduped = 0ULL;
3258 same->info[i].status = 0;
3261 for (i = 0, info = same->info; i < count; i++, info++) {
3262 struct inode *dst;
3263 struct fd dst_file = fdget(info->fd);
3264 if (!dst_file.file) {
3265 info->status = -EBADF;
3266 continue;
3268 dst = file_inode(dst_file.file);
3270 if (!(is_admin || (dst_file.file->f_mode & FMODE_WRITE))) {
3271 info->status = -EINVAL;
3272 } else if (file->f_path.mnt != dst_file.file->f_path.mnt) {
3273 info->status = -EXDEV;
3274 } else if (S_ISDIR(dst->i_mode)) {
3275 info->status = -EISDIR;
3276 } else if (!S_ISREG(dst->i_mode)) {
3277 info->status = -EACCES;
3278 } else {
3279 info->status = btrfs_extent_same(src, off, len, dst,
3280 info->logical_offset);
3281 if (info->status == 0)
3282 info->bytes_deduped += len;
3284 fdput(dst_file);
3287 ret = copy_to_user(argp, same, size);
3288 if (ret)
3289 ret = -EFAULT;
3291 out:
3292 mnt_drop_write_file(file);
3293 kfree(same);
3294 return ret;
3297 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3298 struct inode *inode,
3299 u64 endoff,
3300 const u64 destoff,
3301 const u64 olen,
3302 int no_time_update)
3304 struct btrfs_root *root = BTRFS_I(inode)->root;
3305 int ret;
3307 inode_inc_iversion(inode);
3308 if (!no_time_update)
3309 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3311 * We round up to the block size at eof when determining which
3312 * extents to clone above, but shouldn't round up the file size.
3314 if (endoff > destoff + olen)
3315 endoff = destoff + olen;
3316 if (endoff > inode->i_size)
3317 btrfs_i_size_write(inode, endoff);
3319 ret = btrfs_update_inode(trans, root, inode);
3320 if (ret) {
3321 btrfs_abort_transaction(trans, root, ret);
3322 btrfs_end_transaction(trans, root);
3323 goto out;
3325 ret = btrfs_end_transaction(trans, root);
3326 out:
3327 return ret;
3330 static void clone_update_extent_map(struct inode *inode,
3331 const struct btrfs_trans_handle *trans,
3332 const struct btrfs_path *path,
3333 const u64 hole_offset,
3334 const u64 hole_len)
3336 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3337 struct extent_map *em;
3338 int ret;
3340 em = alloc_extent_map();
3341 if (!em) {
3342 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3343 &BTRFS_I(inode)->runtime_flags);
3344 return;
3347 if (path) {
3348 struct btrfs_file_extent_item *fi;
3350 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3351 struct btrfs_file_extent_item);
3352 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
3353 em->generation = -1;
3354 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3355 BTRFS_FILE_EXTENT_INLINE)
3356 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3357 &BTRFS_I(inode)->runtime_flags);
3358 } else {
3359 em->start = hole_offset;
3360 em->len = hole_len;
3361 em->ram_bytes = em->len;
3362 em->orig_start = hole_offset;
3363 em->block_start = EXTENT_MAP_HOLE;
3364 em->block_len = 0;
3365 em->orig_block_len = 0;
3366 em->compress_type = BTRFS_COMPRESS_NONE;
3367 em->generation = trans->transid;
3370 while (1) {
3371 write_lock(&em_tree->lock);
3372 ret = add_extent_mapping(em_tree, em, 1);
3373 write_unlock(&em_tree->lock);
3374 if (ret != -EEXIST) {
3375 free_extent_map(em);
3376 break;
3378 btrfs_drop_extent_cache(inode, em->start,
3379 em->start + em->len - 1, 0);
3382 if (ret)
3383 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3384 &BTRFS_I(inode)->runtime_flags);
3388 * Make sure we do not end up inserting an inline extent into a file that has
3389 * already other (non-inline) extents. If a file has an inline extent it can
3390 * not have any other extents and the (single) inline extent must start at the
3391 * file offset 0. Failing to respect these rules will lead to file corruption,
3392 * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3394 * We can have extents that have been already written to disk or we can have
3395 * dirty ranges still in delalloc, in which case the extent maps and items are
3396 * created only when we run delalloc, and the delalloc ranges might fall outside
3397 * the range we are currently locking in the inode's io tree. So we check the
3398 * inode's i_size because of that (i_size updates are done while holding the
3399 * i_mutex, which we are holding here).
3400 * We also check to see if the inode has a size not greater than "datal" but has
3401 * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3402 * protected against such concurrent fallocate calls by the i_mutex).
3404 * If the file has no extents but a size greater than datal, do not allow the
3405 * copy because we would need turn the inline extent into a non-inline one (even
3406 * with NO_HOLES enabled). If we find our destination inode only has one inline
3407 * extent, just overwrite it with the source inline extent if its size is less
3408 * than the source extent's size, or we could copy the source inline extent's
3409 * data into the destination inode's inline extent if the later is greater then
3410 * the former.
3412 static int clone_copy_inline_extent(struct inode *src,
3413 struct inode *dst,
3414 struct btrfs_trans_handle *trans,
3415 struct btrfs_path *path,
3416 struct btrfs_key *new_key,
3417 const u64 drop_start,
3418 const u64 datal,
3419 const u64 skip,
3420 const u64 size,
3421 char *inline_data)
3423 struct btrfs_root *root = BTRFS_I(dst)->root;
3424 const u64 aligned_end = ALIGN(new_key->offset + datal,
3425 root->sectorsize);
3426 int ret;
3427 struct btrfs_key key;
3429 if (new_key->offset > 0)
3430 return -EOPNOTSUPP;
3432 key.objectid = btrfs_ino(dst);
3433 key.type = BTRFS_EXTENT_DATA_KEY;
3434 key.offset = 0;
3435 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3436 if (ret < 0) {
3437 return ret;
3438 } else if (ret > 0) {
3439 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3440 ret = btrfs_next_leaf(root, path);
3441 if (ret < 0)
3442 return ret;
3443 else if (ret > 0)
3444 goto copy_inline_extent;
3446 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3447 if (key.objectid == btrfs_ino(dst) &&
3448 key.type == BTRFS_EXTENT_DATA_KEY) {
3449 ASSERT(key.offset > 0);
3450 return -EOPNOTSUPP;
3452 } else if (i_size_read(dst) <= datal) {
3453 struct btrfs_file_extent_item *ei;
3454 u64 ext_len;
3457 * If the file size is <= datal, make sure there are no other
3458 * extents following (can happen do to an fallocate call with
3459 * the flag FALLOC_FL_KEEP_SIZE).
3461 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3462 struct btrfs_file_extent_item);
3464 * If it's an inline extent, it can not have other extents
3465 * following it.
3467 if (btrfs_file_extent_type(path->nodes[0], ei) ==
3468 BTRFS_FILE_EXTENT_INLINE)
3469 goto copy_inline_extent;
3471 ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3472 if (ext_len > aligned_end)
3473 return -EOPNOTSUPP;
3475 ret = btrfs_next_item(root, path);
3476 if (ret < 0) {
3477 return ret;
3478 } else if (ret == 0) {
3479 btrfs_item_key_to_cpu(path->nodes[0], &key,
3480 path->slots[0]);
3481 if (key.objectid == btrfs_ino(dst) &&
3482 key.type == BTRFS_EXTENT_DATA_KEY)
3483 return -EOPNOTSUPP;
3487 copy_inline_extent:
3489 * We have no extent items, or we have an extent at offset 0 which may
3490 * or may not be inlined. All these cases are dealt the same way.
3492 if (i_size_read(dst) > datal) {
3494 * If the destination inode has an inline extent...
3495 * This would require copying the data from the source inline
3496 * extent into the beginning of the destination's inline extent.
3497 * But this is really complex, both extents can be compressed
3498 * or just one of them, which would require decompressing and
3499 * re-compressing data (which could increase the new compressed
3500 * size, not allowing the compressed data to fit anymore in an
3501 * inline extent).
3502 * So just don't support this case for now (it should be rare,
3503 * we are not really saving space when cloning inline extents).
3505 return -EOPNOTSUPP;
3508 btrfs_release_path(path);
3509 ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3510 if (ret)
3511 return ret;
3512 ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3513 if (ret)
3514 return ret;
3516 if (skip) {
3517 const u32 start = btrfs_file_extent_calc_inline_size(0);
3519 memmove(inline_data + start, inline_data + start + skip, datal);
3522 write_extent_buffer(path->nodes[0], inline_data,
3523 btrfs_item_ptr_offset(path->nodes[0],
3524 path->slots[0]),
3525 size);
3526 inode_add_bytes(dst, datal);
3528 return 0;
3532 * btrfs_clone() - clone a range from inode file to another
3534 * @src: Inode to clone from
3535 * @inode: Inode to clone to
3536 * @off: Offset within source to start clone from
3537 * @olen: Original length, passed by user, of range to clone
3538 * @olen_aligned: Block-aligned value of olen
3539 * @destoff: Offset within @inode to start clone
3540 * @no_time_update: Whether to update mtime/ctime on the target inode
3542 static int btrfs_clone(struct inode *src, struct inode *inode,
3543 const u64 off, const u64 olen, const u64 olen_aligned,
3544 const u64 destoff, int no_time_update)
3546 struct btrfs_root *root = BTRFS_I(inode)->root;
3547 struct btrfs_path *path = NULL;
3548 struct extent_buffer *leaf;
3549 struct btrfs_trans_handle *trans;
3550 char *buf = NULL;
3551 struct btrfs_key key;
3552 u32 nritems;
3553 int slot;
3554 int ret;
3555 const u64 len = olen_aligned;
3556 u64 last_dest_end = destoff;
3558 ret = -ENOMEM;
3559 buf = vmalloc(root->nodesize);
3560 if (!buf)
3561 return ret;
3563 path = btrfs_alloc_path();
3564 if (!path) {
3565 vfree(buf);
3566 return ret;
3569 path->reada = 2;
3570 /* clone data */
3571 key.objectid = btrfs_ino(src);
3572 key.type = BTRFS_EXTENT_DATA_KEY;
3573 key.offset = off;
3575 while (1) {
3576 u64 next_key_min_offset = key.offset + 1;
3579 * note the key will change type as we walk through the
3580 * tree.
3582 path->leave_spinning = 1;
3583 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3584 0, 0);
3585 if (ret < 0)
3586 goto out;
3588 * First search, if no extent item that starts at offset off was
3589 * found but the previous item is an extent item, it's possible
3590 * it might overlap our target range, therefore process it.
3592 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3593 btrfs_item_key_to_cpu(path->nodes[0], &key,
3594 path->slots[0] - 1);
3595 if (key.type == BTRFS_EXTENT_DATA_KEY)
3596 path->slots[0]--;
3599 nritems = btrfs_header_nritems(path->nodes[0]);
3600 process_slot:
3601 if (path->slots[0] >= nritems) {
3602 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3603 if (ret < 0)
3604 goto out;
3605 if (ret > 0)
3606 break;
3607 nritems = btrfs_header_nritems(path->nodes[0]);
3609 leaf = path->nodes[0];
3610 slot = path->slots[0];
3612 btrfs_item_key_to_cpu(leaf, &key, slot);
3613 if (key.type > BTRFS_EXTENT_DATA_KEY ||
3614 key.objectid != btrfs_ino(src))
3615 break;
3617 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3618 struct btrfs_file_extent_item *extent;
3619 int type;
3620 u32 size;
3621 struct btrfs_key new_key;
3622 u64 disko = 0, diskl = 0;
3623 u64 datao = 0, datal = 0;
3624 u8 comp;
3625 u64 drop_start;
3627 extent = btrfs_item_ptr(leaf, slot,
3628 struct btrfs_file_extent_item);
3629 comp = btrfs_file_extent_compression(leaf, extent);
3630 type = btrfs_file_extent_type(leaf, extent);
3631 if (type == BTRFS_FILE_EXTENT_REG ||
3632 type == BTRFS_FILE_EXTENT_PREALLOC) {
3633 disko = btrfs_file_extent_disk_bytenr(leaf,
3634 extent);
3635 diskl = btrfs_file_extent_disk_num_bytes(leaf,
3636 extent);
3637 datao = btrfs_file_extent_offset(leaf, extent);
3638 datal = btrfs_file_extent_num_bytes(leaf,
3639 extent);
3640 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3641 /* take upper bound, may be compressed */
3642 datal = btrfs_file_extent_ram_bytes(leaf,
3643 extent);
3647 * The first search might have left us at an extent
3648 * item that ends before our target range's start, can
3649 * happen if we have holes and NO_HOLES feature enabled.
3651 if (key.offset + datal <= off) {
3652 path->slots[0]++;
3653 goto process_slot;
3654 } else if (key.offset >= off + len) {
3655 break;
3657 next_key_min_offset = key.offset + datal;
3658 size = btrfs_item_size_nr(leaf, slot);
3659 read_extent_buffer(leaf, buf,
3660 btrfs_item_ptr_offset(leaf, slot),
3661 size);
3663 btrfs_release_path(path);
3664 path->leave_spinning = 0;
3666 memcpy(&new_key, &key, sizeof(new_key));
3667 new_key.objectid = btrfs_ino(inode);
3668 if (off <= key.offset)
3669 new_key.offset = key.offset + destoff - off;
3670 else
3671 new_key.offset = destoff;
3674 * Deal with a hole that doesn't have an extent item
3675 * that represents it (NO_HOLES feature enabled).
3676 * This hole is either in the middle of the cloning
3677 * range or at the beginning (fully overlaps it or
3678 * partially overlaps it).
3680 if (new_key.offset != last_dest_end)
3681 drop_start = last_dest_end;
3682 else
3683 drop_start = new_key.offset;
3686 * 1 - adjusting old extent (we may have to split it)
3687 * 1 - add new extent
3688 * 1 - inode update
3690 trans = btrfs_start_transaction(root, 3);
3691 if (IS_ERR(trans)) {
3692 ret = PTR_ERR(trans);
3693 goto out;
3696 if (type == BTRFS_FILE_EXTENT_REG ||
3697 type == BTRFS_FILE_EXTENT_PREALLOC) {
3699 * a | --- range to clone ---| b
3700 * | ------------- extent ------------- |
3703 /* subtract range b */
3704 if (key.offset + datal > off + len)
3705 datal = off + len - key.offset;
3707 /* subtract range a */
3708 if (off > key.offset) {
3709 datao += off - key.offset;
3710 datal -= off - key.offset;
3713 ret = btrfs_drop_extents(trans, root, inode,
3714 drop_start,
3715 new_key.offset + datal,
3717 if (ret) {
3718 if (ret != -EOPNOTSUPP)
3719 btrfs_abort_transaction(trans,
3720 root, ret);
3721 btrfs_end_transaction(trans, root);
3722 goto out;
3725 ret = btrfs_insert_empty_item(trans, root, path,
3726 &new_key, size);
3727 if (ret) {
3728 btrfs_abort_transaction(trans, root,
3729 ret);
3730 btrfs_end_transaction(trans, root);
3731 goto out;
3734 leaf = path->nodes[0];
3735 slot = path->slots[0];
3736 write_extent_buffer(leaf, buf,
3737 btrfs_item_ptr_offset(leaf, slot),
3738 size);
3740 extent = btrfs_item_ptr(leaf, slot,
3741 struct btrfs_file_extent_item);
3743 /* disko == 0 means it's a hole */
3744 if (!disko)
3745 datao = 0;
3747 btrfs_set_file_extent_offset(leaf, extent,
3748 datao);
3749 btrfs_set_file_extent_num_bytes(leaf, extent,
3750 datal);
3752 if (disko) {
3753 inode_add_bytes(inode, datal);
3754 ret = btrfs_inc_extent_ref(trans, root,
3755 disko, diskl, 0,
3756 root->root_key.objectid,
3757 btrfs_ino(inode),
3758 new_key.offset - datao);
3759 if (ret) {
3760 btrfs_abort_transaction(trans,
3761 root,
3762 ret);
3763 btrfs_end_transaction(trans,
3764 root);
3765 goto out;
3769 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3770 u64 skip = 0;
3771 u64 trim = 0;
3773 if (off > key.offset) {
3774 skip = off - key.offset;
3775 new_key.offset += skip;
3778 if (key.offset + datal > off + len)
3779 trim = key.offset + datal - (off + len);
3781 if (comp && (skip || trim)) {
3782 ret = -EINVAL;
3783 btrfs_end_transaction(trans, root);
3784 goto out;
3786 size -= skip + trim;
3787 datal -= skip + trim;
3789 ret = clone_copy_inline_extent(src, inode,
3790 trans, path,
3791 &new_key,
3792 drop_start,
3793 datal,
3794 skip, size, buf);
3795 if (ret) {
3796 if (ret != -EOPNOTSUPP)
3797 btrfs_abort_transaction(trans,
3798 root,
3799 ret);
3800 btrfs_end_transaction(trans, root);
3801 goto out;
3803 leaf = path->nodes[0];
3804 slot = path->slots[0];
3807 /* If we have an implicit hole (NO_HOLES feature). */
3808 if (drop_start < new_key.offset)
3809 clone_update_extent_map(inode, trans,
3810 NULL, drop_start,
3811 new_key.offset - drop_start);
3813 clone_update_extent_map(inode, trans, path, 0, 0);
3815 btrfs_mark_buffer_dirty(leaf);
3816 btrfs_release_path(path);
3818 last_dest_end = ALIGN(new_key.offset + datal,
3819 root->sectorsize);
3820 ret = clone_finish_inode_update(trans, inode,
3821 last_dest_end,
3822 destoff, olen,
3823 no_time_update);
3824 if (ret)
3825 goto out;
3826 if (new_key.offset + datal >= destoff + len)
3827 break;
3829 btrfs_release_path(path);
3830 key.offset = next_key_min_offset;
3832 if (fatal_signal_pending(current)) {
3833 ret = -EINTR;
3834 goto out;
3837 ret = 0;
3839 if (last_dest_end < destoff + len) {
3841 * We have an implicit hole (NO_HOLES feature is enabled) that
3842 * fully or partially overlaps our cloning range at its end.
3844 btrfs_release_path(path);
3847 * 1 - remove extent(s)
3848 * 1 - inode update
3850 trans = btrfs_start_transaction(root, 2);
3851 if (IS_ERR(trans)) {
3852 ret = PTR_ERR(trans);
3853 goto out;
3855 ret = btrfs_drop_extents(trans, root, inode,
3856 last_dest_end, destoff + len, 1);
3857 if (ret) {
3858 if (ret != -EOPNOTSUPP)
3859 btrfs_abort_transaction(trans, root, ret);
3860 btrfs_end_transaction(trans, root);
3861 goto out;
3863 clone_update_extent_map(inode, trans, NULL, last_dest_end,
3864 destoff + len - last_dest_end);
3865 ret = clone_finish_inode_update(trans, inode, destoff + len,
3866 destoff, olen, no_time_update);
3869 out:
3870 btrfs_free_path(path);
3871 vfree(buf);
3872 return ret;
3875 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
3876 u64 off, u64 olen, u64 destoff)
3878 struct inode *inode = file_inode(file);
3879 struct btrfs_root *root = BTRFS_I(inode)->root;
3880 struct fd src_file;
3881 struct inode *src;
3882 int ret;
3883 u64 len = olen;
3884 u64 bs = root->fs_info->sb->s_blocksize;
3885 int same_inode = 0;
3888 * TODO:
3889 * - split compressed inline extents. annoying: we need to
3890 * decompress into destination's address_space (the file offset
3891 * may change, so source mapping won't do), then recompress (or
3892 * otherwise reinsert) a subrange.
3894 * - split destination inode's inline extents. The inline extents can
3895 * be either compressed or non-compressed.
3898 /* the destination must be opened for writing */
3899 if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
3900 return -EINVAL;
3902 if (btrfs_root_readonly(root))
3903 return -EROFS;
3905 ret = mnt_want_write_file(file);
3906 if (ret)
3907 return ret;
3909 src_file = fdget(srcfd);
3910 if (!src_file.file) {
3911 ret = -EBADF;
3912 goto out_drop_write;
3915 ret = -EXDEV;
3916 if (src_file.file->f_path.mnt != file->f_path.mnt)
3917 goto out_fput;
3919 src = file_inode(src_file.file);
3921 ret = -EINVAL;
3922 if (src == inode)
3923 same_inode = 1;
3925 /* the src must be open for reading */
3926 if (!(src_file.file->f_mode & FMODE_READ))
3927 goto out_fput;
3929 ret = -EISDIR;
3930 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3931 goto out_fput;
3933 ret = -EXDEV;
3934 if (src->i_sb != inode->i_sb)
3935 goto out_fput;
3937 if (!same_inode) {
3938 btrfs_double_inode_lock(src, inode);
3939 } else {
3940 mutex_lock(&src->i_mutex);
3943 /* don't make the dst file partly checksummed */
3944 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3945 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
3946 ret = -EINVAL;
3947 goto out_unlock;
3950 /* determine range to clone */
3951 ret = -EINVAL;
3952 if (off + len > src->i_size || off + len < off)
3953 goto out_unlock;
3954 if (len == 0)
3955 olen = len = src->i_size - off;
3957 * If we extend to eof, continue to block boundary if and only if the
3958 * destination end offset matches the destination file's size, otherwise
3959 * we would be corrupting data by placing the eof block into the middle
3960 * of a file.
3962 if (off + len == src->i_size) {
3963 if (!IS_ALIGNED(len, bs) && destoff + len < inode->i_size)
3964 goto out_unlock;
3965 len = ALIGN(src->i_size, bs) - off;
3968 if (len == 0) {
3969 ret = 0;
3970 goto out_unlock;
3973 /* verify the end result is block aligned */
3974 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3975 !IS_ALIGNED(destoff, bs))
3976 goto out_unlock;
3978 /* verify if ranges are overlapped within the same file */
3979 if (same_inode) {
3980 if (destoff + len > off && destoff < off + len)
3981 goto out_unlock;
3984 if (destoff > inode->i_size) {
3985 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3986 if (ret)
3987 goto out_unlock;
3991 * Lock the target range too. Right after we replace the file extent
3992 * items in the fs tree (which now point to the cloned data), we might
3993 * have a worker replace them with extent items relative to a write
3994 * operation that was issued before this clone operation (i.e. confront
3995 * with inode.c:btrfs_finish_ordered_io).
3997 if (same_inode) {
3998 u64 lock_start = min_t(u64, off, destoff);
3999 u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
4001 ret = lock_extent_range(src, lock_start, lock_len, true);
4002 } else {
4003 ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
4004 true);
4006 ASSERT(ret == 0);
4007 if (WARN_ON(ret)) {
4008 /* ranges in the io trees already unlocked */
4009 goto out_unlock;
4012 ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
4014 if (same_inode) {
4015 u64 lock_start = min_t(u64, off, destoff);
4016 u64 lock_end = max_t(u64, off, destoff) + len - 1;
4018 unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
4019 } else {
4020 btrfs_double_extent_unlock(src, off, inode, destoff, len);
4023 * Truncate page cache pages so that future reads will see the cloned
4024 * data immediately and not the previous data.
4026 truncate_inode_pages_range(&inode->i_data, destoff,
4027 PAGE_CACHE_ALIGN(destoff + len) - 1);
4028 out_unlock:
4029 if (!same_inode)
4030 btrfs_double_inode_unlock(src, inode);
4031 else
4032 mutex_unlock(&src->i_mutex);
4033 out_fput:
4034 fdput(src_file);
4035 out_drop_write:
4036 mnt_drop_write_file(file);
4037 return ret;
4040 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
4042 struct btrfs_ioctl_clone_range_args args;
4044 if (copy_from_user(&args, argp, sizeof(args)))
4045 return -EFAULT;
4046 return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
4047 args.src_length, args.dest_offset);
4051 * there are many ways the trans_start and trans_end ioctls can lead
4052 * to deadlocks. They should only be used by applications that
4053 * basically own the machine, and have a very in depth understanding
4054 * of all the possible deadlocks and enospc problems.
4056 static long btrfs_ioctl_trans_start(struct file *file)
4058 struct inode *inode = file_inode(file);
4059 struct btrfs_root *root = BTRFS_I(inode)->root;
4060 struct btrfs_trans_handle *trans;
4061 int ret;
4063 ret = -EPERM;
4064 if (!capable(CAP_SYS_ADMIN))
4065 goto out;
4067 ret = -EINPROGRESS;
4068 if (file->private_data)
4069 goto out;
4071 ret = -EROFS;
4072 if (btrfs_root_readonly(root))
4073 goto out;
4075 ret = mnt_want_write_file(file);
4076 if (ret)
4077 goto out;
4079 atomic_inc(&root->fs_info->open_ioctl_trans);
4081 ret = -ENOMEM;
4082 trans = btrfs_start_ioctl_transaction(root);
4083 if (IS_ERR(trans))
4084 goto out_drop;
4086 file->private_data = trans;
4087 return 0;
4089 out_drop:
4090 atomic_dec(&root->fs_info->open_ioctl_trans);
4091 mnt_drop_write_file(file);
4092 out:
4093 return ret;
4096 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
4098 struct inode *inode = file_inode(file);
4099 struct btrfs_root *root = BTRFS_I(inode)->root;
4100 struct btrfs_root *new_root;
4101 struct btrfs_dir_item *di;
4102 struct btrfs_trans_handle *trans;
4103 struct btrfs_path *path;
4104 struct btrfs_key location;
4105 struct btrfs_disk_key disk_key;
4106 u64 objectid = 0;
4107 u64 dir_id;
4108 int ret;
4110 if (!capable(CAP_SYS_ADMIN))
4111 return -EPERM;
4113 ret = mnt_want_write_file(file);
4114 if (ret)
4115 return ret;
4117 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
4118 ret = -EFAULT;
4119 goto out;
4122 if (!objectid)
4123 objectid = BTRFS_FS_TREE_OBJECTID;
4125 location.objectid = objectid;
4126 location.type = BTRFS_ROOT_ITEM_KEY;
4127 location.offset = (u64)-1;
4129 new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
4130 if (IS_ERR(new_root)) {
4131 ret = PTR_ERR(new_root);
4132 goto out;
4134 if (!is_fstree(new_root->objectid)) {
4135 ret = -ENOENT;
4136 goto out;
4139 path = btrfs_alloc_path();
4140 if (!path) {
4141 ret = -ENOMEM;
4142 goto out;
4144 path->leave_spinning = 1;
4146 trans = btrfs_start_transaction(root, 1);
4147 if (IS_ERR(trans)) {
4148 btrfs_free_path(path);
4149 ret = PTR_ERR(trans);
4150 goto out;
4153 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
4154 di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
4155 dir_id, "default", 7, 1);
4156 if (IS_ERR_OR_NULL(di)) {
4157 btrfs_free_path(path);
4158 btrfs_end_transaction(trans, root);
4159 btrfs_err(new_root->fs_info, "Umm, you don't have the default dir"
4160 "item, this isn't going to work");
4161 ret = -ENOENT;
4162 goto out;
4165 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
4166 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
4167 btrfs_mark_buffer_dirty(path->nodes[0]);
4168 btrfs_free_path(path);
4170 btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
4171 btrfs_end_transaction(trans, root);
4172 out:
4173 mnt_drop_write_file(file);
4174 return ret;
4177 void btrfs_get_block_group_info(struct list_head *groups_list,
4178 struct btrfs_ioctl_space_info *space)
4180 struct btrfs_block_group_cache *block_group;
4182 space->total_bytes = 0;
4183 space->used_bytes = 0;
4184 space->flags = 0;
4185 list_for_each_entry(block_group, groups_list, list) {
4186 space->flags = block_group->flags;
4187 space->total_bytes += block_group->key.offset;
4188 space->used_bytes +=
4189 btrfs_block_group_used(&block_group->item);
4193 static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
4195 struct btrfs_ioctl_space_args space_args;
4196 struct btrfs_ioctl_space_info space;
4197 struct btrfs_ioctl_space_info *dest;
4198 struct btrfs_ioctl_space_info *dest_orig;
4199 struct btrfs_ioctl_space_info __user *user_dest;
4200 struct btrfs_space_info *info;
4201 u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
4202 BTRFS_BLOCK_GROUP_SYSTEM,
4203 BTRFS_BLOCK_GROUP_METADATA,
4204 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
4205 int num_types = 4;
4206 int alloc_size;
4207 int ret = 0;
4208 u64 slot_count = 0;
4209 int i, c;
4211 if (copy_from_user(&space_args,
4212 (struct btrfs_ioctl_space_args __user *)arg,
4213 sizeof(space_args)))
4214 return -EFAULT;
4216 for (i = 0; i < num_types; i++) {
4217 struct btrfs_space_info *tmp;
4219 info = NULL;
4220 rcu_read_lock();
4221 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4222 list) {
4223 if (tmp->flags == types[i]) {
4224 info = tmp;
4225 break;
4228 rcu_read_unlock();
4230 if (!info)
4231 continue;
4233 down_read(&info->groups_sem);
4234 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4235 if (!list_empty(&info->block_groups[c]))
4236 slot_count++;
4238 up_read(&info->groups_sem);
4242 * Global block reserve, exported as a space_info
4244 slot_count++;
4246 /* space_slots == 0 means they are asking for a count */
4247 if (space_args.space_slots == 0) {
4248 space_args.total_spaces = slot_count;
4249 goto out;
4252 slot_count = min_t(u64, space_args.space_slots, slot_count);
4254 alloc_size = sizeof(*dest) * slot_count;
4256 /* we generally have at most 6 or so space infos, one for each raid
4257 * level. So, a whole page should be more than enough for everyone
4259 if (alloc_size > PAGE_CACHE_SIZE)
4260 return -ENOMEM;
4262 space_args.total_spaces = 0;
4263 dest = kmalloc(alloc_size, GFP_NOFS);
4264 if (!dest)
4265 return -ENOMEM;
4266 dest_orig = dest;
4268 /* now we have a buffer to copy into */
4269 for (i = 0; i < num_types; i++) {
4270 struct btrfs_space_info *tmp;
4272 if (!slot_count)
4273 break;
4275 info = NULL;
4276 rcu_read_lock();
4277 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4278 list) {
4279 if (tmp->flags == types[i]) {
4280 info = tmp;
4281 break;
4284 rcu_read_unlock();
4286 if (!info)
4287 continue;
4288 down_read(&info->groups_sem);
4289 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4290 if (!list_empty(&info->block_groups[c])) {
4291 btrfs_get_block_group_info(
4292 &info->block_groups[c], &space);
4293 memcpy(dest, &space, sizeof(space));
4294 dest++;
4295 space_args.total_spaces++;
4296 slot_count--;
4298 if (!slot_count)
4299 break;
4301 up_read(&info->groups_sem);
4305 * Add global block reserve
4307 if (slot_count) {
4308 struct btrfs_block_rsv *block_rsv = &root->fs_info->global_block_rsv;
4310 spin_lock(&block_rsv->lock);
4311 space.total_bytes = block_rsv->size;
4312 space.used_bytes = block_rsv->size - block_rsv->reserved;
4313 spin_unlock(&block_rsv->lock);
4314 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4315 memcpy(dest, &space, sizeof(space));
4316 space_args.total_spaces++;
4319 user_dest = (struct btrfs_ioctl_space_info __user *)
4320 (arg + sizeof(struct btrfs_ioctl_space_args));
4322 if (copy_to_user(user_dest, dest_orig, alloc_size))
4323 ret = -EFAULT;
4325 kfree(dest_orig);
4326 out:
4327 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
4328 ret = -EFAULT;
4330 return ret;
4334 * there are many ways the trans_start and trans_end ioctls can lead
4335 * to deadlocks. They should only be used by applications that
4336 * basically own the machine, and have a very in depth understanding
4337 * of all the possible deadlocks and enospc problems.
4339 long btrfs_ioctl_trans_end(struct file *file)
4341 struct inode *inode = file_inode(file);
4342 struct btrfs_root *root = BTRFS_I(inode)->root;
4343 struct btrfs_trans_handle *trans;
4345 trans = file->private_data;
4346 if (!trans)
4347 return -EINVAL;
4348 file->private_data = NULL;
4350 btrfs_end_transaction(trans, root);
4352 atomic_dec(&root->fs_info->open_ioctl_trans);
4354 mnt_drop_write_file(file);
4355 return 0;
4358 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4359 void __user *argp)
4361 struct btrfs_trans_handle *trans;
4362 u64 transid;
4363 int ret;
4365 trans = btrfs_attach_transaction_barrier(root);
4366 if (IS_ERR(trans)) {
4367 if (PTR_ERR(trans) != -ENOENT)
4368 return PTR_ERR(trans);
4370 /* No running transaction, don't bother */
4371 transid = root->fs_info->last_trans_committed;
4372 goto out;
4374 transid = trans->transid;
4375 ret = btrfs_commit_transaction_async(trans, root, 0);
4376 if (ret) {
4377 btrfs_end_transaction(trans, root);
4378 return ret;
4380 out:
4381 if (argp)
4382 if (copy_to_user(argp, &transid, sizeof(transid)))
4383 return -EFAULT;
4384 return 0;
4387 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
4388 void __user *argp)
4390 u64 transid;
4392 if (argp) {
4393 if (copy_from_user(&transid, argp, sizeof(transid)))
4394 return -EFAULT;
4395 } else {
4396 transid = 0; /* current trans */
4398 return btrfs_wait_for_commit(root, transid);
4401 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4403 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4404 struct btrfs_ioctl_scrub_args *sa;
4405 int ret;
4407 if (!capable(CAP_SYS_ADMIN))
4408 return -EPERM;
4410 sa = memdup_user(arg, sizeof(*sa));
4411 if (IS_ERR(sa))
4412 return PTR_ERR(sa);
4414 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4415 ret = mnt_want_write_file(file);
4416 if (ret)
4417 goto out;
4420 ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
4421 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4424 if (copy_to_user(arg, sa, sizeof(*sa)))
4425 ret = -EFAULT;
4427 if (!(sa->flags & BTRFS_SCRUB_READONLY))
4428 mnt_drop_write_file(file);
4429 out:
4430 kfree(sa);
4431 return ret;
4434 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
4436 if (!capable(CAP_SYS_ADMIN))
4437 return -EPERM;
4439 return btrfs_scrub_cancel(root->fs_info);
4442 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
4443 void __user *arg)
4445 struct btrfs_ioctl_scrub_args *sa;
4446 int ret;
4448 if (!capable(CAP_SYS_ADMIN))
4449 return -EPERM;
4451 sa = memdup_user(arg, sizeof(*sa));
4452 if (IS_ERR(sa))
4453 return PTR_ERR(sa);
4455 ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
4457 if (copy_to_user(arg, sa, sizeof(*sa)))
4458 ret = -EFAULT;
4460 kfree(sa);
4461 return ret;
4464 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
4465 void __user *arg)
4467 struct btrfs_ioctl_get_dev_stats *sa;
4468 int ret;
4470 sa = memdup_user(arg, sizeof(*sa));
4471 if (IS_ERR(sa))
4472 return PTR_ERR(sa);
4474 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4475 kfree(sa);
4476 return -EPERM;
4479 ret = btrfs_get_dev_stats(root, sa);
4481 if (copy_to_user(arg, sa, sizeof(*sa)))
4482 ret = -EFAULT;
4484 kfree(sa);
4485 return ret;
4488 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
4490 struct btrfs_ioctl_dev_replace_args *p;
4491 int ret;
4493 if (!capable(CAP_SYS_ADMIN))
4494 return -EPERM;
4496 p = memdup_user(arg, sizeof(*p));
4497 if (IS_ERR(p))
4498 return PTR_ERR(p);
4500 switch (p->cmd) {
4501 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4502 if (root->fs_info->sb->s_flags & MS_RDONLY) {
4503 ret = -EROFS;
4504 goto out;
4506 if (atomic_xchg(
4507 &root->fs_info->mutually_exclusive_operation_running,
4508 1)) {
4509 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4510 } else {
4511 ret = btrfs_dev_replace_start(root, p);
4512 atomic_set(
4513 &root->fs_info->mutually_exclusive_operation_running,
4516 break;
4517 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4518 btrfs_dev_replace_status(root->fs_info, p);
4519 ret = 0;
4520 break;
4521 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4522 ret = btrfs_dev_replace_cancel(root->fs_info, p);
4523 break;
4524 default:
4525 ret = -EINVAL;
4526 break;
4529 if (copy_to_user(arg, p, sizeof(*p)))
4530 ret = -EFAULT;
4531 out:
4532 kfree(p);
4533 return ret;
4536 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4538 int ret = 0;
4539 int i;
4540 u64 rel_ptr;
4541 int size;
4542 struct btrfs_ioctl_ino_path_args *ipa = NULL;
4543 struct inode_fs_paths *ipath = NULL;
4544 struct btrfs_path *path;
4546 if (!capable(CAP_DAC_READ_SEARCH))
4547 return -EPERM;
4549 path = btrfs_alloc_path();
4550 if (!path) {
4551 ret = -ENOMEM;
4552 goto out;
4555 ipa = memdup_user(arg, sizeof(*ipa));
4556 if (IS_ERR(ipa)) {
4557 ret = PTR_ERR(ipa);
4558 ipa = NULL;
4559 goto out;
4562 size = min_t(u32, ipa->size, 4096);
4563 ipath = init_ipath(size, root, path);
4564 if (IS_ERR(ipath)) {
4565 ret = PTR_ERR(ipath);
4566 ipath = NULL;
4567 goto out;
4570 ret = paths_from_inode(ipa->inum, ipath);
4571 if (ret < 0)
4572 goto out;
4574 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4575 rel_ptr = ipath->fspath->val[i] -
4576 (u64)(unsigned long)ipath->fspath->val;
4577 ipath->fspath->val[i] = rel_ptr;
4580 ret = copy_to_user((void *)(unsigned long)ipa->fspath,
4581 (void *)(unsigned long)ipath->fspath, size);
4582 if (ret) {
4583 ret = -EFAULT;
4584 goto out;
4587 out:
4588 btrfs_free_path(path);
4589 free_ipath(ipath);
4590 kfree(ipa);
4592 return ret;
4595 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4597 struct btrfs_data_container *inodes = ctx;
4598 const size_t c = 3 * sizeof(u64);
4600 if (inodes->bytes_left >= c) {
4601 inodes->bytes_left -= c;
4602 inodes->val[inodes->elem_cnt] = inum;
4603 inodes->val[inodes->elem_cnt + 1] = offset;
4604 inodes->val[inodes->elem_cnt + 2] = root;
4605 inodes->elem_cnt += 3;
4606 } else {
4607 inodes->bytes_missing += c - inodes->bytes_left;
4608 inodes->bytes_left = 0;
4609 inodes->elem_missed += 3;
4612 return 0;
4615 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
4616 void __user *arg)
4618 int ret = 0;
4619 int size;
4620 struct btrfs_ioctl_logical_ino_args *loi;
4621 struct btrfs_data_container *inodes = NULL;
4622 struct btrfs_path *path = NULL;
4624 if (!capable(CAP_SYS_ADMIN))
4625 return -EPERM;
4627 loi = memdup_user(arg, sizeof(*loi));
4628 if (IS_ERR(loi)) {
4629 ret = PTR_ERR(loi);
4630 loi = NULL;
4631 goto out;
4634 path = btrfs_alloc_path();
4635 if (!path) {
4636 ret = -ENOMEM;
4637 goto out;
4640 size = min_t(u32, loi->size, 64 * 1024);
4641 inodes = init_data_container(size);
4642 if (IS_ERR(inodes)) {
4643 ret = PTR_ERR(inodes);
4644 inodes = NULL;
4645 goto out;
4648 ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
4649 build_ino_list, inodes);
4650 if (ret == -EINVAL)
4651 ret = -ENOENT;
4652 if (ret < 0)
4653 goto out;
4655 ret = copy_to_user((void *)(unsigned long)loi->inodes,
4656 (void *)(unsigned long)inodes, size);
4657 if (ret)
4658 ret = -EFAULT;
4660 out:
4661 btrfs_free_path(path);
4662 vfree(inodes);
4663 kfree(loi);
4665 return ret;
4668 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4669 struct btrfs_ioctl_balance_args *bargs)
4671 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4673 bargs->flags = bctl->flags;
4675 if (atomic_read(&fs_info->balance_running))
4676 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4677 if (atomic_read(&fs_info->balance_pause_req))
4678 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4679 if (atomic_read(&fs_info->balance_cancel_req))
4680 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4682 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4683 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4684 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4686 if (lock) {
4687 spin_lock(&fs_info->balance_lock);
4688 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4689 spin_unlock(&fs_info->balance_lock);
4690 } else {
4691 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4695 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4697 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4698 struct btrfs_fs_info *fs_info = root->fs_info;
4699 struct btrfs_ioctl_balance_args *bargs;
4700 struct btrfs_balance_control *bctl;
4701 bool need_unlock; /* for mut. excl. ops lock */
4702 int ret;
4704 if (!capable(CAP_SYS_ADMIN))
4705 return -EPERM;
4707 ret = mnt_want_write_file(file);
4708 if (ret)
4709 return ret;
4711 again:
4712 if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
4713 mutex_lock(&fs_info->volume_mutex);
4714 mutex_lock(&fs_info->balance_mutex);
4715 need_unlock = true;
4716 goto locked;
4720 * mut. excl. ops lock is locked. Three possibilites:
4721 * (1) some other op is running
4722 * (2) balance is running
4723 * (3) balance is paused -- special case (think resume)
4725 mutex_lock(&fs_info->balance_mutex);
4726 if (fs_info->balance_ctl) {
4727 /* this is either (2) or (3) */
4728 if (!atomic_read(&fs_info->balance_running)) {
4729 mutex_unlock(&fs_info->balance_mutex);
4730 if (!mutex_trylock(&fs_info->volume_mutex))
4731 goto again;
4732 mutex_lock(&fs_info->balance_mutex);
4734 if (fs_info->balance_ctl &&
4735 !atomic_read(&fs_info->balance_running)) {
4736 /* this is (3) */
4737 need_unlock = false;
4738 goto locked;
4741 mutex_unlock(&fs_info->balance_mutex);
4742 mutex_unlock(&fs_info->volume_mutex);
4743 goto again;
4744 } else {
4745 /* this is (2) */
4746 mutex_unlock(&fs_info->balance_mutex);
4747 ret = -EINPROGRESS;
4748 goto out;
4750 } else {
4751 /* this is (1) */
4752 mutex_unlock(&fs_info->balance_mutex);
4753 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4754 goto out;
4757 locked:
4758 BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
4760 if (arg) {
4761 bargs = memdup_user(arg, sizeof(*bargs));
4762 if (IS_ERR(bargs)) {
4763 ret = PTR_ERR(bargs);
4764 goto out_unlock;
4767 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4768 if (!fs_info->balance_ctl) {
4769 ret = -ENOTCONN;
4770 goto out_bargs;
4773 bctl = fs_info->balance_ctl;
4774 spin_lock(&fs_info->balance_lock);
4775 bctl->flags |= BTRFS_BALANCE_RESUME;
4776 spin_unlock(&fs_info->balance_lock);
4778 goto do_balance;
4780 } else {
4781 bargs = NULL;
4784 if (fs_info->balance_ctl) {
4785 ret = -EINPROGRESS;
4786 goto out_bargs;
4789 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4790 if (!bctl) {
4791 ret = -ENOMEM;
4792 goto out_bargs;
4795 bctl->fs_info = fs_info;
4796 if (arg) {
4797 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4798 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4799 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4801 bctl->flags = bargs->flags;
4802 } else {
4803 /* balance everything - no filters */
4804 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4807 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4808 ret = -EINVAL;
4809 goto out_bctl;
4812 do_balance:
4814 * Ownership of bctl and mutually_exclusive_operation_running
4815 * goes to to btrfs_balance. bctl is freed in __cancel_balance,
4816 * or, if restriper was paused all the way until unmount, in
4817 * free_fs_info. mutually_exclusive_operation_running is
4818 * cleared in __cancel_balance.
4820 need_unlock = false;
4822 ret = btrfs_balance(bctl, bargs);
4823 bctl = NULL;
4825 if (arg) {
4826 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4827 ret = -EFAULT;
4830 out_bctl:
4831 kfree(bctl);
4832 out_bargs:
4833 kfree(bargs);
4834 out_unlock:
4835 mutex_unlock(&fs_info->balance_mutex);
4836 mutex_unlock(&fs_info->volume_mutex);
4837 if (need_unlock)
4838 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4839 out:
4840 mnt_drop_write_file(file);
4841 return ret;
4844 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4846 if (!capable(CAP_SYS_ADMIN))
4847 return -EPERM;
4849 switch (cmd) {
4850 case BTRFS_BALANCE_CTL_PAUSE:
4851 return btrfs_pause_balance(root->fs_info);
4852 case BTRFS_BALANCE_CTL_CANCEL:
4853 return btrfs_cancel_balance(root->fs_info);
4856 return -EINVAL;
4859 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
4860 void __user *arg)
4862 struct btrfs_fs_info *fs_info = root->fs_info;
4863 struct btrfs_ioctl_balance_args *bargs;
4864 int ret = 0;
4866 if (!capable(CAP_SYS_ADMIN))
4867 return -EPERM;
4869 mutex_lock(&fs_info->balance_mutex);
4870 if (!fs_info->balance_ctl) {
4871 ret = -ENOTCONN;
4872 goto out;
4875 bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
4876 if (!bargs) {
4877 ret = -ENOMEM;
4878 goto out;
4881 update_ioctl_balance_args(fs_info, 1, bargs);
4883 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4884 ret = -EFAULT;
4886 kfree(bargs);
4887 out:
4888 mutex_unlock(&fs_info->balance_mutex);
4889 return ret;
4892 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4894 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4895 struct btrfs_ioctl_quota_ctl_args *sa;
4896 struct btrfs_trans_handle *trans = NULL;
4897 int ret;
4898 int err;
4900 if (!capable(CAP_SYS_ADMIN))
4901 return -EPERM;
4903 ret = mnt_want_write_file(file);
4904 if (ret)
4905 return ret;
4907 sa = memdup_user(arg, sizeof(*sa));
4908 if (IS_ERR(sa)) {
4909 ret = PTR_ERR(sa);
4910 goto drop_write;
4913 down_write(&root->fs_info->subvol_sem);
4914 trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
4915 if (IS_ERR(trans)) {
4916 ret = PTR_ERR(trans);
4917 goto out;
4920 switch (sa->cmd) {
4921 case BTRFS_QUOTA_CTL_ENABLE:
4922 ret = btrfs_quota_enable(trans, root->fs_info);
4923 break;
4924 case BTRFS_QUOTA_CTL_DISABLE:
4925 ret = btrfs_quota_disable(trans, root->fs_info);
4926 break;
4927 default:
4928 ret = -EINVAL;
4929 break;
4932 err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
4933 if (err && !ret)
4934 ret = err;
4935 out:
4936 kfree(sa);
4937 up_write(&root->fs_info->subvol_sem);
4938 drop_write:
4939 mnt_drop_write_file(file);
4940 return ret;
4943 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4945 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4946 struct btrfs_ioctl_qgroup_assign_args *sa;
4947 struct btrfs_trans_handle *trans;
4948 int ret;
4949 int err;
4951 if (!capable(CAP_SYS_ADMIN))
4952 return -EPERM;
4954 ret = mnt_want_write_file(file);
4955 if (ret)
4956 return ret;
4958 sa = memdup_user(arg, sizeof(*sa));
4959 if (IS_ERR(sa)) {
4960 ret = PTR_ERR(sa);
4961 goto drop_write;
4964 trans = btrfs_join_transaction(root);
4965 if (IS_ERR(trans)) {
4966 ret = PTR_ERR(trans);
4967 goto out;
4970 /* FIXME: check if the IDs really exist */
4971 if (sa->assign) {
4972 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
4973 sa->src, sa->dst);
4974 } else {
4975 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
4976 sa->src, sa->dst);
4979 /* update qgroup status and info */
4980 err = btrfs_run_qgroups(trans, root->fs_info);
4981 if (err < 0)
4982 btrfs_std_error(root->fs_info, ret,
4983 "failed to update qgroup status and info\n");
4984 err = btrfs_end_transaction(trans, root);
4985 if (err && !ret)
4986 ret = err;
4988 out:
4989 kfree(sa);
4990 drop_write:
4991 mnt_drop_write_file(file);
4992 return ret;
4995 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4997 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4998 struct btrfs_ioctl_qgroup_create_args *sa;
4999 struct btrfs_trans_handle *trans;
5000 int ret;
5001 int err;
5003 if (!capable(CAP_SYS_ADMIN))
5004 return -EPERM;
5006 ret = mnt_want_write_file(file);
5007 if (ret)
5008 return ret;
5010 sa = memdup_user(arg, sizeof(*sa));
5011 if (IS_ERR(sa)) {
5012 ret = PTR_ERR(sa);
5013 goto drop_write;
5016 if (!sa->qgroupid) {
5017 ret = -EINVAL;
5018 goto out;
5021 trans = btrfs_join_transaction(root);
5022 if (IS_ERR(trans)) {
5023 ret = PTR_ERR(trans);
5024 goto out;
5027 /* FIXME: check if the IDs really exist */
5028 if (sa->create) {
5029 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid);
5030 } else {
5031 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
5034 err = btrfs_end_transaction(trans, root);
5035 if (err && !ret)
5036 ret = err;
5038 out:
5039 kfree(sa);
5040 drop_write:
5041 mnt_drop_write_file(file);
5042 return ret;
5045 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
5047 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5048 struct btrfs_ioctl_qgroup_limit_args *sa;
5049 struct btrfs_trans_handle *trans;
5050 int ret;
5051 int err;
5052 u64 qgroupid;
5054 if (!capable(CAP_SYS_ADMIN))
5055 return -EPERM;
5057 ret = mnt_want_write_file(file);
5058 if (ret)
5059 return ret;
5061 sa = memdup_user(arg, sizeof(*sa));
5062 if (IS_ERR(sa)) {
5063 ret = PTR_ERR(sa);
5064 goto drop_write;
5067 trans = btrfs_join_transaction(root);
5068 if (IS_ERR(trans)) {
5069 ret = PTR_ERR(trans);
5070 goto out;
5073 qgroupid = sa->qgroupid;
5074 if (!qgroupid) {
5075 /* take the current subvol as qgroup */
5076 qgroupid = root->root_key.objectid;
5079 /* FIXME: check if the IDs really exist */
5080 ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
5082 err = btrfs_end_transaction(trans, root);
5083 if (err && !ret)
5084 ret = err;
5086 out:
5087 kfree(sa);
5088 drop_write:
5089 mnt_drop_write_file(file);
5090 return ret;
5093 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
5095 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5096 struct btrfs_ioctl_quota_rescan_args *qsa;
5097 int ret;
5099 if (!capable(CAP_SYS_ADMIN))
5100 return -EPERM;
5102 ret = mnt_want_write_file(file);
5103 if (ret)
5104 return ret;
5106 qsa = memdup_user(arg, sizeof(*qsa));
5107 if (IS_ERR(qsa)) {
5108 ret = PTR_ERR(qsa);
5109 goto drop_write;
5112 if (qsa->flags) {
5113 ret = -EINVAL;
5114 goto out;
5117 ret = btrfs_qgroup_rescan(root->fs_info);
5119 out:
5120 kfree(qsa);
5121 drop_write:
5122 mnt_drop_write_file(file);
5123 return ret;
5126 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
5128 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5129 struct btrfs_ioctl_quota_rescan_args *qsa;
5130 int ret = 0;
5132 if (!capable(CAP_SYS_ADMIN))
5133 return -EPERM;
5135 qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
5136 if (!qsa)
5137 return -ENOMEM;
5139 if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
5140 qsa->flags = 1;
5141 qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
5144 if (copy_to_user(arg, qsa, sizeof(*qsa)))
5145 ret = -EFAULT;
5147 kfree(qsa);
5148 return ret;
5151 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
5153 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5155 if (!capable(CAP_SYS_ADMIN))
5156 return -EPERM;
5158 return btrfs_qgroup_wait_for_completion(root->fs_info, true);
5161 static long _btrfs_ioctl_set_received_subvol(struct file *file,
5162 struct btrfs_ioctl_received_subvol_args *sa)
5164 struct inode *inode = file_inode(file);
5165 struct btrfs_root *root = BTRFS_I(inode)->root;
5166 struct btrfs_root_item *root_item = &root->root_item;
5167 struct btrfs_trans_handle *trans;
5168 struct timespec ct = CURRENT_TIME;
5169 int ret = 0;
5170 int received_uuid_changed;
5172 if (!inode_owner_or_capable(inode))
5173 return -EPERM;
5175 ret = mnt_want_write_file(file);
5176 if (ret < 0)
5177 return ret;
5179 down_write(&root->fs_info->subvol_sem);
5181 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
5182 ret = -EINVAL;
5183 goto out;
5186 if (btrfs_root_readonly(root)) {
5187 ret = -EROFS;
5188 goto out;
5192 * 1 - root item
5193 * 2 - uuid items (received uuid + subvol uuid)
5195 trans = btrfs_start_transaction(root, 3);
5196 if (IS_ERR(trans)) {
5197 ret = PTR_ERR(trans);
5198 trans = NULL;
5199 goto out;
5202 sa->rtransid = trans->transid;
5203 sa->rtime.sec = ct.tv_sec;
5204 sa->rtime.nsec = ct.tv_nsec;
5206 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5207 BTRFS_UUID_SIZE);
5208 if (received_uuid_changed &&
5209 !btrfs_is_empty_uuid(root_item->received_uuid))
5210 btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
5211 root_item->received_uuid,
5212 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5213 root->root_key.objectid);
5214 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5215 btrfs_set_root_stransid(root_item, sa->stransid);
5216 btrfs_set_root_rtransid(root_item, sa->rtransid);
5217 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5218 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5219 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5220 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
5222 ret = btrfs_update_root(trans, root->fs_info->tree_root,
5223 &root->root_key, &root->root_item);
5224 if (ret < 0) {
5225 btrfs_end_transaction(trans, root);
5226 goto out;
5228 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5229 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
5230 sa->uuid,
5231 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5232 root->root_key.objectid);
5233 if (ret < 0 && ret != -EEXIST) {
5234 btrfs_abort_transaction(trans, root, ret);
5235 goto out;
5238 ret = btrfs_commit_transaction(trans, root);
5239 if (ret < 0) {
5240 btrfs_abort_transaction(trans, root, ret);
5241 goto out;
5244 out:
5245 up_write(&root->fs_info->subvol_sem);
5246 mnt_drop_write_file(file);
5247 return ret;
5250 #ifdef CONFIG_64BIT
5251 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5252 void __user *arg)
5254 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5255 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5256 int ret = 0;
5258 args32 = memdup_user(arg, sizeof(*args32));
5259 if (IS_ERR(args32)) {
5260 ret = PTR_ERR(args32);
5261 args32 = NULL;
5262 goto out;
5265 args64 = kmalloc(sizeof(*args64), GFP_NOFS);
5266 if (!args64) {
5267 ret = -ENOMEM;
5268 goto out;
5271 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5272 args64->stransid = args32->stransid;
5273 args64->rtransid = args32->rtransid;
5274 args64->stime.sec = args32->stime.sec;
5275 args64->stime.nsec = args32->stime.nsec;
5276 args64->rtime.sec = args32->rtime.sec;
5277 args64->rtime.nsec = args32->rtime.nsec;
5278 args64->flags = args32->flags;
5280 ret = _btrfs_ioctl_set_received_subvol(file, args64);
5281 if (ret)
5282 goto out;
5284 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5285 args32->stransid = args64->stransid;
5286 args32->rtransid = args64->rtransid;
5287 args32->stime.sec = args64->stime.sec;
5288 args32->stime.nsec = args64->stime.nsec;
5289 args32->rtime.sec = args64->rtime.sec;
5290 args32->rtime.nsec = args64->rtime.nsec;
5291 args32->flags = args64->flags;
5293 ret = copy_to_user(arg, args32, sizeof(*args32));
5294 if (ret)
5295 ret = -EFAULT;
5297 out:
5298 kfree(args32);
5299 kfree(args64);
5300 return ret;
5302 #endif
5304 static long btrfs_ioctl_set_received_subvol(struct file *file,
5305 void __user *arg)
5307 struct btrfs_ioctl_received_subvol_args *sa = NULL;
5308 int ret = 0;
5310 sa = memdup_user(arg, sizeof(*sa));
5311 if (IS_ERR(sa)) {
5312 ret = PTR_ERR(sa);
5313 sa = NULL;
5314 goto out;
5317 ret = _btrfs_ioctl_set_received_subvol(file, sa);
5319 if (ret)
5320 goto out;
5322 ret = copy_to_user(arg, sa, sizeof(*sa));
5323 if (ret)
5324 ret = -EFAULT;
5326 out:
5327 kfree(sa);
5328 return ret;
5331 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5333 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5334 size_t len;
5335 int ret;
5336 char label[BTRFS_LABEL_SIZE];
5338 spin_lock(&root->fs_info->super_lock);
5339 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5340 spin_unlock(&root->fs_info->super_lock);
5342 len = strnlen(label, BTRFS_LABEL_SIZE);
5344 if (len == BTRFS_LABEL_SIZE) {
5345 btrfs_warn(root->fs_info,
5346 "label is too long, return the first %zu bytes", --len);
5349 ret = copy_to_user(arg, label, len);
5351 return ret ? -EFAULT : 0;
5354 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5356 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5357 struct btrfs_super_block *super_block = root->fs_info->super_copy;
5358 struct btrfs_trans_handle *trans;
5359 char label[BTRFS_LABEL_SIZE];
5360 int ret;
5362 if (!capable(CAP_SYS_ADMIN))
5363 return -EPERM;
5365 if (copy_from_user(label, arg, sizeof(label)))
5366 return -EFAULT;
5368 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5369 btrfs_err(root->fs_info, "unable to set label with more than %d bytes",
5370 BTRFS_LABEL_SIZE - 1);
5371 return -EINVAL;
5374 ret = mnt_want_write_file(file);
5375 if (ret)
5376 return ret;
5378 trans = btrfs_start_transaction(root, 0);
5379 if (IS_ERR(trans)) {
5380 ret = PTR_ERR(trans);
5381 goto out_unlock;
5384 spin_lock(&root->fs_info->super_lock);
5385 strcpy(super_block->label, label);
5386 spin_unlock(&root->fs_info->super_lock);
5387 ret = btrfs_commit_transaction(trans, root);
5389 out_unlock:
5390 mnt_drop_write_file(file);
5391 return ret;
5394 #define INIT_FEATURE_FLAGS(suffix) \
5395 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5396 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5397 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5399 static int btrfs_ioctl_get_supported_features(struct file *file,
5400 void __user *arg)
5402 static struct btrfs_ioctl_feature_flags features[3] = {
5403 INIT_FEATURE_FLAGS(SUPP),
5404 INIT_FEATURE_FLAGS(SAFE_SET),
5405 INIT_FEATURE_FLAGS(SAFE_CLEAR)
5408 if (copy_to_user(arg, &features, sizeof(features)))
5409 return -EFAULT;
5411 return 0;
5414 static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
5416 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5417 struct btrfs_super_block *super_block = root->fs_info->super_copy;
5418 struct btrfs_ioctl_feature_flags features;
5420 features.compat_flags = btrfs_super_compat_flags(super_block);
5421 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5422 features.incompat_flags = btrfs_super_incompat_flags(super_block);
5424 if (copy_to_user(arg, &features, sizeof(features)))
5425 return -EFAULT;
5427 return 0;
5430 static int check_feature_bits(struct btrfs_root *root,
5431 enum btrfs_feature_set set,
5432 u64 change_mask, u64 flags, u64 supported_flags,
5433 u64 safe_set, u64 safe_clear)
5435 const char *type = btrfs_feature_set_names[set];
5436 char *names;
5437 u64 disallowed, unsupported;
5438 u64 set_mask = flags & change_mask;
5439 u64 clear_mask = ~flags & change_mask;
5441 unsupported = set_mask & ~supported_flags;
5442 if (unsupported) {
5443 names = btrfs_printable_features(set, unsupported);
5444 if (names) {
5445 btrfs_warn(root->fs_info,
5446 "this kernel does not support the %s feature bit%s",
5447 names, strchr(names, ',') ? "s" : "");
5448 kfree(names);
5449 } else
5450 btrfs_warn(root->fs_info,
5451 "this kernel does not support %s bits 0x%llx",
5452 type, unsupported);
5453 return -EOPNOTSUPP;
5456 disallowed = set_mask & ~safe_set;
5457 if (disallowed) {
5458 names = btrfs_printable_features(set, disallowed);
5459 if (names) {
5460 btrfs_warn(root->fs_info,
5461 "can't set the %s feature bit%s while mounted",
5462 names, strchr(names, ',') ? "s" : "");
5463 kfree(names);
5464 } else
5465 btrfs_warn(root->fs_info,
5466 "can't set %s bits 0x%llx while mounted",
5467 type, disallowed);
5468 return -EPERM;
5471 disallowed = clear_mask & ~safe_clear;
5472 if (disallowed) {
5473 names = btrfs_printable_features(set, disallowed);
5474 if (names) {
5475 btrfs_warn(root->fs_info,
5476 "can't clear the %s feature bit%s while mounted",
5477 names, strchr(names, ',') ? "s" : "");
5478 kfree(names);
5479 } else
5480 btrfs_warn(root->fs_info,
5481 "can't clear %s bits 0x%llx while mounted",
5482 type, disallowed);
5483 return -EPERM;
5486 return 0;
5489 #define check_feature(root, change_mask, flags, mask_base) \
5490 check_feature_bits(root, FEAT_##mask_base, change_mask, flags, \
5491 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
5492 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
5493 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5495 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5497 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5498 struct btrfs_super_block *super_block = root->fs_info->super_copy;
5499 struct btrfs_ioctl_feature_flags flags[2];
5500 struct btrfs_trans_handle *trans;
5501 u64 newflags;
5502 int ret;
5504 if (!capable(CAP_SYS_ADMIN))
5505 return -EPERM;
5507 if (copy_from_user(flags, arg, sizeof(flags)))
5508 return -EFAULT;
5510 /* Nothing to do */
5511 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5512 !flags[0].incompat_flags)
5513 return 0;
5515 ret = check_feature(root, flags[0].compat_flags,
5516 flags[1].compat_flags, COMPAT);
5517 if (ret)
5518 return ret;
5520 ret = check_feature(root, flags[0].compat_ro_flags,
5521 flags[1].compat_ro_flags, COMPAT_RO);
5522 if (ret)
5523 return ret;
5525 ret = check_feature(root, flags[0].incompat_flags,
5526 flags[1].incompat_flags, INCOMPAT);
5527 if (ret)
5528 return ret;
5530 trans = btrfs_start_transaction(root, 0);
5531 if (IS_ERR(trans))
5532 return PTR_ERR(trans);
5534 spin_lock(&root->fs_info->super_lock);
5535 newflags = btrfs_super_compat_flags(super_block);
5536 newflags |= flags[0].compat_flags & flags[1].compat_flags;
5537 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5538 btrfs_set_super_compat_flags(super_block, newflags);
5540 newflags = btrfs_super_compat_ro_flags(super_block);
5541 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5542 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5543 btrfs_set_super_compat_ro_flags(super_block, newflags);
5545 newflags = btrfs_super_incompat_flags(super_block);
5546 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5547 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5548 btrfs_set_super_incompat_flags(super_block, newflags);
5549 spin_unlock(&root->fs_info->super_lock);
5551 return btrfs_commit_transaction(trans, root);
5554 long btrfs_ioctl(struct file *file, unsigned int
5555 cmd, unsigned long arg)
5557 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5558 void __user *argp = (void __user *)arg;
5560 switch (cmd) {
5561 case FS_IOC_GETFLAGS:
5562 return btrfs_ioctl_getflags(file, argp);
5563 case FS_IOC_SETFLAGS:
5564 return btrfs_ioctl_setflags(file, argp);
5565 case FS_IOC_GETVERSION:
5566 return btrfs_ioctl_getversion(file, argp);
5567 case FITRIM:
5568 return btrfs_ioctl_fitrim(file, argp);
5569 case BTRFS_IOC_SNAP_CREATE:
5570 return btrfs_ioctl_snap_create(file, argp, 0);
5571 case BTRFS_IOC_SNAP_CREATE_V2:
5572 return btrfs_ioctl_snap_create_v2(file, argp, 0);
5573 case BTRFS_IOC_SUBVOL_CREATE:
5574 return btrfs_ioctl_snap_create(file, argp, 1);
5575 case BTRFS_IOC_SUBVOL_CREATE_V2:
5576 return btrfs_ioctl_snap_create_v2(file, argp, 1);
5577 case BTRFS_IOC_SNAP_DESTROY:
5578 return btrfs_ioctl_snap_destroy(file, argp);
5579 case BTRFS_IOC_SUBVOL_GETFLAGS:
5580 return btrfs_ioctl_subvol_getflags(file, argp);
5581 case BTRFS_IOC_SUBVOL_SETFLAGS:
5582 return btrfs_ioctl_subvol_setflags(file, argp);
5583 case BTRFS_IOC_DEFAULT_SUBVOL:
5584 return btrfs_ioctl_default_subvol(file, argp);
5585 case BTRFS_IOC_DEFRAG:
5586 return btrfs_ioctl_defrag(file, NULL);
5587 case BTRFS_IOC_DEFRAG_RANGE:
5588 return btrfs_ioctl_defrag(file, argp);
5589 case BTRFS_IOC_RESIZE:
5590 return btrfs_ioctl_resize(file, argp);
5591 case BTRFS_IOC_ADD_DEV:
5592 return btrfs_ioctl_add_dev(root, argp);
5593 case BTRFS_IOC_RM_DEV:
5594 return btrfs_ioctl_rm_dev(file, argp);
5595 case BTRFS_IOC_FS_INFO:
5596 return btrfs_ioctl_fs_info(root, argp);
5597 case BTRFS_IOC_DEV_INFO:
5598 return btrfs_ioctl_dev_info(root, argp);
5599 case BTRFS_IOC_BALANCE:
5600 return btrfs_ioctl_balance(file, NULL);
5601 case BTRFS_IOC_CLONE:
5602 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
5603 case BTRFS_IOC_CLONE_RANGE:
5604 return btrfs_ioctl_clone_range(file, argp);
5605 case BTRFS_IOC_TRANS_START:
5606 return btrfs_ioctl_trans_start(file);
5607 case BTRFS_IOC_TRANS_END:
5608 return btrfs_ioctl_trans_end(file);
5609 case BTRFS_IOC_TREE_SEARCH:
5610 return btrfs_ioctl_tree_search(file, argp);
5611 case BTRFS_IOC_TREE_SEARCH_V2:
5612 return btrfs_ioctl_tree_search_v2(file, argp);
5613 case BTRFS_IOC_INO_LOOKUP:
5614 return btrfs_ioctl_ino_lookup(file, argp);
5615 case BTRFS_IOC_INO_PATHS:
5616 return btrfs_ioctl_ino_to_path(root, argp);
5617 case BTRFS_IOC_LOGICAL_INO:
5618 return btrfs_ioctl_logical_to_ino(root, argp);
5619 case BTRFS_IOC_SPACE_INFO:
5620 return btrfs_ioctl_space_info(root, argp);
5621 case BTRFS_IOC_SYNC: {
5622 int ret;
5624 ret = btrfs_start_delalloc_roots(root->fs_info, 0, -1);
5625 if (ret)
5626 return ret;
5627 ret = btrfs_sync_fs(file_inode(file)->i_sb, 1);
5629 * The transaction thread may want to do more work,
5630 * namely it pokes the cleaner ktread that will start
5631 * processing uncleaned subvols.
5633 wake_up_process(root->fs_info->transaction_kthread);
5634 return ret;
5636 case BTRFS_IOC_START_SYNC:
5637 return btrfs_ioctl_start_sync(root, argp);
5638 case BTRFS_IOC_WAIT_SYNC:
5639 return btrfs_ioctl_wait_sync(root, argp);
5640 case BTRFS_IOC_SCRUB:
5641 return btrfs_ioctl_scrub(file, argp);
5642 case BTRFS_IOC_SCRUB_CANCEL:
5643 return btrfs_ioctl_scrub_cancel(root, argp);
5644 case BTRFS_IOC_SCRUB_PROGRESS:
5645 return btrfs_ioctl_scrub_progress(root, argp);
5646 case BTRFS_IOC_BALANCE_V2:
5647 return btrfs_ioctl_balance(file, argp);
5648 case BTRFS_IOC_BALANCE_CTL:
5649 return btrfs_ioctl_balance_ctl(root, arg);
5650 case BTRFS_IOC_BALANCE_PROGRESS:
5651 return btrfs_ioctl_balance_progress(root, argp);
5652 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5653 return btrfs_ioctl_set_received_subvol(file, argp);
5654 #ifdef CONFIG_64BIT
5655 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5656 return btrfs_ioctl_set_received_subvol_32(file, argp);
5657 #endif
5658 case BTRFS_IOC_SEND:
5659 return btrfs_ioctl_send(file, argp);
5660 case BTRFS_IOC_GET_DEV_STATS:
5661 return btrfs_ioctl_get_dev_stats(root, argp);
5662 case BTRFS_IOC_QUOTA_CTL:
5663 return btrfs_ioctl_quota_ctl(file, argp);
5664 case BTRFS_IOC_QGROUP_ASSIGN:
5665 return btrfs_ioctl_qgroup_assign(file, argp);
5666 case BTRFS_IOC_QGROUP_CREATE:
5667 return btrfs_ioctl_qgroup_create(file, argp);
5668 case BTRFS_IOC_QGROUP_LIMIT:
5669 return btrfs_ioctl_qgroup_limit(file, argp);
5670 case BTRFS_IOC_QUOTA_RESCAN:
5671 return btrfs_ioctl_quota_rescan(file, argp);
5672 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5673 return btrfs_ioctl_quota_rescan_status(file, argp);
5674 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5675 return btrfs_ioctl_quota_rescan_wait(file, argp);
5676 case BTRFS_IOC_DEV_REPLACE:
5677 return btrfs_ioctl_dev_replace(root, argp);
5678 case BTRFS_IOC_GET_FSLABEL:
5679 return btrfs_ioctl_get_fslabel(file, argp);
5680 case BTRFS_IOC_SET_FSLABEL:
5681 return btrfs_ioctl_set_fslabel(file, argp);
5682 case BTRFS_IOC_FILE_EXTENT_SAME:
5683 return btrfs_ioctl_file_extent_same(file, argp);
5684 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5685 return btrfs_ioctl_get_supported_features(file, argp);
5686 case BTRFS_IOC_GET_FEATURES:
5687 return btrfs_ioctl_get_features(file, argp);
5688 case BTRFS_IOC_SET_FEATURES:
5689 return btrfs_ioctl_set_features(file, argp);
5692 return -ENOTTY;