HID: hiddev: Fix slab-out-of-bounds write in hiddev_ioctl_usage()
[linux/fpc-iii.git] / fs / btrfs / ioctl.c
blob245a50f490f63b3a4a4a170dc76a7c5fa9d060b7
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"
62 #include "tree-log.h"
64 #ifdef CONFIG_64BIT
65 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
66 * structures are incorrect, as the timespec structure from userspace
67 * is 4 bytes too small. We define these alternatives here to teach
68 * the kernel about the 32-bit struct packing.
70 struct btrfs_ioctl_timespec_32 {
71 __u64 sec;
72 __u32 nsec;
73 } __attribute__ ((__packed__));
75 struct btrfs_ioctl_received_subvol_args_32 {
76 char uuid[BTRFS_UUID_SIZE]; /* in */
77 __u64 stransid; /* in */
78 __u64 rtransid; /* out */
79 struct btrfs_ioctl_timespec_32 stime; /* in */
80 struct btrfs_ioctl_timespec_32 rtime; /* out */
81 __u64 flags; /* in */
82 __u64 reserved[16]; /* in */
83 } __attribute__ ((__packed__));
85 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
86 struct btrfs_ioctl_received_subvol_args_32)
87 #endif
90 static int btrfs_clone(struct inode *src, struct inode *inode,
91 u64 off, u64 olen, u64 olen_aligned, u64 destoff,
92 int no_time_update);
94 /* Mask out flags that are inappropriate for the given type of inode. */
95 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
97 if (S_ISDIR(mode))
98 return flags;
99 else if (S_ISREG(mode))
100 return flags & ~FS_DIRSYNC_FL;
101 else
102 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
106 * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
108 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
110 unsigned int iflags = 0;
112 if (flags & BTRFS_INODE_SYNC)
113 iflags |= FS_SYNC_FL;
114 if (flags & BTRFS_INODE_IMMUTABLE)
115 iflags |= FS_IMMUTABLE_FL;
116 if (flags & BTRFS_INODE_APPEND)
117 iflags |= FS_APPEND_FL;
118 if (flags & BTRFS_INODE_NODUMP)
119 iflags |= FS_NODUMP_FL;
120 if (flags & BTRFS_INODE_NOATIME)
121 iflags |= FS_NOATIME_FL;
122 if (flags & BTRFS_INODE_DIRSYNC)
123 iflags |= FS_DIRSYNC_FL;
124 if (flags & BTRFS_INODE_NODATACOW)
125 iflags |= FS_NOCOW_FL;
127 if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
128 iflags |= FS_COMPR_FL;
129 else if (flags & BTRFS_INODE_NOCOMPRESS)
130 iflags |= FS_NOCOMP_FL;
132 return iflags;
136 * Update inode->i_flags based on the btrfs internal flags.
138 void btrfs_update_iflags(struct inode *inode)
140 struct btrfs_inode *ip = BTRFS_I(inode);
141 unsigned int new_fl = 0;
143 if (ip->flags & BTRFS_INODE_SYNC)
144 new_fl |= S_SYNC;
145 if (ip->flags & BTRFS_INODE_IMMUTABLE)
146 new_fl |= S_IMMUTABLE;
147 if (ip->flags & BTRFS_INODE_APPEND)
148 new_fl |= S_APPEND;
149 if (ip->flags & BTRFS_INODE_NOATIME)
150 new_fl |= S_NOATIME;
151 if (ip->flags & BTRFS_INODE_DIRSYNC)
152 new_fl |= S_DIRSYNC;
154 set_mask_bits(&inode->i_flags,
155 S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
156 new_fl);
160 * Inherit flags from the parent inode.
162 * Currently only the compression flags and the cow flags are inherited.
164 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
166 unsigned int flags;
168 if (!dir)
169 return;
171 flags = BTRFS_I(dir)->flags;
173 if (flags & BTRFS_INODE_NOCOMPRESS) {
174 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
175 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
176 } else if (flags & BTRFS_INODE_COMPRESS) {
177 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
178 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
181 if (flags & BTRFS_INODE_NODATACOW) {
182 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
183 if (S_ISREG(inode->i_mode))
184 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
187 btrfs_update_iflags(inode);
190 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
192 struct btrfs_inode *ip = BTRFS_I(file_inode(file));
193 unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
195 if (copy_to_user(arg, &flags, sizeof(flags)))
196 return -EFAULT;
197 return 0;
200 static int check_flags(unsigned int flags)
202 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
203 FS_NOATIME_FL | FS_NODUMP_FL | \
204 FS_SYNC_FL | FS_DIRSYNC_FL | \
205 FS_NOCOMP_FL | FS_COMPR_FL |
206 FS_NOCOW_FL))
207 return -EOPNOTSUPP;
209 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
210 return -EINVAL;
212 return 0;
215 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
217 struct inode *inode = file_inode(file);
218 struct btrfs_inode *ip = BTRFS_I(inode);
219 struct btrfs_root *root = ip->root;
220 struct btrfs_trans_handle *trans;
221 unsigned int flags, oldflags;
222 int ret;
223 u64 ip_oldflags;
224 unsigned int i_oldflags;
225 umode_t mode;
227 if (!inode_owner_or_capable(inode))
228 return -EPERM;
230 if (btrfs_root_readonly(root))
231 return -EROFS;
233 if (copy_from_user(&flags, arg, sizeof(flags)))
234 return -EFAULT;
236 ret = check_flags(flags);
237 if (ret)
238 return ret;
240 ret = mnt_want_write_file(file);
241 if (ret)
242 return ret;
244 mutex_lock(&inode->i_mutex);
246 ip_oldflags = ip->flags;
247 i_oldflags = inode->i_flags;
248 mode = inode->i_mode;
250 flags = btrfs_mask_flags(inode->i_mode, flags);
251 oldflags = btrfs_flags_to_ioctl(ip->flags);
252 if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
253 if (!capable(CAP_LINUX_IMMUTABLE)) {
254 ret = -EPERM;
255 goto out_unlock;
259 if (flags & FS_SYNC_FL)
260 ip->flags |= BTRFS_INODE_SYNC;
261 else
262 ip->flags &= ~BTRFS_INODE_SYNC;
263 if (flags & FS_IMMUTABLE_FL)
264 ip->flags |= BTRFS_INODE_IMMUTABLE;
265 else
266 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
267 if (flags & FS_APPEND_FL)
268 ip->flags |= BTRFS_INODE_APPEND;
269 else
270 ip->flags &= ~BTRFS_INODE_APPEND;
271 if (flags & FS_NODUMP_FL)
272 ip->flags |= BTRFS_INODE_NODUMP;
273 else
274 ip->flags &= ~BTRFS_INODE_NODUMP;
275 if (flags & FS_NOATIME_FL)
276 ip->flags |= BTRFS_INODE_NOATIME;
277 else
278 ip->flags &= ~BTRFS_INODE_NOATIME;
279 if (flags & FS_DIRSYNC_FL)
280 ip->flags |= BTRFS_INODE_DIRSYNC;
281 else
282 ip->flags &= ~BTRFS_INODE_DIRSYNC;
283 if (flags & FS_NOCOW_FL) {
284 if (S_ISREG(mode)) {
286 * It's safe to turn csums off here, no extents exist.
287 * Otherwise we want the flag to reflect the real COW
288 * status of the file and will not set it.
290 if (inode->i_size == 0)
291 ip->flags |= BTRFS_INODE_NODATACOW
292 | BTRFS_INODE_NODATASUM;
293 } else {
294 ip->flags |= BTRFS_INODE_NODATACOW;
296 } else {
298 * Revert back under same assuptions as above
300 if (S_ISREG(mode)) {
301 if (inode->i_size == 0)
302 ip->flags &= ~(BTRFS_INODE_NODATACOW
303 | BTRFS_INODE_NODATASUM);
304 } else {
305 ip->flags &= ~BTRFS_INODE_NODATACOW;
310 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
311 * flag may be changed automatically if compression code won't make
312 * things smaller.
314 if (flags & FS_NOCOMP_FL) {
315 ip->flags &= ~BTRFS_INODE_COMPRESS;
316 ip->flags |= BTRFS_INODE_NOCOMPRESS;
318 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
319 if (ret && ret != -ENODATA)
320 goto out_drop;
321 } else if (flags & FS_COMPR_FL) {
322 const char *comp;
324 ip->flags |= BTRFS_INODE_COMPRESS;
325 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
327 if (root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
328 comp = "lzo";
329 else
330 comp = "zlib";
331 ret = btrfs_set_prop(inode, "btrfs.compression",
332 comp, strlen(comp), 0);
333 if (ret)
334 goto out_drop;
336 } else {
337 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
338 if (ret && ret != -ENODATA)
339 goto out_drop;
340 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
343 trans = btrfs_start_transaction(root, 1);
344 if (IS_ERR(trans)) {
345 ret = PTR_ERR(trans);
346 goto out_drop;
349 btrfs_update_iflags(inode);
350 inode_inc_iversion(inode);
351 inode->i_ctime = CURRENT_TIME;
352 ret = btrfs_update_inode(trans, root, inode);
354 btrfs_end_transaction(trans, root);
355 out_drop:
356 if (ret) {
357 ip->flags = ip_oldflags;
358 inode->i_flags = i_oldflags;
361 out_unlock:
362 mutex_unlock(&inode->i_mutex);
363 mnt_drop_write_file(file);
364 return ret;
367 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
369 struct inode *inode = file_inode(file);
371 return put_user(inode->i_generation, arg);
374 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
376 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
377 struct btrfs_device *device;
378 struct request_queue *q;
379 struct fstrim_range range;
380 u64 minlen = ULLONG_MAX;
381 u64 num_devices = 0;
382 int ret;
384 if (!capable(CAP_SYS_ADMIN))
385 return -EPERM;
387 rcu_read_lock();
388 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
389 dev_list) {
390 if (!device->bdev)
391 continue;
392 q = bdev_get_queue(device->bdev);
393 if (blk_queue_discard(q)) {
394 num_devices++;
395 minlen = min((u64)q->limits.discard_granularity,
396 minlen);
399 rcu_read_unlock();
401 if (!num_devices)
402 return -EOPNOTSUPP;
403 if (copy_from_user(&range, arg, sizeof(range)))
404 return -EFAULT;
407 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
408 * block group is in the logical address space, which can be any
409 * sectorsize aligned bytenr in the range [0, U64_MAX].
411 if (range.len < fs_info->sb->s_blocksize)
412 return -EINVAL;
414 range.minlen = max(range.minlen, minlen);
415 ret = btrfs_trim_fs(fs_info->tree_root, &range);
416 if (ret < 0)
417 return ret;
419 if (copy_to_user(arg, &range, sizeof(range)))
420 return -EFAULT;
422 return 0;
425 int btrfs_is_empty_uuid(u8 *uuid)
427 int i;
429 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
430 if (uuid[i])
431 return 0;
433 return 1;
436 static noinline int create_subvol(struct inode *dir,
437 struct dentry *dentry,
438 char *name, int namelen,
439 u64 *async_transid,
440 struct btrfs_qgroup_inherit *inherit)
442 struct btrfs_trans_handle *trans;
443 struct btrfs_key key;
444 struct btrfs_root_item root_item;
445 struct btrfs_inode_item *inode_item;
446 struct extent_buffer *leaf;
447 struct btrfs_root *root = BTRFS_I(dir)->root;
448 struct btrfs_root *new_root;
449 struct btrfs_block_rsv block_rsv;
450 struct timespec cur_time = CURRENT_TIME;
451 struct inode *inode;
452 int ret;
453 int err;
454 u64 objectid;
455 u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
456 u64 index = 0;
457 u64 qgroup_reserved;
458 uuid_le new_uuid;
460 ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
461 if (ret)
462 return ret;
465 * Don't create subvolume whose level is not zero. Or qgroup will be
466 * screwed up since it assume subvolme qgroup's level to be 0.
468 if (btrfs_qgroup_level(objectid))
469 return -ENOSPC;
471 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
473 * The same as the snapshot creation, please see the comment
474 * of create_snapshot().
476 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
477 8, &qgroup_reserved, false);
478 if (ret)
479 return ret;
481 trans = btrfs_start_transaction(root, 0);
482 if (IS_ERR(trans)) {
483 ret = PTR_ERR(trans);
484 btrfs_subvolume_release_metadata(root, &block_rsv,
485 qgroup_reserved);
486 return ret;
488 trans->block_rsv = &block_rsv;
489 trans->bytes_reserved = block_rsv.size;
491 ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
492 if (ret)
493 goto fail;
495 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
496 if (IS_ERR(leaf)) {
497 ret = PTR_ERR(leaf);
498 goto fail;
501 memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
502 btrfs_set_header_bytenr(leaf, leaf->start);
503 btrfs_set_header_generation(leaf, trans->transid);
504 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
505 btrfs_set_header_owner(leaf, objectid);
507 write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
508 BTRFS_FSID_SIZE);
509 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
510 btrfs_header_chunk_tree_uuid(leaf),
511 BTRFS_UUID_SIZE);
512 btrfs_mark_buffer_dirty(leaf);
514 memset(&root_item, 0, sizeof(root_item));
516 inode_item = &root_item.inode;
517 btrfs_set_stack_inode_generation(inode_item, 1);
518 btrfs_set_stack_inode_size(inode_item, 3);
519 btrfs_set_stack_inode_nlink(inode_item, 1);
520 btrfs_set_stack_inode_nbytes(inode_item, root->nodesize);
521 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
523 btrfs_set_root_flags(&root_item, 0);
524 btrfs_set_root_limit(&root_item, 0);
525 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
527 btrfs_set_root_bytenr(&root_item, leaf->start);
528 btrfs_set_root_generation(&root_item, trans->transid);
529 btrfs_set_root_level(&root_item, 0);
530 btrfs_set_root_refs(&root_item, 1);
531 btrfs_set_root_used(&root_item, leaf->len);
532 btrfs_set_root_last_snapshot(&root_item, 0);
534 btrfs_set_root_generation_v2(&root_item,
535 btrfs_root_generation(&root_item));
536 uuid_le_gen(&new_uuid);
537 memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
538 btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
539 btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
540 root_item.ctime = root_item.otime;
541 btrfs_set_root_ctransid(&root_item, trans->transid);
542 btrfs_set_root_otransid(&root_item, trans->transid);
544 btrfs_tree_unlock(leaf);
545 free_extent_buffer(leaf);
546 leaf = NULL;
548 btrfs_set_root_dirid(&root_item, new_dirid);
550 key.objectid = objectid;
551 key.offset = 0;
552 key.type = BTRFS_ROOT_ITEM_KEY;
553 ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
554 &root_item);
555 if (ret)
556 goto fail;
558 key.offset = (u64)-1;
559 new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
560 if (IS_ERR(new_root)) {
561 ret = PTR_ERR(new_root);
562 btrfs_abort_transaction(trans, root, ret);
563 goto fail;
566 btrfs_record_root_in_trans(trans, new_root);
568 ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
569 if (ret) {
570 /* We potentially lose an unused inode item here */
571 btrfs_abort_transaction(trans, root, ret);
572 goto fail;
575 mutex_lock(&new_root->objectid_mutex);
576 new_root->highest_objectid = new_dirid;
577 mutex_unlock(&new_root->objectid_mutex);
580 * insert the directory item
582 ret = btrfs_set_inode_index(dir, &index);
583 if (ret) {
584 btrfs_abort_transaction(trans, root, ret);
585 goto fail;
588 ret = btrfs_insert_dir_item(trans, root,
589 name, namelen, dir, &key,
590 BTRFS_FT_DIR, index);
591 if (ret) {
592 btrfs_abort_transaction(trans, root, ret);
593 goto fail;
596 btrfs_i_size_write(dir, dir->i_size + namelen * 2);
597 ret = btrfs_update_inode(trans, root, dir);
598 if (ret) {
599 btrfs_abort_transaction(trans, root, ret);
600 goto fail;
603 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
604 objectid, root->root_key.objectid,
605 btrfs_ino(dir), index, name, namelen);
606 if (ret) {
607 btrfs_abort_transaction(trans, root, ret);
608 goto fail;
611 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
612 root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
613 objectid);
614 if (ret)
615 btrfs_abort_transaction(trans, root, ret);
617 fail:
618 trans->block_rsv = NULL;
619 trans->bytes_reserved = 0;
620 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
622 if (async_transid) {
623 *async_transid = trans->transid;
624 err = btrfs_commit_transaction_async(trans, root, 1);
625 if (err)
626 err = btrfs_commit_transaction(trans, root);
627 } else {
628 err = btrfs_commit_transaction(trans, root);
630 if (err && !ret)
631 ret = err;
633 if (!ret) {
634 inode = btrfs_lookup_dentry(dir, dentry);
635 if (IS_ERR(inode))
636 return PTR_ERR(inode);
637 d_instantiate(dentry, inode);
639 return ret;
642 static void btrfs_wait_for_no_snapshoting_writes(struct btrfs_root *root)
644 s64 writers;
645 DEFINE_WAIT(wait);
647 do {
648 prepare_to_wait(&root->subv_writers->wait, &wait,
649 TASK_UNINTERRUPTIBLE);
651 writers = percpu_counter_sum(&root->subv_writers->counter);
652 if (writers)
653 schedule();
655 finish_wait(&root->subv_writers->wait, &wait);
656 } while (writers);
659 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
660 struct dentry *dentry, char *name, int namelen,
661 u64 *async_transid, bool readonly,
662 struct btrfs_qgroup_inherit *inherit)
664 struct inode *inode;
665 struct btrfs_pending_snapshot *pending_snapshot;
666 struct btrfs_trans_handle *trans;
667 int ret;
669 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
670 return -EINVAL;
672 atomic_inc(&root->will_be_snapshoted);
673 smp_mb__after_atomic();
674 btrfs_wait_for_no_snapshoting_writes(root);
676 ret = btrfs_start_delalloc_inodes(root, 0);
677 if (ret)
678 goto out;
680 btrfs_wait_ordered_extents(root, -1);
682 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
683 if (!pending_snapshot) {
684 ret = -ENOMEM;
685 goto out;
688 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
689 BTRFS_BLOCK_RSV_TEMP);
691 * 1 - parent dir inode
692 * 2 - dir entries
693 * 1 - root item
694 * 2 - root ref/backref
695 * 1 - root of snapshot
696 * 1 - UUID item
698 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
699 &pending_snapshot->block_rsv, 8,
700 &pending_snapshot->qgroup_reserved,
701 false);
702 if (ret)
703 goto free;
705 pending_snapshot->dentry = dentry;
706 pending_snapshot->root = root;
707 pending_snapshot->readonly = readonly;
708 pending_snapshot->dir = dir;
709 pending_snapshot->inherit = inherit;
711 trans = btrfs_start_transaction(root, 0);
712 if (IS_ERR(trans)) {
713 ret = PTR_ERR(trans);
714 goto fail;
717 spin_lock(&root->fs_info->trans_lock);
718 list_add(&pending_snapshot->list,
719 &trans->transaction->pending_snapshots);
720 spin_unlock(&root->fs_info->trans_lock);
721 if (async_transid) {
722 *async_transid = trans->transid;
723 ret = btrfs_commit_transaction_async(trans,
724 root->fs_info->extent_root, 1);
725 if (ret)
726 ret = btrfs_commit_transaction(trans, root);
727 } else {
728 ret = btrfs_commit_transaction(trans,
729 root->fs_info->extent_root);
731 if (ret)
732 goto fail;
734 ret = pending_snapshot->error;
735 if (ret)
736 goto fail;
738 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
739 if (ret)
740 goto fail;
742 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
743 if (IS_ERR(inode)) {
744 ret = PTR_ERR(inode);
745 goto fail;
748 d_instantiate(dentry, inode);
749 ret = 0;
750 fail:
751 btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
752 &pending_snapshot->block_rsv,
753 pending_snapshot->qgroup_reserved);
754 free:
755 kfree(pending_snapshot);
756 out:
757 if (atomic_dec_and_test(&root->will_be_snapshoted))
758 wake_up_atomic_t(&root->will_be_snapshoted);
759 return ret;
762 /* copy of may_delete in fs/namei.c()
763 * Check whether we can remove a link victim from directory dir, check
764 * whether the type of victim is right.
765 * 1. We can't do it if dir is read-only (done in permission())
766 * 2. We should have write and exec permissions on dir
767 * 3. We can't remove anything from append-only dir
768 * 4. We can't do anything with immutable dir (done in permission())
769 * 5. If the sticky bit on dir is set we should either
770 * a. be owner of dir, or
771 * b. be owner of victim, or
772 * c. have CAP_FOWNER capability
773 * 6. If the victim is append-only or immutable we can't do antyhing with
774 * links pointing to it.
775 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
776 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
777 * 9. We can't remove a root or mountpoint.
778 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
779 * nfs_async_unlink().
782 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
784 int error;
786 if (d_really_is_negative(victim))
787 return -ENOENT;
789 BUG_ON(d_inode(victim->d_parent) != dir);
790 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
792 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
793 if (error)
794 return error;
795 if (IS_APPEND(dir))
796 return -EPERM;
797 if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
798 IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
799 return -EPERM;
800 if (isdir) {
801 if (!d_is_dir(victim))
802 return -ENOTDIR;
803 if (IS_ROOT(victim))
804 return -EBUSY;
805 } else if (d_is_dir(victim))
806 return -EISDIR;
807 if (IS_DEADDIR(dir))
808 return -ENOENT;
809 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
810 return -EBUSY;
811 return 0;
814 /* copy of may_create in fs/namei.c() */
815 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
817 if (d_really_is_positive(child))
818 return -EEXIST;
819 if (IS_DEADDIR(dir))
820 return -ENOENT;
821 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
825 * Create a new subvolume below @parent. This is largely modeled after
826 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
827 * inside this filesystem so it's quite a bit simpler.
829 static noinline int btrfs_mksubvol(struct path *parent,
830 char *name, int namelen,
831 struct btrfs_root *snap_src,
832 u64 *async_transid, bool readonly,
833 struct btrfs_qgroup_inherit *inherit)
835 struct inode *dir = d_inode(parent->dentry);
836 struct dentry *dentry;
837 int error;
839 error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
840 if (error == -EINTR)
841 return error;
843 dentry = lookup_one_len(name, parent->dentry, namelen);
844 error = PTR_ERR(dentry);
845 if (IS_ERR(dentry))
846 goto out_unlock;
848 error = -EEXIST;
849 if (d_really_is_positive(dentry))
850 goto out_dput;
852 error = btrfs_may_create(dir, dentry);
853 if (error)
854 goto out_dput;
857 * even if this name doesn't exist, we may get hash collisions.
858 * check for them now when we can safely fail
860 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
861 dir->i_ino, name,
862 namelen);
863 if (error)
864 goto out_dput;
866 down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
868 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
869 goto out_up_read;
871 if (snap_src) {
872 error = create_snapshot(snap_src, dir, dentry, name, namelen,
873 async_transid, readonly, inherit);
874 } else {
875 error = create_subvol(dir, dentry, name, namelen,
876 async_transid, inherit);
878 if (!error)
879 fsnotify_mkdir(dir, dentry);
880 out_up_read:
881 up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
882 out_dput:
883 dput(dentry);
884 out_unlock:
885 mutex_unlock(&dir->i_mutex);
886 return error;
890 * When we're defragging a range, we don't want to kick it off again
891 * if it is really just waiting for delalloc to send it down.
892 * If we find a nice big extent or delalloc range for the bytes in the
893 * file you want to defrag, we return 0 to let you know to skip this
894 * part of the file
896 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
898 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
899 struct extent_map *em = NULL;
900 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
901 u64 end;
903 read_lock(&em_tree->lock);
904 em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
905 read_unlock(&em_tree->lock);
907 if (em) {
908 end = extent_map_end(em);
909 free_extent_map(em);
910 if (end - offset > thresh)
911 return 0;
913 /* if we already have a nice delalloc here, just stop */
914 thresh /= 2;
915 end = count_range_bits(io_tree, &offset, offset + thresh,
916 thresh, EXTENT_DELALLOC, 1);
917 if (end >= thresh)
918 return 0;
919 return 1;
923 * helper function to walk through a file and find extents
924 * newer than a specific transid, and smaller than thresh.
926 * This is used by the defragging code to find new and small
927 * extents
929 static int find_new_extents(struct btrfs_root *root,
930 struct inode *inode, u64 newer_than,
931 u64 *off, u32 thresh)
933 struct btrfs_path *path;
934 struct btrfs_key min_key;
935 struct extent_buffer *leaf;
936 struct btrfs_file_extent_item *extent;
937 int type;
938 int ret;
939 u64 ino = btrfs_ino(inode);
941 path = btrfs_alloc_path();
942 if (!path)
943 return -ENOMEM;
945 min_key.objectid = ino;
946 min_key.type = BTRFS_EXTENT_DATA_KEY;
947 min_key.offset = *off;
949 while (1) {
950 ret = btrfs_search_forward(root, &min_key, path, newer_than);
951 if (ret != 0)
952 goto none;
953 process_slot:
954 if (min_key.objectid != ino)
955 goto none;
956 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
957 goto none;
959 leaf = path->nodes[0];
960 extent = btrfs_item_ptr(leaf, path->slots[0],
961 struct btrfs_file_extent_item);
963 type = btrfs_file_extent_type(leaf, extent);
964 if (type == BTRFS_FILE_EXTENT_REG &&
965 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
966 check_defrag_in_cache(inode, min_key.offset, thresh)) {
967 *off = min_key.offset;
968 btrfs_free_path(path);
969 return 0;
972 path->slots[0]++;
973 if (path->slots[0] < btrfs_header_nritems(leaf)) {
974 btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
975 goto process_slot;
978 if (min_key.offset == (u64)-1)
979 goto none;
981 min_key.offset++;
982 btrfs_release_path(path);
984 none:
985 btrfs_free_path(path);
986 return -ENOENT;
989 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
991 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
992 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
993 struct extent_map *em;
994 u64 len = PAGE_CACHE_SIZE;
997 * hopefully we have this extent in the tree already, try without
998 * the full extent lock
1000 read_lock(&em_tree->lock);
1001 em = lookup_extent_mapping(em_tree, start, len);
1002 read_unlock(&em_tree->lock);
1004 if (!em) {
1005 struct extent_state *cached = NULL;
1006 u64 end = start + len - 1;
1008 /* get the big lock and read metadata off disk */
1009 lock_extent_bits(io_tree, start, end, 0, &cached);
1010 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
1011 unlock_extent_cached(io_tree, start, end, &cached, GFP_NOFS);
1013 if (IS_ERR(em))
1014 return NULL;
1017 return em;
1020 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1022 struct extent_map *next;
1023 bool ret = true;
1025 /* this is the last extent */
1026 if (em->start + em->len >= i_size_read(inode))
1027 return false;
1029 next = defrag_lookup_extent(inode, em->start + em->len);
1030 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1031 ret = false;
1032 else if ((em->block_start + em->block_len == next->block_start) &&
1033 (em->block_len > 128 * 1024 && next->block_len > 128 * 1024))
1034 ret = false;
1036 free_extent_map(next);
1037 return ret;
1040 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1041 u64 *last_len, u64 *skip, u64 *defrag_end,
1042 int compress)
1044 struct extent_map *em;
1045 int ret = 1;
1046 bool next_mergeable = true;
1047 bool prev_mergeable = true;
1050 * make sure that once we start defragging an extent, we keep on
1051 * defragging it
1053 if (start < *defrag_end)
1054 return 1;
1056 *skip = 0;
1058 em = defrag_lookup_extent(inode, start);
1059 if (!em)
1060 return 0;
1062 /* this will cover holes, and inline extents */
1063 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1064 ret = 0;
1065 goto out;
1068 if (!*defrag_end)
1069 prev_mergeable = false;
1071 next_mergeable = defrag_check_next_extent(inode, em);
1073 * we hit a real extent, if it is big or the next extent is not a
1074 * real extent, don't bother defragging it
1076 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1077 (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1078 ret = 0;
1079 out:
1081 * last_len ends up being a counter of how many bytes we've defragged.
1082 * every time we choose not to defrag an extent, we reset *last_len
1083 * so that the next tiny extent will force a defrag.
1085 * The end result of this is that tiny extents before a single big
1086 * extent will force at least part of that big extent to be defragged.
1088 if (ret) {
1089 *defrag_end = extent_map_end(em);
1090 } else {
1091 *last_len = 0;
1092 *skip = extent_map_end(em);
1093 *defrag_end = 0;
1096 free_extent_map(em);
1097 return ret;
1101 * it doesn't do much good to defrag one or two pages
1102 * at a time. This pulls in a nice chunk of pages
1103 * to COW and defrag.
1105 * It also makes sure the delalloc code has enough
1106 * dirty data to avoid making new small extents as part
1107 * of the defrag
1109 * It's a good idea to start RA on this range
1110 * before calling this.
1112 static int cluster_pages_for_defrag(struct inode *inode,
1113 struct page **pages,
1114 unsigned long start_index,
1115 unsigned long num_pages)
1117 unsigned long file_end;
1118 u64 isize = i_size_read(inode);
1119 u64 page_start;
1120 u64 page_end;
1121 u64 page_cnt;
1122 int ret;
1123 int i;
1124 int i_done;
1125 struct btrfs_ordered_extent *ordered;
1126 struct extent_state *cached_state = NULL;
1127 struct extent_io_tree *tree;
1128 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1130 file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1131 if (!isize || start_index > file_end)
1132 return 0;
1134 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1136 ret = btrfs_delalloc_reserve_space(inode,
1137 start_index << PAGE_CACHE_SHIFT,
1138 page_cnt << PAGE_CACHE_SHIFT);
1139 if (ret)
1140 return ret;
1141 i_done = 0;
1142 tree = &BTRFS_I(inode)->io_tree;
1144 /* step one, lock all the pages */
1145 for (i = 0; i < page_cnt; i++) {
1146 struct page *page;
1147 again:
1148 page = find_or_create_page(inode->i_mapping,
1149 start_index + i, mask);
1150 if (!page)
1151 break;
1153 page_start = page_offset(page);
1154 page_end = page_start + PAGE_CACHE_SIZE - 1;
1155 while (1) {
1156 lock_extent_bits(tree, page_start, page_end,
1157 0, &cached_state);
1158 ordered = btrfs_lookup_ordered_extent(inode,
1159 page_start);
1160 unlock_extent_cached(tree, page_start, page_end,
1161 &cached_state, GFP_NOFS);
1162 if (!ordered)
1163 break;
1165 unlock_page(page);
1166 btrfs_start_ordered_extent(inode, ordered, 1);
1167 btrfs_put_ordered_extent(ordered);
1168 lock_page(page);
1170 * we unlocked the page above, so we need check if
1171 * it was released or not.
1173 if (page->mapping != inode->i_mapping) {
1174 unlock_page(page);
1175 page_cache_release(page);
1176 goto again;
1180 if (!PageUptodate(page)) {
1181 btrfs_readpage(NULL, page);
1182 lock_page(page);
1183 if (!PageUptodate(page)) {
1184 unlock_page(page);
1185 page_cache_release(page);
1186 ret = -EIO;
1187 break;
1191 if (page->mapping != inode->i_mapping) {
1192 unlock_page(page);
1193 page_cache_release(page);
1194 goto again;
1197 pages[i] = page;
1198 i_done++;
1200 if (!i_done || ret)
1201 goto out;
1203 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1204 goto out;
1207 * so now we have a nice long stream of locked
1208 * and up to date pages, lets wait on them
1210 for (i = 0; i < i_done; i++)
1211 wait_on_page_writeback(pages[i]);
1213 page_start = page_offset(pages[0]);
1214 page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1216 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1217 page_start, page_end - 1, 0, &cached_state);
1218 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1219 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1220 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1221 &cached_state, GFP_NOFS);
1223 if (i_done != page_cnt) {
1224 spin_lock(&BTRFS_I(inode)->lock);
1225 BTRFS_I(inode)->outstanding_extents++;
1226 spin_unlock(&BTRFS_I(inode)->lock);
1227 btrfs_delalloc_release_space(inode,
1228 start_index << PAGE_CACHE_SHIFT,
1229 (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1233 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1234 &cached_state, GFP_NOFS);
1236 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1237 page_start, page_end - 1, &cached_state,
1238 GFP_NOFS);
1240 for (i = 0; i < i_done; i++) {
1241 clear_page_dirty_for_io(pages[i]);
1242 ClearPageChecked(pages[i]);
1243 set_page_extent_mapped(pages[i]);
1244 set_page_dirty(pages[i]);
1245 unlock_page(pages[i]);
1246 page_cache_release(pages[i]);
1248 return i_done;
1249 out:
1250 for (i = 0; i < i_done; i++) {
1251 unlock_page(pages[i]);
1252 page_cache_release(pages[i]);
1254 btrfs_delalloc_release_space(inode,
1255 start_index << PAGE_CACHE_SHIFT,
1256 page_cnt << PAGE_CACHE_SHIFT);
1257 return ret;
1261 int btrfs_defrag_file(struct inode *inode, struct file *file,
1262 struct btrfs_ioctl_defrag_range_args *range,
1263 u64 newer_than, unsigned long max_to_defrag)
1265 struct btrfs_root *root = BTRFS_I(inode)->root;
1266 struct file_ra_state *ra = NULL;
1267 unsigned long last_index;
1268 u64 isize = i_size_read(inode);
1269 u64 last_len = 0;
1270 u64 skip = 0;
1271 u64 defrag_end = 0;
1272 u64 newer_off = range->start;
1273 unsigned long i;
1274 unsigned long ra_index = 0;
1275 int ret;
1276 int defrag_count = 0;
1277 int compress_type = BTRFS_COMPRESS_ZLIB;
1278 u32 extent_thresh = range->extent_thresh;
1279 unsigned long max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1280 unsigned long cluster = max_cluster;
1281 u64 new_align = ~((u64)128 * 1024 - 1);
1282 struct page **pages = NULL;
1284 if (isize == 0)
1285 return 0;
1287 if (range->start >= isize)
1288 return -EINVAL;
1290 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1291 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1292 return -EINVAL;
1293 if (range->compress_type)
1294 compress_type = range->compress_type;
1297 if (extent_thresh == 0)
1298 extent_thresh = 256 * 1024;
1301 * if we were not given a file, allocate a readahead
1302 * context
1304 if (!file) {
1305 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1306 if (!ra)
1307 return -ENOMEM;
1308 file_ra_state_init(ra, inode->i_mapping);
1309 } else {
1310 ra = &file->f_ra;
1313 pages = kmalloc_array(max_cluster, sizeof(struct page *),
1314 GFP_NOFS);
1315 if (!pages) {
1316 ret = -ENOMEM;
1317 goto out_ra;
1320 /* find the last page to defrag */
1321 if (range->start + range->len > range->start) {
1322 last_index = min_t(u64, isize - 1,
1323 range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1324 } else {
1325 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1328 if (newer_than) {
1329 ret = find_new_extents(root, inode, newer_than,
1330 &newer_off, 64 * 1024);
1331 if (!ret) {
1332 range->start = newer_off;
1334 * we always align our defrag to help keep
1335 * the extents in the file evenly spaced
1337 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1338 } else
1339 goto out_ra;
1340 } else {
1341 i = range->start >> PAGE_CACHE_SHIFT;
1343 if (!max_to_defrag)
1344 max_to_defrag = last_index - i + 1;
1347 * make writeback starts from i, so the defrag range can be
1348 * written sequentially.
1350 if (i < inode->i_mapping->writeback_index)
1351 inode->i_mapping->writeback_index = i;
1353 while (i <= last_index && defrag_count < max_to_defrag &&
1354 (i < DIV_ROUND_UP(i_size_read(inode), PAGE_CACHE_SIZE))) {
1356 * make sure we stop running if someone unmounts
1357 * the FS
1359 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1360 break;
1362 if (btrfs_defrag_cancelled(root->fs_info)) {
1363 btrfs_debug(root->fs_info, "defrag_file cancelled");
1364 ret = -EAGAIN;
1365 break;
1368 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1369 extent_thresh, &last_len, &skip,
1370 &defrag_end, range->flags &
1371 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1372 unsigned long next;
1374 * the should_defrag function tells us how much to skip
1375 * bump our counter by the suggested amount
1377 next = DIV_ROUND_UP(skip, PAGE_CACHE_SIZE);
1378 i = max(i + 1, next);
1379 continue;
1382 if (!newer_than) {
1383 cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1384 PAGE_CACHE_SHIFT) - i;
1385 cluster = min(cluster, max_cluster);
1386 } else {
1387 cluster = max_cluster;
1390 if (i + cluster > ra_index) {
1391 ra_index = max(i, ra_index);
1392 btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1393 cluster);
1394 ra_index += cluster;
1397 mutex_lock(&inode->i_mutex);
1398 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1399 BTRFS_I(inode)->force_compress = compress_type;
1400 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1401 if (ret < 0) {
1402 mutex_unlock(&inode->i_mutex);
1403 goto out_ra;
1406 defrag_count += ret;
1407 balance_dirty_pages_ratelimited(inode->i_mapping);
1408 mutex_unlock(&inode->i_mutex);
1410 if (newer_than) {
1411 if (newer_off == (u64)-1)
1412 break;
1414 if (ret > 0)
1415 i += ret;
1417 newer_off = max(newer_off + 1,
1418 (u64)i << PAGE_CACHE_SHIFT);
1420 ret = find_new_extents(root, inode,
1421 newer_than, &newer_off,
1422 64 * 1024);
1423 if (!ret) {
1424 range->start = newer_off;
1425 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1426 } else {
1427 break;
1429 } else {
1430 if (ret > 0) {
1431 i += ret;
1432 last_len += ret << PAGE_CACHE_SHIFT;
1433 } else {
1434 i++;
1435 last_len = 0;
1440 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1441 filemap_flush(inode->i_mapping);
1442 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1443 &BTRFS_I(inode)->runtime_flags))
1444 filemap_flush(inode->i_mapping);
1447 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1448 /* the filemap_flush will queue IO into the worker threads, but
1449 * we have to make sure the IO is actually started and that
1450 * ordered extents get created before we return
1452 atomic_inc(&root->fs_info->async_submit_draining);
1453 while (atomic_read(&root->fs_info->nr_async_submits) ||
1454 atomic_read(&root->fs_info->async_delalloc_pages)) {
1455 wait_event(root->fs_info->async_submit_wait,
1456 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1457 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1459 atomic_dec(&root->fs_info->async_submit_draining);
1462 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1463 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1466 ret = defrag_count;
1468 out_ra:
1469 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1470 mutex_lock(&inode->i_mutex);
1471 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1472 mutex_unlock(&inode->i_mutex);
1474 if (!file)
1475 kfree(ra);
1476 kfree(pages);
1477 return ret;
1480 static noinline int btrfs_ioctl_resize(struct file *file,
1481 void __user *arg)
1483 u64 new_size;
1484 u64 old_size;
1485 u64 devid = 1;
1486 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1487 struct btrfs_ioctl_vol_args *vol_args;
1488 struct btrfs_trans_handle *trans;
1489 struct btrfs_device *device = NULL;
1490 char *sizestr;
1491 char *retptr;
1492 char *devstr = NULL;
1493 int ret = 0;
1494 int mod = 0;
1496 if (!capable(CAP_SYS_ADMIN))
1497 return -EPERM;
1499 ret = mnt_want_write_file(file);
1500 if (ret)
1501 return ret;
1503 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1504 1)) {
1505 mnt_drop_write_file(file);
1506 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1509 mutex_lock(&root->fs_info->volume_mutex);
1510 vol_args = memdup_user(arg, sizeof(*vol_args));
1511 if (IS_ERR(vol_args)) {
1512 ret = PTR_ERR(vol_args);
1513 goto out;
1516 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1518 sizestr = vol_args->name;
1519 devstr = strchr(sizestr, ':');
1520 if (devstr) {
1521 sizestr = devstr + 1;
1522 *devstr = '\0';
1523 devstr = vol_args->name;
1524 ret = kstrtoull(devstr, 10, &devid);
1525 if (ret)
1526 goto out_free;
1527 if (!devid) {
1528 ret = -EINVAL;
1529 goto out_free;
1531 btrfs_info(root->fs_info, "resizing devid %llu", devid);
1534 device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1535 if (!device) {
1536 btrfs_info(root->fs_info, "resizer unable to find device %llu",
1537 devid);
1538 ret = -ENODEV;
1539 goto out_free;
1542 if (!device->writeable) {
1543 btrfs_info(root->fs_info,
1544 "resizer unable to apply on readonly device %llu",
1545 devid);
1546 ret = -EPERM;
1547 goto out_free;
1550 if (!strcmp(sizestr, "max"))
1551 new_size = device->bdev->bd_inode->i_size;
1552 else {
1553 if (sizestr[0] == '-') {
1554 mod = -1;
1555 sizestr++;
1556 } else if (sizestr[0] == '+') {
1557 mod = 1;
1558 sizestr++;
1560 new_size = memparse(sizestr, &retptr);
1561 if (*retptr != '\0' || new_size == 0) {
1562 ret = -EINVAL;
1563 goto out_free;
1567 if (device->is_tgtdev_for_dev_replace) {
1568 ret = -EPERM;
1569 goto out_free;
1572 old_size = btrfs_device_get_total_bytes(device);
1574 if (mod < 0) {
1575 if (new_size > old_size) {
1576 ret = -EINVAL;
1577 goto out_free;
1579 new_size = old_size - new_size;
1580 } else if (mod > 0) {
1581 if (new_size > ULLONG_MAX - old_size) {
1582 ret = -ERANGE;
1583 goto out_free;
1585 new_size = old_size + new_size;
1588 if (new_size < 256 * 1024 * 1024) {
1589 ret = -EINVAL;
1590 goto out_free;
1592 if (new_size > device->bdev->bd_inode->i_size) {
1593 ret = -EFBIG;
1594 goto out_free;
1597 new_size = div_u64(new_size, root->sectorsize);
1598 new_size *= root->sectorsize;
1600 btrfs_info_in_rcu(root->fs_info, "new size for %s is %llu",
1601 rcu_str_deref(device->name), new_size);
1603 if (new_size > old_size) {
1604 trans = btrfs_start_transaction(root, 0);
1605 if (IS_ERR(trans)) {
1606 ret = PTR_ERR(trans);
1607 goto out_free;
1609 ret = btrfs_grow_device(trans, device, new_size);
1610 btrfs_commit_transaction(trans, root);
1611 } else if (new_size < old_size) {
1612 ret = btrfs_shrink_device(device, new_size);
1613 } /* equal, nothing need to do */
1615 out_free:
1616 kfree(vol_args);
1617 out:
1618 mutex_unlock(&root->fs_info->volume_mutex);
1619 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1620 mnt_drop_write_file(file);
1621 return ret;
1624 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1625 char *name, unsigned long fd, int subvol,
1626 u64 *transid, bool readonly,
1627 struct btrfs_qgroup_inherit *inherit)
1629 int namelen;
1630 int ret = 0;
1632 if (!S_ISDIR(file_inode(file)->i_mode))
1633 return -ENOTDIR;
1635 ret = mnt_want_write_file(file);
1636 if (ret)
1637 goto out;
1639 namelen = strlen(name);
1640 if (strchr(name, '/')) {
1641 ret = -EINVAL;
1642 goto out_drop_write;
1645 if (name[0] == '.' &&
1646 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1647 ret = -EEXIST;
1648 goto out_drop_write;
1651 if (subvol) {
1652 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1653 NULL, transid, readonly, inherit);
1654 } else {
1655 struct fd src = fdget(fd);
1656 struct inode *src_inode;
1657 if (!src.file) {
1658 ret = -EINVAL;
1659 goto out_drop_write;
1662 src_inode = file_inode(src.file);
1663 if (src_inode->i_sb != file_inode(file)->i_sb) {
1664 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1665 "Snapshot src from another FS");
1666 ret = -EXDEV;
1667 } else if (!inode_owner_or_capable(src_inode)) {
1669 * Subvolume creation is not restricted, but snapshots
1670 * are limited to own subvolumes only
1672 ret = -EPERM;
1673 } else {
1674 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1675 BTRFS_I(src_inode)->root,
1676 transid, readonly, inherit);
1678 fdput(src);
1680 out_drop_write:
1681 mnt_drop_write_file(file);
1682 out:
1683 return ret;
1686 static noinline int btrfs_ioctl_snap_create(struct file *file,
1687 void __user *arg, int subvol)
1689 struct btrfs_ioctl_vol_args *vol_args;
1690 int ret;
1692 if (!S_ISDIR(file_inode(file)->i_mode))
1693 return -ENOTDIR;
1695 vol_args = memdup_user(arg, sizeof(*vol_args));
1696 if (IS_ERR(vol_args))
1697 return PTR_ERR(vol_args);
1698 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1700 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1701 vol_args->fd, subvol,
1702 NULL, false, NULL);
1704 kfree(vol_args);
1705 return ret;
1708 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1709 void __user *arg, int subvol)
1711 struct btrfs_ioctl_vol_args_v2 *vol_args;
1712 int ret;
1713 u64 transid = 0;
1714 u64 *ptr = NULL;
1715 bool readonly = false;
1716 struct btrfs_qgroup_inherit *inherit = NULL;
1718 if (!S_ISDIR(file_inode(file)->i_mode))
1719 return -ENOTDIR;
1721 vol_args = memdup_user(arg, sizeof(*vol_args));
1722 if (IS_ERR(vol_args))
1723 return PTR_ERR(vol_args);
1724 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1726 if (vol_args->flags &
1727 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1728 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1729 ret = -EOPNOTSUPP;
1730 goto free_args;
1733 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1734 ptr = &transid;
1735 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1736 readonly = true;
1737 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1738 if (vol_args->size > PAGE_CACHE_SIZE) {
1739 ret = -EINVAL;
1740 goto free_args;
1742 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1743 if (IS_ERR(inherit)) {
1744 ret = PTR_ERR(inherit);
1745 goto free_args;
1749 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1750 vol_args->fd, subvol, ptr,
1751 readonly, inherit);
1752 if (ret)
1753 goto free_inherit;
1755 if (ptr && copy_to_user(arg +
1756 offsetof(struct btrfs_ioctl_vol_args_v2,
1757 transid),
1758 ptr, sizeof(*ptr)))
1759 ret = -EFAULT;
1761 free_inherit:
1762 kfree(inherit);
1763 free_args:
1764 kfree(vol_args);
1765 return ret;
1768 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1769 void __user *arg)
1771 struct inode *inode = file_inode(file);
1772 struct btrfs_root *root = BTRFS_I(inode)->root;
1773 int ret = 0;
1774 u64 flags = 0;
1776 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1777 return -EINVAL;
1779 down_read(&root->fs_info->subvol_sem);
1780 if (btrfs_root_readonly(root))
1781 flags |= BTRFS_SUBVOL_RDONLY;
1782 up_read(&root->fs_info->subvol_sem);
1784 if (copy_to_user(arg, &flags, sizeof(flags)))
1785 ret = -EFAULT;
1787 return ret;
1790 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1791 void __user *arg)
1793 struct inode *inode = file_inode(file);
1794 struct btrfs_root *root = BTRFS_I(inode)->root;
1795 struct btrfs_trans_handle *trans;
1796 u64 root_flags;
1797 u64 flags;
1798 int ret = 0;
1800 if (!inode_owner_or_capable(inode))
1801 return -EPERM;
1803 ret = mnt_want_write_file(file);
1804 if (ret)
1805 goto out;
1807 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1808 ret = -EINVAL;
1809 goto out_drop_write;
1812 if (copy_from_user(&flags, arg, sizeof(flags))) {
1813 ret = -EFAULT;
1814 goto out_drop_write;
1817 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1818 ret = -EINVAL;
1819 goto out_drop_write;
1822 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1823 ret = -EOPNOTSUPP;
1824 goto out_drop_write;
1827 down_write(&root->fs_info->subvol_sem);
1829 /* nothing to do */
1830 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1831 goto out_drop_sem;
1833 root_flags = btrfs_root_flags(&root->root_item);
1834 if (flags & BTRFS_SUBVOL_RDONLY) {
1835 btrfs_set_root_flags(&root->root_item,
1836 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1837 } else {
1839 * Block RO -> RW transition if this subvolume is involved in
1840 * send
1842 spin_lock(&root->root_item_lock);
1843 if (root->send_in_progress == 0) {
1844 btrfs_set_root_flags(&root->root_item,
1845 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1846 spin_unlock(&root->root_item_lock);
1847 } else {
1848 spin_unlock(&root->root_item_lock);
1849 btrfs_warn(root->fs_info,
1850 "Attempt to set subvolume %llu read-write during send",
1851 root->root_key.objectid);
1852 ret = -EPERM;
1853 goto out_drop_sem;
1857 trans = btrfs_start_transaction(root, 1);
1858 if (IS_ERR(trans)) {
1859 ret = PTR_ERR(trans);
1860 goto out_reset;
1863 ret = btrfs_update_root(trans, root->fs_info->tree_root,
1864 &root->root_key, &root->root_item);
1866 btrfs_commit_transaction(trans, root);
1867 out_reset:
1868 if (ret)
1869 btrfs_set_root_flags(&root->root_item, root_flags);
1870 out_drop_sem:
1871 up_write(&root->fs_info->subvol_sem);
1872 out_drop_write:
1873 mnt_drop_write_file(file);
1874 out:
1875 return ret;
1879 * helper to check if the subvolume references other subvolumes
1881 static noinline int may_destroy_subvol(struct btrfs_root *root)
1883 struct btrfs_path *path;
1884 struct btrfs_dir_item *di;
1885 struct btrfs_key key;
1886 u64 dir_id;
1887 int ret;
1889 path = btrfs_alloc_path();
1890 if (!path)
1891 return -ENOMEM;
1893 /* Make sure this root isn't set as the default subvol */
1894 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1895 di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1896 dir_id, "default", 7, 0);
1897 if (di && !IS_ERR(di)) {
1898 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1899 if (key.objectid == root->root_key.objectid) {
1900 ret = -EPERM;
1901 btrfs_err(root->fs_info, "deleting default subvolume "
1902 "%llu is not allowed", key.objectid);
1903 goto out;
1905 btrfs_release_path(path);
1908 key.objectid = root->root_key.objectid;
1909 key.type = BTRFS_ROOT_REF_KEY;
1910 key.offset = (u64)-1;
1912 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1913 &key, path, 0, 0);
1914 if (ret < 0)
1915 goto out;
1916 BUG_ON(ret == 0);
1918 ret = 0;
1919 if (path->slots[0] > 0) {
1920 path->slots[0]--;
1921 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1922 if (key.objectid == root->root_key.objectid &&
1923 key.type == BTRFS_ROOT_REF_KEY)
1924 ret = -ENOTEMPTY;
1926 out:
1927 btrfs_free_path(path);
1928 return ret;
1931 static noinline int key_in_sk(struct btrfs_key *key,
1932 struct btrfs_ioctl_search_key *sk)
1934 struct btrfs_key test;
1935 int ret;
1937 test.objectid = sk->min_objectid;
1938 test.type = sk->min_type;
1939 test.offset = sk->min_offset;
1941 ret = btrfs_comp_cpu_keys(key, &test);
1942 if (ret < 0)
1943 return 0;
1945 test.objectid = sk->max_objectid;
1946 test.type = sk->max_type;
1947 test.offset = sk->max_offset;
1949 ret = btrfs_comp_cpu_keys(key, &test);
1950 if (ret > 0)
1951 return 0;
1952 return 1;
1955 static noinline int copy_to_sk(struct btrfs_root *root,
1956 struct btrfs_path *path,
1957 struct btrfs_key *key,
1958 struct btrfs_ioctl_search_key *sk,
1959 size_t *buf_size,
1960 char __user *ubuf,
1961 unsigned long *sk_offset,
1962 int *num_found)
1964 u64 found_transid;
1965 struct extent_buffer *leaf;
1966 struct btrfs_ioctl_search_header sh;
1967 struct btrfs_key test;
1968 unsigned long item_off;
1969 unsigned long item_len;
1970 int nritems;
1971 int i;
1972 int slot;
1973 int ret = 0;
1975 leaf = path->nodes[0];
1976 slot = path->slots[0];
1977 nritems = btrfs_header_nritems(leaf);
1979 if (btrfs_header_generation(leaf) > sk->max_transid) {
1980 i = nritems;
1981 goto advance_key;
1983 found_transid = btrfs_header_generation(leaf);
1985 for (i = slot; i < nritems; i++) {
1986 item_off = btrfs_item_ptr_offset(leaf, i);
1987 item_len = btrfs_item_size_nr(leaf, i);
1989 btrfs_item_key_to_cpu(leaf, key, i);
1990 if (!key_in_sk(key, sk))
1991 continue;
1993 if (sizeof(sh) + item_len > *buf_size) {
1994 if (*num_found) {
1995 ret = 1;
1996 goto out;
2000 * return one empty item back for v1, which does not
2001 * handle -EOVERFLOW
2004 *buf_size = sizeof(sh) + item_len;
2005 item_len = 0;
2006 ret = -EOVERFLOW;
2009 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2010 ret = 1;
2011 goto out;
2014 sh.objectid = key->objectid;
2015 sh.offset = key->offset;
2016 sh.type = key->type;
2017 sh.len = item_len;
2018 sh.transid = found_transid;
2020 /* copy search result header */
2021 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2022 ret = -EFAULT;
2023 goto out;
2026 *sk_offset += sizeof(sh);
2028 if (item_len) {
2029 char __user *up = ubuf + *sk_offset;
2030 /* copy the item */
2031 if (read_extent_buffer_to_user(leaf, up,
2032 item_off, item_len)) {
2033 ret = -EFAULT;
2034 goto out;
2037 *sk_offset += item_len;
2039 (*num_found)++;
2041 if (ret) /* -EOVERFLOW from above */
2042 goto out;
2044 if (*num_found >= sk->nr_items) {
2045 ret = 1;
2046 goto out;
2049 advance_key:
2050 ret = 0;
2051 test.objectid = sk->max_objectid;
2052 test.type = sk->max_type;
2053 test.offset = sk->max_offset;
2054 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2055 ret = 1;
2056 else if (key->offset < (u64)-1)
2057 key->offset++;
2058 else if (key->type < (u8)-1) {
2059 key->offset = 0;
2060 key->type++;
2061 } else if (key->objectid < (u64)-1) {
2062 key->offset = 0;
2063 key->type = 0;
2064 key->objectid++;
2065 } else
2066 ret = 1;
2067 out:
2069 * 0: all items from this leaf copied, continue with next
2070 * 1: * more items can be copied, but unused buffer is too small
2071 * * all items were found
2072 * Either way, it will stops the loop which iterates to the next
2073 * leaf
2074 * -EOVERFLOW: item was to large for buffer
2075 * -EFAULT: could not copy extent buffer back to userspace
2077 return ret;
2080 static noinline int search_ioctl(struct inode *inode,
2081 struct btrfs_ioctl_search_key *sk,
2082 size_t *buf_size,
2083 char __user *ubuf)
2085 struct btrfs_root *root;
2086 struct btrfs_key key;
2087 struct btrfs_path *path;
2088 struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
2089 int ret;
2090 int num_found = 0;
2091 unsigned long sk_offset = 0;
2093 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2094 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2095 return -EOVERFLOW;
2098 path = btrfs_alloc_path();
2099 if (!path)
2100 return -ENOMEM;
2102 if (sk->tree_id == 0) {
2103 /* search the root of the inode that was passed */
2104 root = BTRFS_I(inode)->root;
2105 } else {
2106 key.objectid = sk->tree_id;
2107 key.type = BTRFS_ROOT_ITEM_KEY;
2108 key.offset = (u64)-1;
2109 root = btrfs_read_fs_root_no_name(info, &key);
2110 if (IS_ERR(root)) {
2111 btrfs_err(info, "could not find root %llu",
2112 sk->tree_id);
2113 btrfs_free_path(path);
2114 return -ENOENT;
2118 key.objectid = sk->min_objectid;
2119 key.type = sk->min_type;
2120 key.offset = sk->min_offset;
2122 while (1) {
2123 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2124 if (ret != 0) {
2125 if (ret > 0)
2126 ret = 0;
2127 goto err;
2129 ret = copy_to_sk(root, path, &key, sk, buf_size, ubuf,
2130 &sk_offset, &num_found);
2131 btrfs_release_path(path);
2132 if (ret)
2133 break;
2136 if (ret > 0)
2137 ret = 0;
2138 err:
2139 sk->nr_items = num_found;
2140 btrfs_free_path(path);
2141 return ret;
2144 static noinline int btrfs_ioctl_tree_search(struct file *file,
2145 void __user *argp)
2147 struct btrfs_ioctl_search_args __user *uargs;
2148 struct btrfs_ioctl_search_key sk;
2149 struct inode *inode;
2150 int ret;
2151 size_t buf_size;
2153 if (!capable(CAP_SYS_ADMIN))
2154 return -EPERM;
2156 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2158 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2159 return -EFAULT;
2161 buf_size = sizeof(uargs->buf);
2163 inode = file_inode(file);
2164 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2167 * In the origin implementation an overflow is handled by returning a
2168 * search header with a len of zero, so reset ret.
2170 if (ret == -EOVERFLOW)
2171 ret = 0;
2173 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2174 ret = -EFAULT;
2175 return ret;
2178 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2179 void __user *argp)
2181 struct btrfs_ioctl_search_args_v2 __user *uarg;
2182 struct btrfs_ioctl_search_args_v2 args;
2183 struct inode *inode;
2184 int ret;
2185 size_t buf_size;
2186 const size_t buf_limit = 16 * 1024 * 1024;
2188 if (!capable(CAP_SYS_ADMIN))
2189 return -EPERM;
2191 /* copy search header and buffer size */
2192 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2193 if (copy_from_user(&args, uarg, sizeof(args)))
2194 return -EFAULT;
2196 buf_size = args.buf_size;
2198 if (buf_size < sizeof(struct btrfs_ioctl_search_header))
2199 return -EOVERFLOW;
2201 /* limit result size to 16MB */
2202 if (buf_size > buf_limit)
2203 buf_size = buf_limit;
2205 inode = file_inode(file);
2206 ret = search_ioctl(inode, &args.key, &buf_size,
2207 (char *)(&uarg->buf[0]));
2208 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2209 ret = -EFAULT;
2210 else if (ret == -EOVERFLOW &&
2211 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2212 ret = -EFAULT;
2214 return ret;
2218 * Search INODE_REFs to identify path name of 'dirid' directory
2219 * in a 'tree_id' tree. and sets path name to 'name'.
2221 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2222 u64 tree_id, u64 dirid, char *name)
2224 struct btrfs_root *root;
2225 struct btrfs_key key;
2226 char *ptr;
2227 int ret = -1;
2228 int slot;
2229 int len;
2230 int total_len = 0;
2231 struct btrfs_inode_ref *iref;
2232 struct extent_buffer *l;
2233 struct btrfs_path *path;
2235 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2236 name[0]='\0';
2237 return 0;
2240 path = btrfs_alloc_path();
2241 if (!path)
2242 return -ENOMEM;
2244 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2246 key.objectid = tree_id;
2247 key.type = BTRFS_ROOT_ITEM_KEY;
2248 key.offset = (u64)-1;
2249 root = btrfs_read_fs_root_no_name(info, &key);
2250 if (IS_ERR(root)) {
2251 btrfs_err(info, "could not find root %llu", tree_id);
2252 ret = -ENOENT;
2253 goto out;
2256 key.objectid = dirid;
2257 key.type = BTRFS_INODE_REF_KEY;
2258 key.offset = (u64)-1;
2260 while (1) {
2261 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2262 if (ret < 0)
2263 goto out;
2264 else if (ret > 0) {
2265 ret = btrfs_previous_item(root, path, dirid,
2266 BTRFS_INODE_REF_KEY);
2267 if (ret < 0)
2268 goto out;
2269 else if (ret > 0) {
2270 ret = -ENOENT;
2271 goto out;
2275 l = path->nodes[0];
2276 slot = path->slots[0];
2277 btrfs_item_key_to_cpu(l, &key, slot);
2279 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2280 len = btrfs_inode_ref_name_len(l, iref);
2281 ptr -= len + 1;
2282 total_len += len + 1;
2283 if (ptr < name) {
2284 ret = -ENAMETOOLONG;
2285 goto out;
2288 *(ptr + len) = '/';
2289 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2291 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2292 break;
2294 btrfs_release_path(path);
2295 key.objectid = key.offset;
2296 key.offset = (u64)-1;
2297 dirid = key.objectid;
2299 memmove(name, ptr, total_len);
2300 name[total_len] = '\0';
2301 ret = 0;
2302 out:
2303 btrfs_free_path(path);
2304 return ret;
2307 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2308 void __user *argp)
2310 struct btrfs_ioctl_ino_lookup_args *args;
2311 struct inode *inode;
2312 int ret = 0;
2314 args = memdup_user(argp, sizeof(*args));
2315 if (IS_ERR(args))
2316 return PTR_ERR(args);
2318 inode = file_inode(file);
2321 * Unprivileged query to obtain the containing subvolume root id. The
2322 * path is reset so it's consistent with btrfs_search_path_in_tree.
2324 if (args->treeid == 0)
2325 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2327 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2328 args->name[0] = 0;
2329 goto out;
2332 if (!capable(CAP_SYS_ADMIN)) {
2333 ret = -EPERM;
2334 goto out;
2337 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2338 args->treeid, args->objectid,
2339 args->name);
2341 out:
2342 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2343 ret = -EFAULT;
2345 kfree(args);
2346 return ret;
2349 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2350 void __user *arg)
2352 struct dentry *parent = file->f_path.dentry;
2353 struct dentry *dentry;
2354 struct inode *dir = d_inode(parent);
2355 struct inode *inode;
2356 struct btrfs_root *root = BTRFS_I(dir)->root;
2357 struct btrfs_root *dest = NULL;
2358 struct btrfs_ioctl_vol_args *vol_args;
2359 struct btrfs_trans_handle *trans;
2360 struct btrfs_block_rsv block_rsv;
2361 u64 root_flags;
2362 u64 qgroup_reserved;
2363 int namelen;
2364 int ret;
2365 int err = 0;
2367 if (!S_ISDIR(dir->i_mode))
2368 return -ENOTDIR;
2370 vol_args = memdup_user(arg, sizeof(*vol_args));
2371 if (IS_ERR(vol_args))
2372 return PTR_ERR(vol_args);
2374 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2375 namelen = strlen(vol_args->name);
2376 if (strchr(vol_args->name, '/') ||
2377 strncmp(vol_args->name, "..", namelen) == 0) {
2378 err = -EINVAL;
2379 goto out;
2382 err = mnt_want_write_file(file);
2383 if (err)
2384 goto out;
2387 err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2388 if (err == -EINTR)
2389 goto out_drop_write;
2390 dentry = lookup_one_len(vol_args->name, parent, namelen);
2391 if (IS_ERR(dentry)) {
2392 err = PTR_ERR(dentry);
2393 goto out_unlock_dir;
2396 if (d_really_is_negative(dentry)) {
2397 err = -ENOENT;
2398 goto out_dput;
2401 inode = d_inode(dentry);
2402 dest = BTRFS_I(inode)->root;
2403 if (!capable(CAP_SYS_ADMIN)) {
2405 * Regular user. Only allow this with a special mount
2406 * option, when the user has write+exec access to the
2407 * subvol root, and when rmdir(2) would have been
2408 * allowed.
2410 * Note that this is _not_ check that the subvol is
2411 * empty or doesn't contain data that we wouldn't
2412 * otherwise be able to delete.
2414 * Users who want to delete empty subvols should try
2415 * rmdir(2).
2417 err = -EPERM;
2418 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2419 goto out_dput;
2422 * Do not allow deletion if the parent dir is the same
2423 * as the dir to be deleted. That means the ioctl
2424 * must be called on the dentry referencing the root
2425 * of the subvol, not a random directory contained
2426 * within it.
2428 err = -EINVAL;
2429 if (root == dest)
2430 goto out_dput;
2432 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2433 if (err)
2434 goto out_dput;
2437 /* check if subvolume may be deleted by a user */
2438 err = btrfs_may_delete(dir, dentry, 1);
2439 if (err)
2440 goto out_dput;
2442 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2443 err = -EINVAL;
2444 goto out_dput;
2447 mutex_lock(&inode->i_mutex);
2450 * Don't allow to delete a subvolume with send in progress. This is
2451 * inside the i_mutex so the error handling that has to drop the bit
2452 * again is not run concurrently.
2454 spin_lock(&dest->root_item_lock);
2455 root_flags = btrfs_root_flags(&dest->root_item);
2456 if (dest->send_in_progress == 0) {
2457 btrfs_set_root_flags(&dest->root_item,
2458 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2459 spin_unlock(&dest->root_item_lock);
2460 } else {
2461 spin_unlock(&dest->root_item_lock);
2462 btrfs_warn(root->fs_info,
2463 "Attempt to delete subvolume %llu during send",
2464 dest->root_key.objectid);
2465 err = -EPERM;
2466 goto out_unlock_inode;
2469 down_write(&root->fs_info->subvol_sem);
2471 err = may_destroy_subvol(dest);
2472 if (err)
2473 goto out_up_write;
2475 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2477 * One for dir inode, two for dir entries, two for root
2478 * ref/backref.
2480 err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2481 5, &qgroup_reserved, true);
2482 if (err)
2483 goto out_up_write;
2485 trans = btrfs_start_transaction(root, 0);
2486 if (IS_ERR(trans)) {
2487 err = PTR_ERR(trans);
2488 goto out_release;
2490 trans->block_rsv = &block_rsv;
2491 trans->bytes_reserved = block_rsv.size;
2493 ret = btrfs_unlink_subvol(trans, root, dir,
2494 dest->root_key.objectid,
2495 dentry->d_name.name,
2496 dentry->d_name.len);
2497 if (ret) {
2498 err = ret;
2499 btrfs_abort_transaction(trans, root, ret);
2500 goto out_end_trans;
2503 btrfs_record_root_in_trans(trans, dest);
2505 memset(&dest->root_item.drop_progress, 0,
2506 sizeof(dest->root_item.drop_progress));
2507 dest->root_item.drop_level = 0;
2508 btrfs_set_root_refs(&dest->root_item, 0);
2510 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
2511 ret = btrfs_insert_orphan_item(trans,
2512 root->fs_info->tree_root,
2513 dest->root_key.objectid);
2514 if (ret) {
2515 btrfs_abort_transaction(trans, root, ret);
2516 err = ret;
2517 goto out_end_trans;
2521 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2522 dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2523 dest->root_key.objectid);
2524 if (ret && ret != -ENOENT) {
2525 btrfs_abort_transaction(trans, root, ret);
2526 err = ret;
2527 goto out_end_trans;
2529 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2530 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2531 dest->root_item.received_uuid,
2532 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2533 dest->root_key.objectid);
2534 if (ret && ret != -ENOENT) {
2535 btrfs_abort_transaction(trans, root, ret);
2536 err = ret;
2537 goto out_end_trans;
2541 out_end_trans:
2542 trans->block_rsv = NULL;
2543 trans->bytes_reserved = 0;
2544 if (!err)
2545 btrfs_record_snapshot_destroy(trans, dir);
2546 ret = btrfs_end_transaction(trans, root);
2547 if (ret && !err)
2548 err = ret;
2549 inode->i_flags |= S_DEAD;
2550 out_release:
2551 btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2552 out_up_write:
2553 up_write(&root->fs_info->subvol_sem);
2554 if (err) {
2555 spin_lock(&dest->root_item_lock);
2556 root_flags = btrfs_root_flags(&dest->root_item);
2557 btrfs_set_root_flags(&dest->root_item,
2558 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2559 spin_unlock(&dest->root_item_lock);
2561 out_unlock_inode:
2562 mutex_unlock(&inode->i_mutex);
2563 if (!err) {
2564 d_invalidate(dentry);
2565 btrfs_invalidate_inodes(dest);
2566 d_delete(dentry);
2567 ASSERT(dest->send_in_progress == 0);
2569 /* the last ref */
2570 if (dest->ino_cache_inode) {
2571 iput(dest->ino_cache_inode);
2572 dest->ino_cache_inode = NULL;
2575 out_dput:
2576 dput(dentry);
2577 out_unlock_dir:
2578 mutex_unlock(&dir->i_mutex);
2579 out_drop_write:
2580 mnt_drop_write_file(file);
2581 out:
2582 kfree(vol_args);
2583 return err;
2586 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2588 struct inode *inode = file_inode(file);
2589 struct btrfs_root *root = BTRFS_I(inode)->root;
2590 struct btrfs_ioctl_defrag_range_args *range;
2591 int ret;
2593 ret = mnt_want_write_file(file);
2594 if (ret)
2595 return ret;
2597 if (btrfs_root_readonly(root)) {
2598 ret = -EROFS;
2599 goto out;
2602 switch (inode->i_mode & S_IFMT) {
2603 case S_IFDIR:
2604 if (!capable(CAP_SYS_ADMIN)) {
2605 ret = -EPERM;
2606 goto out;
2608 ret = btrfs_defrag_root(root);
2609 if (ret)
2610 goto out;
2611 ret = btrfs_defrag_root(root->fs_info->extent_root);
2612 break;
2613 case S_IFREG:
2614 if (!(file->f_mode & FMODE_WRITE)) {
2615 ret = -EINVAL;
2616 goto out;
2619 range = kzalloc(sizeof(*range), GFP_KERNEL);
2620 if (!range) {
2621 ret = -ENOMEM;
2622 goto out;
2625 if (argp) {
2626 if (copy_from_user(range, argp,
2627 sizeof(*range))) {
2628 ret = -EFAULT;
2629 kfree(range);
2630 goto out;
2632 /* compression requires us to start the IO */
2633 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2634 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2635 range->extent_thresh = (u32)-1;
2637 } else {
2638 /* the rest are all set to zero by kzalloc */
2639 range->len = (u64)-1;
2641 ret = btrfs_defrag_file(file_inode(file), file,
2642 range, 0, 0);
2643 if (ret > 0)
2644 ret = 0;
2645 kfree(range);
2646 break;
2647 default:
2648 ret = -EINVAL;
2650 out:
2651 mnt_drop_write_file(file);
2652 return ret;
2655 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2657 struct btrfs_ioctl_vol_args *vol_args;
2658 int ret;
2660 if (!capable(CAP_SYS_ADMIN))
2661 return -EPERM;
2663 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2664 1)) {
2665 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2668 mutex_lock(&root->fs_info->volume_mutex);
2669 vol_args = memdup_user(arg, sizeof(*vol_args));
2670 if (IS_ERR(vol_args)) {
2671 ret = PTR_ERR(vol_args);
2672 goto out;
2675 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2676 ret = btrfs_init_new_device(root, vol_args->name);
2678 if (!ret)
2679 btrfs_info(root->fs_info, "disk added %s",vol_args->name);
2681 kfree(vol_args);
2682 out:
2683 mutex_unlock(&root->fs_info->volume_mutex);
2684 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2685 return ret;
2688 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2690 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2691 struct btrfs_ioctl_vol_args *vol_args;
2692 int ret;
2694 if (!capable(CAP_SYS_ADMIN))
2695 return -EPERM;
2697 ret = mnt_want_write_file(file);
2698 if (ret)
2699 return ret;
2701 vol_args = memdup_user(arg, sizeof(*vol_args));
2702 if (IS_ERR(vol_args)) {
2703 ret = PTR_ERR(vol_args);
2704 goto err_drop;
2707 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2709 if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2710 1)) {
2711 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2712 goto out;
2715 mutex_lock(&root->fs_info->volume_mutex);
2716 ret = btrfs_rm_device(root, vol_args->name);
2717 mutex_unlock(&root->fs_info->volume_mutex);
2718 atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2720 if (!ret)
2721 btrfs_info(root->fs_info, "disk deleted %s",vol_args->name);
2723 out:
2724 kfree(vol_args);
2725 err_drop:
2726 mnt_drop_write_file(file);
2727 return ret;
2730 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2732 struct btrfs_ioctl_fs_info_args *fi_args;
2733 struct btrfs_device *device;
2734 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2735 int ret = 0;
2737 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2738 if (!fi_args)
2739 return -ENOMEM;
2741 mutex_lock(&fs_devices->device_list_mutex);
2742 fi_args->num_devices = fs_devices->num_devices;
2743 memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2745 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2746 if (device->devid > fi_args->max_id)
2747 fi_args->max_id = device->devid;
2749 mutex_unlock(&fs_devices->device_list_mutex);
2751 fi_args->nodesize = root->fs_info->super_copy->nodesize;
2752 fi_args->sectorsize = root->fs_info->super_copy->sectorsize;
2753 fi_args->clone_alignment = root->fs_info->super_copy->sectorsize;
2755 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2756 ret = -EFAULT;
2758 kfree(fi_args);
2759 return ret;
2762 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2764 struct btrfs_ioctl_dev_info_args *di_args;
2765 struct btrfs_device *dev;
2766 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2767 int ret = 0;
2768 char *s_uuid = NULL;
2770 di_args = memdup_user(arg, sizeof(*di_args));
2771 if (IS_ERR(di_args))
2772 return PTR_ERR(di_args);
2774 if (!btrfs_is_empty_uuid(di_args->uuid))
2775 s_uuid = di_args->uuid;
2777 mutex_lock(&fs_devices->device_list_mutex);
2778 dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2780 if (!dev) {
2781 ret = -ENODEV;
2782 goto out;
2785 di_args->devid = dev->devid;
2786 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
2787 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2788 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2789 if (dev->name) {
2790 struct rcu_string *name;
2792 rcu_read_lock();
2793 name = rcu_dereference(dev->name);
2794 strncpy(di_args->path, name->str, sizeof(di_args->path));
2795 rcu_read_unlock();
2796 di_args->path[sizeof(di_args->path) - 1] = 0;
2797 } else {
2798 di_args->path[0] = '\0';
2801 out:
2802 mutex_unlock(&fs_devices->device_list_mutex);
2803 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2804 ret = -EFAULT;
2806 kfree(di_args);
2807 return ret;
2810 static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2812 struct page *page;
2814 page = grab_cache_page(inode->i_mapping, index);
2815 if (!page)
2816 return ERR_PTR(-ENOMEM);
2818 if (!PageUptodate(page)) {
2819 int ret;
2821 ret = btrfs_readpage(NULL, page);
2822 if (ret)
2823 return ERR_PTR(ret);
2824 lock_page(page);
2825 if (!PageUptodate(page)) {
2826 unlock_page(page);
2827 page_cache_release(page);
2828 return ERR_PTR(-EIO);
2830 if (page->mapping != inode->i_mapping) {
2831 unlock_page(page);
2832 page_cache_release(page);
2833 return ERR_PTR(-EAGAIN);
2837 return page;
2840 static int gather_extent_pages(struct inode *inode, struct page **pages,
2841 int num_pages, u64 off)
2843 int i;
2844 pgoff_t index = off >> PAGE_CACHE_SHIFT;
2846 for (i = 0; i < num_pages; i++) {
2847 again:
2848 pages[i] = extent_same_get_page(inode, index + i);
2849 if (IS_ERR(pages[i])) {
2850 int err = PTR_ERR(pages[i]);
2852 if (err == -EAGAIN)
2853 goto again;
2854 pages[i] = NULL;
2855 return err;
2858 return 0;
2861 static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2862 bool retry_range_locking)
2865 * Do any pending delalloc/csum calculations on inode, one way or
2866 * another, and lock file content.
2867 * The locking order is:
2869 * 1) pages
2870 * 2) range in the inode's io tree
2872 while (1) {
2873 struct btrfs_ordered_extent *ordered;
2874 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2875 ordered = btrfs_lookup_first_ordered_extent(inode,
2876 off + len - 1);
2877 if ((!ordered ||
2878 ordered->file_offset + ordered->len <= off ||
2879 ordered->file_offset >= off + len) &&
2880 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2881 off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2882 if (ordered)
2883 btrfs_put_ordered_extent(ordered);
2884 break;
2886 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2887 if (ordered)
2888 btrfs_put_ordered_extent(ordered);
2889 if (!retry_range_locking)
2890 return -EAGAIN;
2891 btrfs_wait_ordered_range(inode, off, len);
2893 return 0;
2896 static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2898 mutex_unlock(&inode1->i_mutex);
2899 mutex_unlock(&inode2->i_mutex);
2902 static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2904 if (inode1 < inode2)
2905 swap(inode1, inode2);
2907 mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2908 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2911 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2912 struct inode *inode2, u64 loff2, u64 len)
2914 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2915 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2918 static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2919 struct inode *inode2, u64 loff2, u64 len,
2920 bool retry_range_locking)
2922 int ret;
2924 if (inode1 < inode2) {
2925 swap(inode1, inode2);
2926 swap(loff1, loff2);
2928 ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2929 if (ret)
2930 return ret;
2931 ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2932 if (ret)
2933 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2934 loff1 + len - 1);
2935 return ret;
2938 struct cmp_pages {
2939 int num_pages;
2940 struct page **src_pages;
2941 struct page **dst_pages;
2944 static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2946 int i;
2947 struct page *pg;
2949 for (i = 0; i < cmp->num_pages; i++) {
2950 pg = cmp->src_pages[i];
2951 if (pg) {
2952 unlock_page(pg);
2953 page_cache_release(pg);
2955 pg = cmp->dst_pages[i];
2956 if (pg) {
2957 unlock_page(pg);
2958 page_cache_release(pg);
2961 kfree(cmp->src_pages);
2962 kfree(cmp->dst_pages);
2965 static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2966 struct inode *dst, u64 dst_loff,
2967 u64 len, struct cmp_pages *cmp)
2969 int ret;
2970 int num_pages = PAGE_CACHE_ALIGN(len) >> PAGE_CACHE_SHIFT;
2971 struct page **src_pgarr, **dst_pgarr;
2974 * We must gather up all the pages before we initiate our
2975 * extent locking. We use an array for the page pointers. Size
2976 * of the array is bounded by len, which is in turn bounded by
2977 * BTRFS_MAX_DEDUPE_LEN.
2979 src_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2980 dst_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2981 if (!src_pgarr || !dst_pgarr) {
2982 kfree(src_pgarr);
2983 kfree(dst_pgarr);
2984 return -ENOMEM;
2986 cmp->num_pages = num_pages;
2987 cmp->src_pages = src_pgarr;
2988 cmp->dst_pages = dst_pgarr;
2990 ret = gather_extent_pages(src, cmp->src_pages, cmp->num_pages, loff);
2991 if (ret)
2992 goto out;
2994 ret = gather_extent_pages(dst, cmp->dst_pages, cmp->num_pages, dst_loff);
2996 out:
2997 if (ret)
2998 btrfs_cmp_data_free(cmp);
2999 return ret;
3002 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
3003 u64 dst_loff, u64 len, struct cmp_pages *cmp)
3005 int ret = 0;
3006 int i;
3007 struct page *src_page, *dst_page;
3008 unsigned int cmp_len = PAGE_CACHE_SIZE;
3009 void *addr, *dst_addr;
3011 i = 0;
3012 while (len) {
3013 if (len < PAGE_CACHE_SIZE)
3014 cmp_len = len;
3016 BUG_ON(i >= cmp->num_pages);
3018 src_page = cmp->src_pages[i];
3019 dst_page = cmp->dst_pages[i];
3020 ASSERT(PageLocked(src_page));
3021 ASSERT(PageLocked(dst_page));
3023 addr = kmap_atomic(src_page);
3024 dst_addr = kmap_atomic(dst_page);
3026 flush_dcache_page(src_page);
3027 flush_dcache_page(dst_page);
3029 if (memcmp(addr, dst_addr, cmp_len))
3030 ret = BTRFS_SAME_DATA_DIFFERS;
3032 kunmap_atomic(addr);
3033 kunmap_atomic(dst_addr);
3035 if (ret)
3036 break;
3038 len -= cmp_len;
3039 i++;
3042 return ret;
3045 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3046 u64 olen)
3048 u64 len = *plen;
3049 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3051 if (off + olen > inode->i_size || off + olen < off)
3052 return -EINVAL;
3054 /* if we extend to eof, continue to block boundary */
3055 if (off + len == inode->i_size)
3056 *plen = len = ALIGN(inode->i_size, bs) - off;
3058 /* Check that we are block aligned - btrfs_clone() requires this */
3059 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3060 return -EINVAL;
3062 return 0;
3065 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3066 struct inode *dst, u64 dst_loff)
3068 int ret;
3069 u64 len = olen;
3070 struct cmp_pages cmp;
3071 int same_inode = 0;
3072 u64 same_lock_start = 0;
3073 u64 same_lock_len = 0;
3075 if (src == dst)
3076 same_inode = 1;
3078 if (len == 0)
3079 return 0;
3081 if (same_inode) {
3082 mutex_lock(&src->i_mutex);
3084 ret = extent_same_check_offsets(src, loff, &len, olen);
3085 if (ret)
3086 goto out_unlock;
3089 * Single inode case wants the same checks, except we
3090 * don't want our length pushed out past i_size as
3091 * comparing that data range makes no sense.
3093 * extent_same_check_offsets() will do this for an
3094 * unaligned length at i_size, so catch it here and
3095 * reject the request.
3097 * This effectively means we require aligned extents
3098 * for the single-inode case, whereas the other cases
3099 * allow an unaligned length so long as it ends at
3100 * i_size.
3102 if (len != olen) {
3103 ret = -EINVAL;
3104 goto out_unlock;
3107 /* Check for overlapping ranges */
3108 if (dst_loff + len > loff && dst_loff < loff + len) {
3109 ret = -EINVAL;
3110 goto out_unlock;
3113 same_lock_start = min_t(u64, loff, dst_loff);
3114 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
3115 } else {
3116 btrfs_double_inode_lock(src, dst);
3118 ret = extent_same_check_offsets(src, loff, &len, olen);
3119 if (ret)
3120 goto out_unlock;
3122 ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3123 if (ret)
3124 goto out_unlock;
3127 /* don't make the dst file partly checksummed */
3128 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3129 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3130 ret = -EINVAL;
3131 goto out_unlock;
3134 again:
3135 ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3136 if (ret)
3137 goto out_unlock;
3139 if (same_inode)
3140 ret = lock_extent_range(src, same_lock_start, same_lock_len,
3141 false);
3142 else
3143 ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3144 false);
3146 * If one of the inodes has dirty pages in the respective range or
3147 * ordered extents, we need to flush dellaloc and wait for all ordered
3148 * extents in the range. We must unlock the pages and the ranges in the
3149 * io trees to avoid deadlocks when flushing delalloc (requires locking
3150 * pages) and when waiting for ordered extents to complete (they require
3151 * range locking).
3153 if (ret == -EAGAIN) {
3155 * Ranges in the io trees already unlocked. Now unlock all
3156 * pages before waiting for all IO to complete.
3158 btrfs_cmp_data_free(&cmp);
3159 if (same_inode) {
3160 btrfs_wait_ordered_range(src, same_lock_start,
3161 same_lock_len);
3162 } else {
3163 btrfs_wait_ordered_range(src, loff, len);
3164 btrfs_wait_ordered_range(dst, dst_loff, len);
3166 goto again;
3168 ASSERT(ret == 0);
3169 if (WARN_ON(ret)) {
3170 /* ranges in the io trees already unlocked */
3171 btrfs_cmp_data_free(&cmp);
3172 return ret;
3175 /* pass original length for comparison so we stay within i_size */
3176 ret = btrfs_cmp_data(src, loff, dst, dst_loff, olen, &cmp);
3177 if (ret == 0)
3178 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3180 if (same_inode)
3181 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3182 same_lock_start + same_lock_len - 1);
3183 else
3184 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3186 btrfs_cmp_data_free(&cmp);
3187 out_unlock:
3188 if (same_inode)
3189 mutex_unlock(&src->i_mutex);
3190 else
3191 btrfs_double_inode_unlock(src, dst);
3193 return ret;
3196 #define BTRFS_MAX_DEDUPE_LEN (16 * 1024 * 1024)
3198 static long btrfs_ioctl_file_extent_same(struct file *file,
3199 struct btrfs_ioctl_same_args __user *argp)
3201 struct btrfs_ioctl_same_args *same = NULL;
3202 struct btrfs_ioctl_same_extent_info *info;
3203 struct inode *src = file_inode(file);
3204 u64 off;
3205 u64 len;
3206 int i;
3207 int ret;
3208 unsigned long size;
3209 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3210 bool is_admin = capable(CAP_SYS_ADMIN);
3211 u16 count;
3213 if (!(file->f_mode & FMODE_READ))
3214 return -EINVAL;
3216 ret = mnt_want_write_file(file);
3217 if (ret)
3218 return ret;
3220 if (get_user(count, &argp->dest_count)) {
3221 ret = -EFAULT;
3222 goto out;
3225 size = offsetof(struct btrfs_ioctl_same_args __user, info[count]);
3227 same = memdup_user(argp, size);
3229 if (IS_ERR(same)) {
3230 ret = PTR_ERR(same);
3231 same = NULL;
3232 goto out;
3235 off = same->logical_offset;
3236 len = same->length;
3239 * Limit the total length we will dedupe for each operation.
3240 * This is intended to bound the total time spent in this
3241 * ioctl to something sane.
3243 if (len > BTRFS_MAX_DEDUPE_LEN)
3244 len = BTRFS_MAX_DEDUPE_LEN;
3246 if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
3248 * Btrfs does not support blocksize < page_size. As a
3249 * result, btrfs_cmp_data() won't correctly handle
3250 * this situation without an update.
3252 ret = -EINVAL;
3253 goto out;
3256 ret = -EISDIR;
3257 if (S_ISDIR(src->i_mode))
3258 goto out;
3260 ret = -EACCES;
3261 if (!S_ISREG(src->i_mode))
3262 goto out;
3264 /* pre-format output fields to sane values */
3265 for (i = 0; i < count; i++) {
3266 same->info[i].bytes_deduped = 0ULL;
3267 same->info[i].status = 0;
3270 for (i = 0, info = same->info; i < count; i++, info++) {
3271 struct inode *dst;
3272 struct fd dst_file = fdget(info->fd);
3273 if (!dst_file.file) {
3274 info->status = -EBADF;
3275 continue;
3277 dst = file_inode(dst_file.file);
3279 if (!(is_admin || (dst_file.file->f_mode & FMODE_WRITE))) {
3280 info->status = -EINVAL;
3281 } else if (file->f_path.mnt != dst_file.file->f_path.mnt) {
3282 info->status = -EXDEV;
3283 } else if (S_ISDIR(dst->i_mode)) {
3284 info->status = -EISDIR;
3285 } else if (!S_ISREG(dst->i_mode)) {
3286 info->status = -EACCES;
3287 } else {
3288 info->status = btrfs_extent_same(src, off, len, dst,
3289 info->logical_offset);
3290 if (info->status == 0)
3291 info->bytes_deduped += len;
3293 fdput(dst_file);
3296 ret = copy_to_user(argp, same, size);
3297 if (ret)
3298 ret = -EFAULT;
3300 out:
3301 mnt_drop_write_file(file);
3302 kfree(same);
3303 return ret;
3306 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3307 struct inode *inode,
3308 u64 endoff,
3309 const u64 destoff,
3310 const u64 olen,
3311 int no_time_update)
3313 struct btrfs_root *root = BTRFS_I(inode)->root;
3314 int ret;
3316 inode_inc_iversion(inode);
3317 if (!no_time_update)
3318 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3320 * We round up to the block size at eof when determining which
3321 * extents to clone above, but shouldn't round up the file size.
3323 if (endoff > destoff + olen)
3324 endoff = destoff + olen;
3325 if (endoff > inode->i_size)
3326 btrfs_i_size_write(inode, endoff);
3328 ret = btrfs_update_inode(trans, root, inode);
3329 if (ret) {
3330 btrfs_abort_transaction(trans, root, ret);
3331 btrfs_end_transaction(trans, root);
3332 goto out;
3334 ret = btrfs_end_transaction(trans, root);
3335 out:
3336 return ret;
3339 static void clone_update_extent_map(struct inode *inode,
3340 const struct btrfs_trans_handle *trans,
3341 const struct btrfs_path *path,
3342 const u64 hole_offset,
3343 const u64 hole_len)
3345 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3346 struct extent_map *em;
3347 int ret;
3349 em = alloc_extent_map();
3350 if (!em) {
3351 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3352 &BTRFS_I(inode)->runtime_flags);
3353 return;
3356 if (path) {
3357 struct btrfs_file_extent_item *fi;
3359 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3360 struct btrfs_file_extent_item);
3361 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
3362 em->generation = -1;
3363 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3364 BTRFS_FILE_EXTENT_INLINE)
3365 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3366 &BTRFS_I(inode)->runtime_flags);
3367 } else {
3368 em->start = hole_offset;
3369 em->len = hole_len;
3370 em->ram_bytes = em->len;
3371 em->orig_start = hole_offset;
3372 em->block_start = EXTENT_MAP_HOLE;
3373 em->block_len = 0;
3374 em->orig_block_len = 0;
3375 em->compress_type = BTRFS_COMPRESS_NONE;
3376 em->generation = trans->transid;
3379 while (1) {
3380 write_lock(&em_tree->lock);
3381 ret = add_extent_mapping(em_tree, em, 1);
3382 write_unlock(&em_tree->lock);
3383 if (ret != -EEXIST) {
3384 free_extent_map(em);
3385 break;
3387 btrfs_drop_extent_cache(inode, em->start,
3388 em->start + em->len - 1, 0);
3391 if (ret)
3392 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3393 &BTRFS_I(inode)->runtime_flags);
3397 * Make sure we do not end up inserting an inline extent into a file that has
3398 * already other (non-inline) extents. If a file has an inline extent it can
3399 * not have any other extents and the (single) inline extent must start at the
3400 * file offset 0. Failing to respect these rules will lead to file corruption,
3401 * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3403 * We can have extents that have been already written to disk or we can have
3404 * dirty ranges still in delalloc, in which case the extent maps and items are
3405 * created only when we run delalloc, and the delalloc ranges might fall outside
3406 * the range we are currently locking in the inode's io tree. So we check the
3407 * inode's i_size because of that (i_size updates are done while holding the
3408 * i_mutex, which we are holding here).
3409 * We also check to see if the inode has a size not greater than "datal" but has
3410 * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3411 * protected against such concurrent fallocate calls by the i_mutex).
3413 * If the file has no extents but a size greater than datal, do not allow the
3414 * copy because we would need turn the inline extent into a non-inline one (even
3415 * with NO_HOLES enabled). If we find our destination inode only has one inline
3416 * extent, just overwrite it with the source inline extent if its size is less
3417 * than the source extent's size, or we could copy the source inline extent's
3418 * data into the destination inode's inline extent if the later is greater then
3419 * the former.
3421 static int clone_copy_inline_extent(struct inode *src,
3422 struct inode *dst,
3423 struct btrfs_trans_handle *trans,
3424 struct btrfs_path *path,
3425 struct btrfs_key *new_key,
3426 const u64 drop_start,
3427 const u64 datal,
3428 const u64 skip,
3429 const u64 size,
3430 char *inline_data)
3432 struct btrfs_root *root = BTRFS_I(dst)->root;
3433 const u64 aligned_end = ALIGN(new_key->offset + datal,
3434 root->sectorsize);
3435 int ret;
3436 struct btrfs_key key;
3438 if (new_key->offset > 0)
3439 return -EOPNOTSUPP;
3441 key.objectid = btrfs_ino(dst);
3442 key.type = BTRFS_EXTENT_DATA_KEY;
3443 key.offset = 0;
3444 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3445 if (ret < 0) {
3446 return ret;
3447 } else if (ret > 0) {
3448 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3449 ret = btrfs_next_leaf(root, path);
3450 if (ret < 0)
3451 return ret;
3452 else if (ret > 0)
3453 goto copy_inline_extent;
3455 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3456 if (key.objectid == btrfs_ino(dst) &&
3457 key.type == BTRFS_EXTENT_DATA_KEY) {
3458 ASSERT(key.offset > 0);
3459 return -EOPNOTSUPP;
3461 } else if (i_size_read(dst) <= datal) {
3462 struct btrfs_file_extent_item *ei;
3463 u64 ext_len;
3466 * If the file size is <= datal, make sure there are no other
3467 * extents following (can happen do to an fallocate call with
3468 * the flag FALLOC_FL_KEEP_SIZE).
3470 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3471 struct btrfs_file_extent_item);
3473 * If it's an inline extent, it can not have other extents
3474 * following it.
3476 if (btrfs_file_extent_type(path->nodes[0], ei) ==
3477 BTRFS_FILE_EXTENT_INLINE)
3478 goto copy_inline_extent;
3480 ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3481 if (ext_len > aligned_end)
3482 return -EOPNOTSUPP;
3484 ret = btrfs_next_item(root, path);
3485 if (ret < 0) {
3486 return ret;
3487 } else if (ret == 0) {
3488 btrfs_item_key_to_cpu(path->nodes[0], &key,
3489 path->slots[0]);
3490 if (key.objectid == btrfs_ino(dst) &&
3491 key.type == BTRFS_EXTENT_DATA_KEY)
3492 return -EOPNOTSUPP;
3496 copy_inline_extent:
3498 * We have no extent items, or we have an extent at offset 0 which may
3499 * or may not be inlined. All these cases are dealt the same way.
3501 if (i_size_read(dst) > datal) {
3503 * If the destination inode has an inline extent...
3504 * This would require copying the data from the source inline
3505 * extent into the beginning of the destination's inline extent.
3506 * But this is really complex, both extents can be compressed
3507 * or just one of them, which would require decompressing and
3508 * re-compressing data (which could increase the new compressed
3509 * size, not allowing the compressed data to fit anymore in an
3510 * inline extent).
3511 * So just don't support this case for now (it should be rare,
3512 * we are not really saving space when cloning inline extents).
3514 return -EOPNOTSUPP;
3517 btrfs_release_path(path);
3518 ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3519 if (ret)
3520 return ret;
3521 ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3522 if (ret)
3523 return ret;
3525 if (skip) {
3526 const u32 start = btrfs_file_extent_calc_inline_size(0);
3528 memmove(inline_data + start, inline_data + start + skip, datal);
3531 write_extent_buffer(path->nodes[0], inline_data,
3532 btrfs_item_ptr_offset(path->nodes[0],
3533 path->slots[0]),
3534 size);
3535 inode_add_bytes(dst, datal);
3537 return 0;
3541 * btrfs_clone() - clone a range from inode file to another
3543 * @src: Inode to clone from
3544 * @inode: Inode to clone to
3545 * @off: Offset within source to start clone from
3546 * @olen: Original length, passed by user, of range to clone
3547 * @olen_aligned: Block-aligned value of olen
3548 * @destoff: Offset within @inode to start clone
3549 * @no_time_update: Whether to update mtime/ctime on the target inode
3551 static int btrfs_clone(struct inode *src, struct inode *inode,
3552 const u64 off, const u64 olen, const u64 olen_aligned,
3553 const u64 destoff, int no_time_update)
3555 struct btrfs_root *root = BTRFS_I(inode)->root;
3556 struct btrfs_path *path = NULL;
3557 struct extent_buffer *leaf;
3558 struct btrfs_trans_handle *trans;
3559 char *buf = NULL;
3560 struct btrfs_key key;
3561 u32 nritems;
3562 int slot;
3563 int ret;
3564 const u64 len = olen_aligned;
3565 u64 last_dest_end = destoff;
3567 ret = -ENOMEM;
3568 buf = vmalloc(root->nodesize);
3569 if (!buf)
3570 return ret;
3572 path = btrfs_alloc_path();
3573 if (!path) {
3574 vfree(buf);
3575 return ret;
3578 path->reada = 2;
3579 /* clone data */
3580 key.objectid = btrfs_ino(src);
3581 key.type = BTRFS_EXTENT_DATA_KEY;
3582 key.offset = off;
3584 while (1) {
3585 u64 next_key_min_offset = key.offset + 1;
3588 * note the key will change type as we walk through the
3589 * tree.
3591 path->leave_spinning = 1;
3592 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3593 0, 0);
3594 if (ret < 0)
3595 goto out;
3597 * First search, if no extent item that starts at offset off was
3598 * found but the previous item is an extent item, it's possible
3599 * it might overlap our target range, therefore process it.
3601 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3602 btrfs_item_key_to_cpu(path->nodes[0], &key,
3603 path->slots[0] - 1);
3604 if (key.type == BTRFS_EXTENT_DATA_KEY)
3605 path->slots[0]--;
3608 nritems = btrfs_header_nritems(path->nodes[0]);
3609 process_slot:
3610 if (path->slots[0] >= nritems) {
3611 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3612 if (ret < 0)
3613 goto out;
3614 if (ret > 0)
3615 break;
3616 nritems = btrfs_header_nritems(path->nodes[0]);
3618 leaf = path->nodes[0];
3619 slot = path->slots[0];
3621 btrfs_item_key_to_cpu(leaf, &key, slot);
3622 if (key.type > BTRFS_EXTENT_DATA_KEY ||
3623 key.objectid != btrfs_ino(src))
3624 break;
3626 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3627 struct btrfs_file_extent_item *extent;
3628 int type;
3629 u32 size;
3630 struct btrfs_key new_key;
3631 u64 disko = 0, diskl = 0;
3632 u64 datao = 0, datal = 0;
3633 u8 comp;
3634 u64 drop_start;
3636 extent = btrfs_item_ptr(leaf, slot,
3637 struct btrfs_file_extent_item);
3638 comp = btrfs_file_extent_compression(leaf, extent);
3639 type = btrfs_file_extent_type(leaf, extent);
3640 if (type == BTRFS_FILE_EXTENT_REG ||
3641 type == BTRFS_FILE_EXTENT_PREALLOC) {
3642 disko = btrfs_file_extent_disk_bytenr(leaf,
3643 extent);
3644 diskl = btrfs_file_extent_disk_num_bytes(leaf,
3645 extent);
3646 datao = btrfs_file_extent_offset(leaf, extent);
3647 datal = btrfs_file_extent_num_bytes(leaf,
3648 extent);
3649 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3650 /* take upper bound, may be compressed */
3651 datal = btrfs_file_extent_ram_bytes(leaf,
3652 extent);
3656 * The first search might have left us at an extent
3657 * item that ends before our target range's start, can
3658 * happen if we have holes and NO_HOLES feature enabled.
3660 if (key.offset + datal <= off) {
3661 path->slots[0]++;
3662 goto process_slot;
3663 } else if (key.offset >= off + len) {
3664 break;
3666 next_key_min_offset = key.offset + datal;
3667 size = btrfs_item_size_nr(leaf, slot);
3668 read_extent_buffer(leaf, buf,
3669 btrfs_item_ptr_offset(leaf, slot),
3670 size);
3672 btrfs_release_path(path);
3673 path->leave_spinning = 0;
3675 memcpy(&new_key, &key, sizeof(new_key));
3676 new_key.objectid = btrfs_ino(inode);
3677 if (off <= key.offset)
3678 new_key.offset = key.offset + destoff - off;
3679 else
3680 new_key.offset = destoff;
3683 * Deal with a hole that doesn't have an extent item
3684 * that represents it (NO_HOLES feature enabled).
3685 * This hole is either in the middle of the cloning
3686 * range or at the beginning (fully overlaps it or
3687 * partially overlaps it).
3689 if (new_key.offset != last_dest_end)
3690 drop_start = last_dest_end;
3691 else
3692 drop_start = new_key.offset;
3695 * 1 - adjusting old extent (we may have to split it)
3696 * 1 - add new extent
3697 * 1 - inode update
3699 trans = btrfs_start_transaction(root, 3);
3700 if (IS_ERR(trans)) {
3701 ret = PTR_ERR(trans);
3702 goto out;
3705 if (type == BTRFS_FILE_EXTENT_REG ||
3706 type == BTRFS_FILE_EXTENT_PREALLOC) {
3708 * a | --- range to clone ---| b
3709 * | ------------- extent ------------- |
3712 /* subtract range b */
3713 if (key.offset + datal > off + len)
3714 datal = off + len - key.offset;
3716 /* subtract range a */
3717 if (off > key.offset) {
3718 datao += off - key.offset;
3719 datal -= off - key.offset;
3722 ret = btrfs_drop_extents(trans, root, inode,
3723 drop_start,
3724 new_key.offset + datal,
3726 if (ret) {
3727 if (ret != -EOPNOTSUPP)
3728 btrfs_abort_transaction(trans,
3729 root, ret);
3730 btrfs_end_transaction(trans, root);
3731 goto out;
3734 ret = btrfs_insert_empty_item(trans, root, path,
3735 &new_key, size);
3736 if (ret) {
3737 btrfs_abort_transaction(trans, root,
3738 ret);
3739 btrfs_end_transaction(trans, root);
3740 goto out;
3743 leaf = path->nodes[0];
3744 slot = path->slots[0];
3745 write_extent_buffer(leaf, buf,
3746 btrfs_item_ptr_offset(leaf, slot),
3747 size);
3749 extent = btrfs_item_ptr(leaf, slot,
3750 struct btrfs_file_extent_item);
3752 /* disko == 0 means it's a hole */
3753 if (!disko)
3754 datao = 0;
3756 btrfs_set_file_extent_offset(leaf, extent,
3757 datao);
3758 btrfs_set_file_extent_num_bytes(leaf, extent,
3759 datal);
3761 if (disko) {
3762 inode_add_bytes(inode, datal);
3763 ret = btrfs_inc_extent_ref(trans, root,
3764 disko, diskl, 0,
3765 root->root_key.objectid,
3766 btrfs_ino(inode),
3767 new_key.offset - datao);
3768 if (ret) {
3769 btrfs_abort_transaction(trans,
3770 root,
3771 ret);
3772 btrfs_end_transaction(trans,
3773 root);
3774 goto out;
3778 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3779 u64 skip = 0;
3780 u64 trim = 0;
3782 if (off > key.offset) {
3783 skip = off - key.offset;
3784 new_key.offset += skip;
3787 if (key.offset + datal > off + len)
3788 trim = key.offset + datal - (off + len);
3790 if (comp && (skip || trim)) {
3791 ret = -EINVAL;
3792 btrfs_end_transaction(trans, root);
3793 goto out;
3795 size -= skip + trim;
3796 datal -= skip + trim;
3798 ret = clone_copy_inline_extent(src, inode,
3799 trans, path,
3800 &new_key,
3801 drop_start,
3802 datal,
3803 skip, size, buf);
3804 if (ret) {
3805 if (ret != -EOPNOTSUPP)
3806 btrfs_abort_transaction(trans,
3807 root,
3808 ret);
3809 btrfs_end_transaction(trans, root);
3810 goto out;
3812 leaf = path->nodes[0];
3813 slot = path->slots[0];
3816 /* If we have an implicit hole (NO_HOLES feature). */
3817 if (drop_start < new_key.offset)
3818 clone_update_extent_map(inode, trans,
3819 NULL, drop_start,
3820 new_key.offset - drop_start);
3822 clone_update_extent_map(inode, trans, path, 0, 0);
3824 btrfs_mark_buffer_dirty(leaf);
3825 btrfs_release_path(path);
3827 last_dest_end = ALIGN(new_key.offset + datal,
3828 root->sectorsize);
3829 ret = clone_finish_inode_update(trans, inode,
3830 last_dest_end,
3831 destoff, olen,
3832 no_time_update);
3833 if (ret)
3834 goto out;
3835 if (new_key.offset + datal >= destoff + len)
3836 break;
3838 btrfs_release_path(path);
3839 key.offset = next_key_min_offset;
3841 if (fatal_signal_pending(current)) {
3842 ret = -EINTR;
3843 goto out;
3846 ret = 0;
3848 if (last_dest_end < destoff + len) {
3850 * We have an implicit hole (NO_HOLES feature is enabled) that
3851 * fully or partially overlaps our cloning range at its end.
3853 btrfs_release_path(path);
3856 * 1 - remove extent(s)
3857 * 1 - inode update
3859 trans = btrfs_start_transaction(root, 2);
3860 if (IS_ERR(trans)) {
3861 ret = PTR_ERR(trans);
3862 goto out;
3864 ret = btrfs_drop_extents(trans, root, inode,
3865 last_dest_end, destoff + len, 1);
3866 if (ret) {
3867 if (ret != -EOPNOTSUPP)
3868 btrfs_abort_transaction(trans, root, ret);
3869 btrfs_end_transaction(trans, root);
3870 goto out;
3872 clone_update_extent_map(inode, trans, NULL, last_dest_end,
3873 destoff + len - last_dest_end);
3874 ret = clone_finish_inode_update(trans, inode, destoff + len,
3875 destoff, olen, no_time_update);
3878 out:
3879 btrfs_free_path(path);
3880 vfree(buf);
3881 return ret;
3884 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
3885 u64 off, u64 olen, u64 destoff)
3887 struct inode *inode = file_inode(file);
3888 struct btrfs_root *root = BTRFS_I(inode)->root;
3889 struct fd src_file;
3890 struct inode *src;
3891 int ret;
3892 u64 len = olen;
3893 u64 bs = root->fs_info->sb->s_blocksize;
3894 int same_inode = 0;
3897 * TODO:
3898 * - split compressed inline extents. annoying: we need to
3899 * decompress into destination's address_space (the file offset
3900 * may change, so source mapping won't do), then recompress (or
3901 * otherwise reinsert) a subrange.
3903 * - split destination inode's inline extents. The inline extents can
3904 * be either compressed or non-compressed.
3907 /* the destination must be opened for writing */
3908 if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
3909 return -EINVAL;
3911 if (btrfs_root_readonly(root))
3912 return -EROFS;
3914 ret = mnt_want_write_file(file);
3915 if (ret)
3916 return ret;
3918 src_file = fdget(srcfd);
3919 if (!src_file.file) {
3920 ret = -EBADF;
3921 goto out_drop_write;
3924 ret = -EXDEV;
3925 if (src_file.file->f_path.mnt != file->f_path.mnt)
3926 goto out_fput;
3928 src = file_inode(src_file.file);
3930 ret = -EINVAL;
3931 if (src == inode)
3932 same_inode = 1;
3934 /* the src must be open for reading */
3935 if (!(src_file.file->f_mode & FMODE_READ))
3936 goto out_fput;
3938 ret = -EISDIR;
3939 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3940 goto out_fput;
3942 ret = -EXDEV;
3943 if (src->i_sb != inode->i_sb)
3944 goto out_fput;
3946 if (!same_inode) {
3947 btrfs_double_inode_lock(src, inode);
3948 } else {
3949 mutex_lock(&src->i_mutex);
3952 /* don't make the dst file partly checksummed */
3953 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3954 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
3955 ret = -EINVAL;
3956 goto out_unlock;
3959 /* determine range to clone */
3960 ret = -EINVAL;
3961 if (off + len > src->i_size || off + len < off)
3962 goto out_unlock;
3963 if (len == 0)
3964 olen = len = src->i_size - off;
3966 * If we extend to eof, continue to block boundary if and only if the
3967 * destination end offset matches the destination file's size, otherwise
3968 * we would be corrupting data by placing the eof block into the middle
3969 * of a file.
3971 if (off + len == src->i_size) {
3972 if (!IS_ALIGNED(len, bs) && destoff + len < inode->i_size)
3973 goto out_unlock;
3974 len = ALIGN(src->i_size, bs) - off;
3977 if (len == 0) {
3978 ret = 0;
3979 goto out_unlock;
3982 /* verify the end result is block aligned */
3983 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3984 !IS_ALIGNED(destoff, bs))
3985 goto out_unlock;
3987 /* verify if ranges are overlapped within the same file */
3988 if (same_inode) {
3989 if (destoff + len > off && destoff < off + len)
3990 goto out_unlock;
3993 if (destoff > inode->i_size) {
3994 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3995 if (ret)
3996 goto out_unlock;
4000 * Lock the target range too. Right after we replace the file extent
4001 * items in the fs tree (which now point to the cloned data), we might
4002 * have a worker replace them with extent items relative to a write
4003 * operation that was issued before this clone operation (i.e. confront
4004 * with inode.c:btrfs_finish_ordered_io).
4006 if (same_inode) {
4007 u64 lock_start = min_t(u64, off, destoff);
4008 u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
4010 ret = lock_extent_range(src, lock_start, lock_len, true);
4011 } else {
4012 ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
4013 true);
4015 ASSERT(ret == 0);
4016 if (WARN_ON(ret)) {
4017 /* ranges in the io trees already unlocked */
4018 goto out_unlock;
4021 ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
4023 if (same_inode) {
4024 u64 lock_start = min_t(u64, off, destoff);
4025 u64 lock_end = max_t(u64, off, destoff) + len - 1;
4027 unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
4028 } else {
4029 btrfs_double_extent_unlock(src, off, inode, destoff, len);
4032 * Truncate page cache pages so that future reads will see the cloned
4033 * data immediately and not the previous data.
4035 truncate_inode_pages_range(&inode->i_data, destoff,
4036 PAGE_CACHE_ALIGN(destoff + len) - 1);
4037 out_unlock:
4038 if (!same_inode)
4039 btrfs_double_inode_unlock(src, inode);
4040 else
4041 mutex_unlock(&src->i_mutex);
4042 out_fput:
4043 fdput(src_file);
4044 out_drop_write:
4045 mnt_drop_write_file(file);
4046 return ret;
4049 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
4051 struct btrfs_ioctl_clone_range_args args;
4053 if (copy_from_user(&args, argp, sizeof(args)))
4054 return -EFAULT;
4055 return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
4056 args.src_length, args.dest_offset);
4060 * there are many ways the trans_start and trans_end ioctls can lead
4061 * to deadlocks. They should only be used by applications that
4062 * basically own the machine, and have a very in depth understanding
4063 * of all the possible deadlocks and enospc problems.
4065 static long btrfs_ioctl_trans_start(struct file *file)
4067 struct inode *inode = file_inode(file);
4068 struct btrfs_root *root = BTRFS_I(inode)->root;
4069 struct btrfs_trans_handle *trans;
4070 int ret;
4072 ret = -EPERM;
4073 if (!capable(CAP_SYS_ADMIN))
4074 goto out;
4076 ret = -EINPROGRESS;
4077 if (file->private_data)
4078 goto out;
4080 ret = -EROFS;
4081 if (btrfs_root_readonly(root))
4082 goto out;
4084 ret = mnt_want_write_file(file);
4085 if (ret)
4086 goto out;
4088 atomic_inc(&root->fs_info->open_ioctl_trans);
4090 ret = -ENOMEM;
4091 trans = btrfs_start_ioctl_transaction(root);
4092 if (IS_ERR(trans))
4093 goto out_drop;
4095 file->private_data = trans;
4096 return 0;
4098 out_drop:
4099 atomic_dec(&root->fs_info->open_ioctl_trans);
4100 mnt_drop_write_file(file);
4101 out:
4102 return ret;
4105 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
4107 struct inode *inode = file_inode(file);
4108 struct btrfs_root *root = BTRFS_I(inode)->root;
4109 struct btrfs_root *new_root;
4110 struct btrfs_dir_item *di;
4111 struct btrfs_trans_handle *trans;
4112 struct btrfs_path *path;
4113 struct btrfs_key location;
4114 struct btrfs_disk_key disk_key;
4115 u64 objectid = 0;
4116 u64 dir_id;
4117 int ret;
4119 if (!capable(CAP_SYS_ADMIN))
4120 return -EPERM;
4122 ret = mnt_want_write_file(file);
4123 if (ret)
4124 return ret;
4126 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
4127 ret = -EFAULT;
4128 goto out;
4131 if (!objectid)
4132 objectid = BTRFS_FS_TREE_OBJECTID;
4134 location.objectid = objectid;
4135 location.type = BTRFS_ROOT_ITEM_KEY;
4136 location.offset = (u64)-1;
4138 new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
4139 if (IS_ERR(new_root)) {
4140 ret = PTR_ERR(new_root);
4141 goto out;
4143 if (!is_fstree(new_root->objectid)) {
4144 ret = -ENOENT;
4145 goto out;
4148 path = btrfs_alloc_path();
4149 if (!path) {
4150 ret = -ENOMEM;
4151 goto out;
4153 path->leave_spinning = 1;
4155 trans = btrfs_start_transaction(root, 1);
4156 if (IS_ERR(trans)) {
4157 btrfs_free_path(path);
4158 ret = PTR_ERR(trans);
4159 goto out;
4162 dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
4163 di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
4164 dir_id, "default", 7, 1);
4165 if (IS_ERR_OR_NULL(di)) {
4166 btrfs_free_path(path);
4167 btrfs_end_transaction(trans, root);
4168 btrfs_err(new_root->fs_info, "Umm, you don't have the default dir"
4169 "item, this isn't going to work");
4170 ret = -ENOENT;
4171 goto out;
4174 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
4175 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
4176 btrfs_mark_buffer_dirty(path->nodes[0]);
4177 btrfs_free_path(path);
4179 btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
4180 btrfs_end_transaction(trans, root);
4181 out:
4182 mnt_drop_write_file(file);
4183 return ret;
4186 void btrfs_get_block_group_info(struct list_head *groups_list,
4187 struct btrfs_ioctl_space_info *space)
4189 struct btrfs_block_group_cache *block_group;
4191 space->total_bytes = 0;
4192 space->used_bytes = 0;
4193 space->flags = 0;
4194 list_for_each_entry(block_group, groups_list, list) {
4195 space->flags = block_group->flags;
4196 space->total_bytes += block_group->key.offset;
4197 space->used_bytes +=
4198 btrfs_block_group_used(&block_group->item);
4202 static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
4204 struct btrfs_ioctl_space_args space_args;
4205 struct btrfs_ioctl_space_info space;
4206 struct btrfs_ioctl_space_info *dest;
4207 struct btrfs_ioctl_space_info *dest_orig;
4208 struct btrfs_ioctl_space_info __user *user_dest;
4209 struct btrfs_space_info *info;
4210 u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
4211 BTRFS_BLOCK_GROUP_SYSTEM,
4212 BTRFS_BLOCK_GROUP_METADATA,
4213 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
4214 int num_types = 4;
4215 int alloc_size;
4216 int ret = 0;
4217 u64 slot_count = 0;
4218 int i, c;
4220 if (copy_from_user(&space_args,
4221 (struct btrfs_ioctl_space_args __user *)arg,
4222 sizeof(space_args)))
4223 return -EFAULT;
4225 for (i = 0; i < num_types; i++) {
4226 struct btrfs_space_info *tmp;
4228 info = NULL;
4229 rcu_read_lock();
4230 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4231 list) {
4232 if (tmp->flags == types[i]) {
4233 info = tmp;
4234 break;
4237 rcu_read_unlock();
4239 if (!info)
4240 continue;
4242 down_read(&info->groups_sem);
4243 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4244 if (!list_empty(&info->block_groups[c]))
4245 slot_count++;
4247 up_read(&info->groups_sem);
4251 * Global block reserve, exported as a space_info
4253 slot_count++;
4255 /* space_slots == 0 means they are asking for a count */
4256 if (space_args.space_slots == 0) {
4257 space_args.total_spaces = slot_count;
4258 goto out;
4261 slot_count = min_t(u64, space_args.space_slots, slot_count);
4263 alloc_size = sizeof(*dest) * slot_count;
4265 /* we generally have at most 6 or so space infos, one for each raid
4266 * level. So, a whole page should be more than enough for everyone
4268 if (alloc_size > PAGE_CACHE_SIZE)
4269 return -ENOMEM;
4271 space_args.total_spaces = 0;
4272 dest = kmalloc(alloc_size, GFP_NOFS);
4273 if (!dest)
4274 return -ENOMEM;
4275 dest_orig = dest;
4277 /* now we have a buffer to copy into */
4278 for (i = 0; i < num_types; i++) {
4279 struct btrfs_space_info *tmp;
4281 if (!slot_count)
4282 break;
4284 info = NULL;
4285 rcu_read_lock();
4286 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4287 list) {
4288 if (tmp->flags == types[i]) {
4289 info = tmp;
4290 break;
4293 rcu_read_unlock();
4295 if (!info)
4296 continue;
4297 down_read(&info->groups_sem);
4298 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4299 if (!list_empty(&info->block_groups[c])) {
4300 btrfs_get_block_group_info(
4301 &info->block_groups[c], &space);
4302 memcpy(dest, &space, sizeof(space));
4303 dest++;
4304 space_args.total_spaces++;
4305 slot_count--;
4307 if (!slot_count)
4308 break;
4310 up_read(&info->groups_sem);
4314 * Add global block reserve
4316 if (slot_count) {
4317 struct btrfs_block_rsv *block_rsv = &root->fs_info->global_block_rsv;
4319 spin_lock(&block_rsv->lock);
4320 space.total_bytes = block_rsv->size;
4321 space.used_bytes = block_rsv->size - block_rsv->reserved;
4322 spin_unlock(&block_rsv->lock);
4323 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4324 memcpy(dest, &space, sizeof(space));
4325 space_args.total_spaces++;
4328 user_dest = (struct btrfs_ioctl_space_info __user *)
4329 (arg + sizeof(struct btrfs_ioctl_space_args));
4331 if (copy_to_user(user_dest, dest_orig, alloc_size))
4332 ret = -EFAULT;
4334 kfree(dest_orig);
4335 out:
4336 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
4337 ret = -EFAULT;
4339 return ret;
4343 * there are many ways the trans_start and trans_end ioctls can lead
4344 * to deadlocks. They should only be used by applications that
4345 * basically own the machine, and have a very in depth understanding
4346 * of all the possible deadlocks and enospc problems.
4348 long btrfs_ioctl_trans_end(struct file *file)
4350 struct inode *inode = file_inode(file);
4351 struct btrfs_root *root = BTRFS_I(inode)->root;
4352 struct btrfs_trans_handle *trans;
4354 trans = file->private_data;
4355 if (!trans)
4356 return -EINVAL;
4357 file->private_data = NULL;
4359 btrfs_end_transaction(trans, root);
4361 atomic_dec(&root->fs_info->open_ioctl_trans);
4363 mnt_drop_write_file(file);
4364 return 0;
4367 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4368 void __user *argp)
4370 struct btrfs_trans_handle *trans;
4371 u64 transid;
4372 int ret;
4374 trans = btrfs_attach_transaction_barrier(root);
4375 if (IS_ERR(trans)) {
4376 if (PTR_ERR(trans) != -ENOENT)
4377 return PTR_ERR(trans);
4379 /* No running transaction, don't bother */
4380 transid = root->fs_info->last_trans_committed;
4381 goto out;
4383 transid = trans->transid;
4384 ret = btrfs_commit_transaction_async(trans, root, 0);
4385 if (ret) {
4386 btrfs_end_transaction(trans, root);
4387 return ret;
4389 out:
4390 if (argp)
4391 if (copy_to_user(argp, &transid, sizeof(transid)))
4392 return -EFAULT;
4393 return 0;
4396 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
4397 void __user *argp)
4399 u64 transid;
4401 if (argp) {
4402 if (copy_from_user(&transid, argp, sizeof(transid)))
4403 return -EFAULT;
4404 } else {
4405 transid = 0; /* current trans */
4407 return btrfs_wait_for_commit(root, transid);
4410 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4412 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4413 struct btrfs_ioctl_scrub_args *sa;
4414 int ret;
4416 if (!capable(CAP_SYS_ADMIN))
4417 return -EPERM;
4419 sa = memdup_user(arg, sizeof(*sa));
4420 if (IS_ERR(sa))
4421 return PTR_ERR(sa);
4423 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4424 ret = mnt_want_write_file(file);
4425 if (ret)
4426 goto out;
4429 ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
4430 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4433 if (copy_to_user(arg, sa, sizeof(*sa)))
4434 ret = -EFAULT;
4436 if (!(sa->flags & BTRFS_SCRUB_READONLY))
4437 mnt_drop_write_file(file);
4438 out:
4439 kfree(sa);
4440 return ret;
4443 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
4445 if (!capable(CAP_SYS_ADMIN))
4446 return -EPERM;
4448 return btrfs_scrub_cancel(root->fs_info);
4451 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
4452 void __user *arg)
4454 struct btrfs_ioctl_scrub_args *sa;
4455 int ret;
4457 if (!capable(CAP_SYS_ADMIN))
4458 return -EPERM;
4460 sa = memdup_user(arg, sizeof(*sa));
4461 if (IS_ERR(sa))
4462 return PTR_ERR(sa);
4464 ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
4466 if (copy_to_user(arg, sa, sizeof(*sa)))
4467 ret = -EFAULT;
4469 kfree(sa);
4470 return ret;
4473 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
4474 void __user *arg)
4476 struct btrfs_ioctl_get_dev_stats *sa;
4477 int ret;
4479 sa = memdup_user(arg, sizeof(*sa));
4480 if (IS_ERR(sa))
4481 return PTR_ERR(sa);
4483 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4484 kfree(sa);
4485 return -EPERM;
4488 ret = btrfs_get_dev_stats(root, sa);
4490 if (copy_to_user(arg, sa, sizeof(*sa)))
4491 ret = -EFAULT;
4493 kfree(sa);
4494 return ret;
4497 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
4499 struct btrfs_ioctl_dev_replace_args *p;
4500 int ret;
4502 if (!capable(CAP_SYS_ADMIN))
4503 return -EPERM;
4505 p = memdup_user(arg, sizeof(*p));
4506 if (IS_ERR(p))
4507 return PTR_ERR(p);
4509 switch (p->cmd) {
4510 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4511 if (root->fs_info->sb->s_flags & MS_RDONLY) {
4512 ret = -EROFS;
4513 goto out;
4515 if (atomic_xchg(
4516 &root->fs_info->mutually_exclusive_operation_running,
4517 1)) {
4518 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4519 } else {
4520 ret = btrfs_dev_replace_start(root, p);
4521 atomic_set(
4522 &root->fs_info->mutually_exclusive_operation_running,
4525 break;
4526 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4527 btrfs_dev_replace_status(root->fs_info, p);
4528 ret = 0;
4529 break;
4530 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4531 ret = btrfs_dev_replace_cancel(root->fs_info, p);
4532 break;
4533 default:
4534 ret = -EINVAL;
4535 break;
4538 if (copy_to_user(arg, p, sizeof(*p)))
4539 ret = -EFAULT;
4540 out:
4541 kfree(p);
4542 return ret;
4545 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4547 int ret = 0;
4548 int i;
4549 u64 rel_ptr;
4550 int size;
4551 struct btrfs_ioctl_ino_path_args *ipa = NULL;
4552 struct inode_fs_paths *ipath = NULL;
4553 struct btrfs_path *path;
4555 if (!capable(CAP_DAC_READ_SEARCH))
4556 return -EPERM;
4558 path = btrfs_alloc_path();
4559 if (!path) {
4560 ret = -ENOMEM;
4561 goto out;
4564 ipa = memdup_user(arg, sizeof(*ipa));
4565 if (IS_ERR(ipa)) {
4566 ret = PTR_ERR(ipa);
4567 ipa = NULL;
4568 goto out;
4571 size = min_t(u32, ipa->size, 4096);
4572 ipath = init_ipath(size, root, path);
4573 if (IS_ERR(ipath)) {
4574 ret = PTR_ERR(ipath);
4575 ipath = NULL;
4576 goto out;
4579 ret = paths_from_inode(ipa->inum, ipath);
4580 if (ret < 0)
4581 goto out;
4583 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4584 rel_ptr = ipath->fspath->val[i] -
4585 (u64)(unsigned long)ipath->fspath->val;
4586 ipath->fspath->val[i] = rel_ptr;
4589 ret = copy_to_user((void *)(unsigned long)ipa->fspath,
4590 (void *)(unsigned long)ipath->fspath, size);
4591 if (ret) {
4592 ret = -EFAULT;
4593 goto out;
4596 out:
4597 btrfs_free_path(path);
4598 free_ipath(ipath);
4599 kfree(ipa);
4601 return ret;
4604 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4606 struct btrfs_data_container *inodes = ctx;
4607 const size_t c = 3 * sizeof(u64);
4609 if (inodes->bytes_left >= c) {
4610 inodes->bytes_left -= c;
4611 inodes->val[inodes->elem_cnt] = inum;
4612 inodes->val[inodes->elem_cnt + 1] = offset;
4613 inodes->val[inodes->elem_cnt + 2] = root;
4614 inodes->elem_cnt += 3;
4615 } else {
4616 inodes->bytes_missing += c - inodes->bytes_left;
4617 inodes->bytes_left = 0;
4618 inodes->elem_missed += 3;
4621 return 0;
4624 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
4625 void __user *arg)
4627 int ret = 0;
4628 int size;
4629 struct btrfs_ioctl_logical_ino_args *loi;
4630 struct btrfs_data_container *inodes = NULL;
4631 struct btrfs_path *path = NULL;
4633 if (!capable(CAP_SYS_ADMIN))
4634 return -EPERM;
4636 loi = memdup_user(arg, sizeof(*loi));
4637 if (IS_ERR(loi)) {
4638 ret = PTR_ERR(loi);
4639 loi = NULL;
4640 goto out;
4643 path = btrfs_alloc_path();
4644 if (!path) {
4645 ret = -ENOMEM;
4646 goto out;
4649 size = min_t(u32, loi->size, 64 * 1024);
4650 inodes = init_data_container(size);
4651 if (IS_ERR(inodes)) {
4652 ret = PTR_ERR(inodes);
4653 inodes = NULL;
4654 goto out;
4657 ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
4658 build_ino_list, inodes);
4659 if (ret == -EINVAL)
4660 ret = -ENOENT;
4661 if (ret < 0)
4662 goto out;
4664 ret = copy_to_user((void *)(unsigned long)loi->inodes,
4665 (void *)(unsigned long)inodes, size);
4666 if (ret)
4667 ret = -EFAULT;
4669 out:
4670 btrfs_free_path(path);
4671 vfree(inodes);
4672 kfree(loi);
4674 return ret;
4677 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4678 struct btrfs_ioctl_balance_args *bargs)
4680 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4682 bargs->flags = bctl->flags;
4684 if (atomic_read(&fs_info->balance_running))
4685 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4686 if (atomic_read(&fs_info->balance_pause_req))
4687 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4688 if (atomic_read(&fs_info->balance_cancel_req))
4689 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4691 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4692 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4693 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4695 if (lock) {
4696 spin_lock(&fs_info->balance_lock);
4697 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4698 spin_unlock(&fs_info->balance_lock);
4699 } else {
4700 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4704 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4706 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4707 struct btrfs_fs_info *fs_info = root->fs_info;
4708 struct btrfs_ioctl_balance_args *bargs;
4709 struct btrfs_balance_control *bctl;
4710 bool need_unlock; /* for mut. excl. ops lock */
4711 int ret;
4713 if (!capable(CAP_SYS_ADMIN))
4714 return -EPERM;
4716 ret = mnt_want_write_file(file);
4717 if (ret)
4718 return ret;
4720 again:
4721 if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
4722 mutex_lock(&fs_info->volume_mutex);
4723 mutex_lock(&fs_info->balance_mutex);
4724 need_unlock = true;
4725 goto locked;
4729 * mut. excl. ops lock is locked. Three possibilites:
4730 * (1) some other op is running
4731 * (2) balance is running
4732 * (3) balance is paused -- special case (think resume)
4734 mutex_lock(&fs_info->balance_mutex);
4735 if (fs_info->balance_ctl) {
4736 /* this is either (2) or (3) */
4737 if (!atomic_read(&fs_info->balance_running)) {
4738 mutex_unlock(&fs_info->balance_mutex);
4739 if (!mutex_trylock(&fs_info->volume_mutex))
4740 goto again;
4741 mutex_lock(&fs_info->balance_mutex);
4743 if (fs_info->balance_ctl &&
4744 !atomic_read(&fs_info->balance_running)) {
4745 /* this is (3) */
4746 need_unlock = false;
4747 goto locked;
4750 mutex_unlock(&fs_info->balance_mutex);
4751 mutex_unlock(&fs_info->volume_mutex);
4752 goto again;
4753 } else {
4754 /* this is (2) */
4755 mutex_unlock(&fs_info->balance_mutex);
4756 ret = -EINPROGRESS;
4757 goto out;
4759 } else {
4760 /* this is (1) */
4761 mutex_unlock(&fs_info->balance_mutex);
4762 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4763 goto out;
4766 locked:
4767 BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
4769 if (arg) {
4770 bargs = memdup_user(arg, sizeof(*bargs));
4771 if (IS_ERR(bargs)) {
4772 ret = PTR_ERR(bargs);
4773 goto out_unlock;
4776 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4777 if (!fs_info->balance_ctl) {
4778 ret = -ENOTCONN;
4779 goto out_bargs;
4782 bctl = fs_info->balance_ctl;
4783 spin_lock(&fs_info->balance_lock);
4784 bctl->flags |= BTRFS_BALANCE_RESUME;
4785 spin_unlock(&fs_info->balance_lock);
4787 goto do_balance;
4789 } else {
4790 bargs = NULL;
4793 if (fs_info->balance_ctl) {
4794 ret = -EINPROGRESS;
4795 goto out_bargs;
4798 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4799 if (!bctl) {
4800 ret = -ENOMEM;
4801 goto out_bargs;
4804 bctl->fs_info = fs_info;
4805 if (arg) {
4806 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4807 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4808 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4810 bctl->flags = bargs->flags;
4811 } else {
4812 /* balance everything - no filters */
4813 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4816 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4817 ret = -EINVAL;
4818 goto out_bctl;
4821 do_balance:
4823 * Ownership of bctl and mutually_exclusive_operation_running
4824 * goes to to btrfs_balance. bctl is freed in __cancel_balance,
4825 * or, if restriper was paused all the way until unmount, in
4826 * free_fs_info. mutually_exclusive_operation_running is
4827 * cleared in __cancel_balance.
4829 need_unlock = false;
4831 ret = btrfs_balance(bctl, bargs);
4832 bctl = NULL;
4834 if (arg) {
4835 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4836 ret = -EFAULT;
4839 out_bctl:
4840 kfree(bctl);
4841 out_bargs:
4842 kfree(bargs);
4843 out_unlock:
4844 mutex_unlock(&fs_info->balance_mutex);
4845 mutex_unlock(&fs_info->volume_mutex);
4846 if (need_unlock)
4847 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4848 out:
4849 mnt_drop_write_file(file);
4850 return ret;
4853 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4855 if (!capable(CAP_SYS_ADMIN))
4856 return -EPERM;
4858 switch (cmd) {
4859 case BTRFS_BALANCE_CTL_PAUSE:
4860 return btrfs_pause_balance(root->fs_info);
4861 case BTRFS_BALANCE_CTL_CANCEL:
4862 return btrfs_cancel_balance(root->fs_info);
4865 return -EINVAL;
4868 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
4869 void __user *arg)
4871 struct btrfs_fs_info *fs_info = root->fs_info;
4872 struct btrfs_ioctl_balance_args *bargs;
4873 int ret = 0;
4875 if (!capable(CAP_SYS_ADMIN))
4876 return -EPERM;
4878 mutex_lock(&fs_info->balance_mutex);
4879 if (!fs_info->balance_ctl) {
4880 ret = -ENOTCONN;
4881 goto out;
4884 bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
4885 if (!bargs) {
4886 ret = -ENOMEM;
4887 goto out;
4890 update_ioctl_balance_args(fs_info, 1, bargs);
4892 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4893 ret = -EFAULT;
4895 kfree(bargs);
4896 out:
4897 mutex_unlock(&fs_info->balance_mutex);
4898 return ret;
4901 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4903 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4904 struct btrfs_ioctl_quota_ctl_args *sa;
4905 struct btrfs_trans_handle *trans = NULL;
4906 int ret;
4907 int err;
4909 if (!capable(CAP_SYS_ADMIN))
4910 return -EPERM;
4912 ret = mnt_want_write_file(file);
4913 if (ret)
4914 return ret;
4916 sa = memdup_user(arg, sizeof(*sa));
4917 if (IS_ERR(sa)) {
4918 ret = PTR_ERR(sa);
4919 goto drop_write;
4922 down_write(&root->fs_info->subvol_sem);
4923 trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
4924 if (IS_ERR(trans)) {
4925 ret = PTR_ERR(trans);
4926 goto out;
4929 switch (sa->cmd) {
4930 case BTRFS_QUOTA_CTL_ENABLE:
4931 ret = btrfs_quota_enable(trans, root->fs_info);
4932 break;
4933 case BTRFS_QUOTA_CTL_DISABLE:
4934 ret = btrfs_quota_disable(trans, root->fs_info);
4935 break;
4936 default:
4937 ret = -EINVAL;
4938 break;
4941 err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
4942 if (err && !ret)
4943 ret = err;
4944 out:
4945 kfree(sa);
4946 up_write(&root->fs_info->subvol_sem);
4947 drop_write:
4948 mnt_drop_write_file(file);
4949 return ret;
4952 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4954 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4955 struct btrfs_ioctl_qgroup_assign_args *sa;
4956 struct btrfs_trans_handle *trans;
4957 int ret;
4958 int err;
4960 if (!capable(CAP_SYS_ADMIN))
4961 return -EPERM;
4963 ret = mnt_want_write_file(file);
4964 if (ret)
4965 return ret;
4967 sa = memdup_user(arg, sizeof(*sa));
4968 if (IS_ERR(sa)) {
4969 ret = PTR_ERR(sa);
4970 goto drop_write;
4973 trans = btrfs_join_transaction(root);
4974 if (IS_ERR(trans)) {
4975 ret = PTR_ERR(trans);
4976 goto out;
4979 /* FIXME: check if the IDs really exist */
4980 if (sa->assign) {
4981 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
4982 sa->src, sa->dst);
4983 } else {
4984 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
4985 sa->src, sa->dst);
4988 /* update qgroup status and info */
4989 err = btrfs_run_qgroups(trans, root->fs_info);
4990 if (err < 0)
4991 btrfs_std_error(root->fs_info, ret,
4992 "failed to update qgroup status and info\n");
4993 err = btrfs_end_transaction(trans, root);
4994 if (err && !ret)
4995 ret = err;
4997 out:
4998 kfree(sa);
4999 drop_write:
5000 mnt_drop_write_file(file);
5001 return ret;
5004 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
5006 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5007 struct btrfs_ioctl_qgroup_create_args *sa;
5008 struct btrfs_trans_handle *trans;
5009 int ret;
5010 int err;
5012 if (!capable(CAP_SYS_ADMIN))
5013 return -EPERM;
5015 ret = mnt_want_write_file(file);
5016 if (ret)
5017 return ret;
5019 sa = memdup_user(arg, sizeof(*sa));
5020 if (IS_ERR(sa)) {
5021 ret = PTR_ERR(sa);
5022 goto drop_write;
5025 if (!sa->qgroupid) {
5026 ret = -EINVAL;
5027 goto out;
5030 trans = btrfs_join_transaction(root);
5031 if (IS_ERR(trans)) {
5032 ret = PTR_ERR(trans);
5033 goto out;
5036 /* FIXME: check if the IDs really exist */
5037 if (sa->create) {
5038 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid);
5039 } else {
5040 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
5043 err = btrfs_end_transaction(trans, root);
5044 if (err && !ret)
5045 ret = err;
5047 out:
5048 kfree(sa);
5049 drop_write:
5050 mnt_drop_write_file(file);
5051 return ret;
5054 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
5056 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5057 struct btrfs_ioctl_qgroup_limit_args *sa;
5058 struct btrfs_trans_handle *trans;
5059 int ret;
5060 int err;
5061 u64 qgroupid;
5063 if (!capable(CAP_SYS_ADMIN))
5064 return -EPERM;
5066 ret = mnt_want_write_file(file);
5067 if (ret)
5068 return ret;
5070 sa = memdup_user(arg, sizeof(*sa));
5071 if (IS_ERR(sa)) {
5072 ret = PTR_ERR(sa);
5073 goto drop_write;
5076 trans = btrfs_join_transaction(root);
5077 if (IS_ERR(trans)) {
5078 ret = PTR_ERR(trans);
5079 goto out;
5082 qgroupid = sa->qgroupid;
5083 if (!qgroupid) {
5084 /* take the current subvol as qgroup */
5085 qgroupid = root->root_key.objectid;
5088 /* FIXME: check if the IDs really exist */
5089 ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
5091 err = btrfs_end_transaction(trans, root);
5092 if (err && !ret)
5093 ret = err;
5095 out:
5096 kfree(sa);
5097 drop_write:
5098 mnt_drop_write_file(file);
5099 return ret;
5102 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
5104 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5105 struct btrfs_ioctl_quota_rescan_args *qsa;
5106 int ret;
5108 if (!capable(CAP_SYS_ADMIN))
5109 return -EPERM;
5111 ret = mnt_want_write_file(file);
5112 if (ret)
5113 return ret;
5115 qsa = memdup_user(arg, sizeof(*qsa));
5116 if (IS_ERR(qsa)) {
5117 ret = PTR_ERR(qsa);
5118 goto drop_write;
5121 if (qsa->flags) {
5122 ret = -EINVAL;
5123 goto out;
5126 ret = btrfs_qgroup_rescan(root->fs_info);
5128 out:
5129 kfree(qsa);
5130 drop_write:
5131 mnt_drop_write_file(file);
5132 return ret;
5135 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
5137 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5138 struct btrfs_ioctl_quota_rescan_args *qsa;
5139 int ret = 0;
5141 if (!capable(CAP_SYS_ADMIN))
5142 return -EPERM;
5144 qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
5145 if (!qsa)
5146 return -ENOMEM;
5148 if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
5149 qsa->flags = 1;
5150 qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
5153 if (copy_to_user(arg, qsa, sizeof(*qsa)))
5154 ret = -EFAULT;
5156 kfree(qsa);
5157 return ret;
5160 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
5162 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5164 if (!capable(CAP_SYS_ADMIN))
5165 return -EPERM;
5167 return btrfs_qgroup_wait_for_completion(root->fs_info, true);
5170 static long _btrfs_ioctl_set_received_subvol(struct file *file,
5171 struct btrfs_ioctl_received_subvol_args *sa)
5173 struct inode *inode = file_inode(file);
5174 struct btrfs_root *root = BTRFS_I(inode)->root;
5175 struct btrfs_root_item *root_item = &root->root_item;
5176 struct btrfs_trans_handle *trans;
5177 struct timespec ct = CURRENT_TIME;
5178 int ret = 0;
5179 int received_uuid_changed;
5181 if (!inode_owner_or_capable(inode))
5182 return -EPERM;
5184 ret = mnt_want_write_file(file);
5185 if (ret < 0)
5186 return ret;
5188 down_write(&root->fs_info->subvol_sem);
5190 if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
5191 ret = -EINVAL;
5192 goto out;
5195 if (btrfs_root_readonly(root)) {
5196 ret = -EROFS;
5197 goto out;
5201 * 1 - root item
5202 * 2 - uuid items (received uuid + subvol uuid)
5204 trans = btrfs_start_transaction(root, 3);
5205 if (IS_ERR(trans)) {
5206 ret = PTR_ERR(trans);
5207 trans = NULL;
5208 goto out;
5211 sa->rtransid = trans->transid;
5212 sa->rtime.sec = ct.tv_sec;
5213 sa->rtime.nsec = ct.tv_nsec;
5215 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5216 BTRFS_UUID_SIZE);
5217 if (received_uuid_changed &&
5218 !btrfs_is_empty_uuid(root_item->received_uuid))
5219 btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
5220 root_item->received_uuid,
5221 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5222 root->root_key.objectid);
5223 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5224 btrfs_set_root_stransid(root_item, sa->stransid);
5225 btrfs_set_root_rtransid(root_item, sa->rtransid);
5226 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5227 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5228 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5229 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
5231 ret = btrfs_update_root(trans, root->fs_info->tree_root,
5232 &root->root_key, &root->root_item);
5233 if (ret < 0) {
5234 btrfs_end_transaction(trans, root);
5235 goto out;
5237 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5238 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
5239 sa->uuid,
5240 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5241 root->root_key.objectid);
5242 if (ret < 0 && ret != -EEXIST) {
5243 btrfs_abort_transaction(trans, root, ret);
5244 goto out;
5247 ret = btrfs_commit_transaction(trans, root);
5248 if (ret < 0) {
5249 btrfs_abort_transaction(trans, root, ret);
5250 goto out;
5253 out:
5254 up_write(&root->fs_info->subvol_sem);
5255 mnt_drop_write_file(file);
5256 return ret;
5259 #ifdef CONFIG_64BIT
5260 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5261 void __user *arg)
5263 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5264 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5265 int ret = 0;
5267 args32 = memdup_user(arg, sizeof(*args32));
5268 if (IS_ERR(args32)) {
5269 ret = PTR_ERR(args32);
5270 args32 = NULL;
5271 goto out;
5274 args64 = kmalloc(sizeof(*args64), GFP_NOFS);
5275 if (!args64) {
5276 ret = -ENOMEM;
5277 goto out;
5280 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5281 args64->stransid = args32->stransid;
5282 args64->rtransid = args32->rtransid;
5283 args64->stime.sec = args32->stime.sec;
5284 args64->stime.nsec = args32->stime.nsec;
5285 args64->rtime.sec = args32->rtime.sec;
5286 args64->rtime.nsec = args32->rtime.nsec;
5287 args64->flags = args32->flags;
5289 ret = _btrfs_ioctl_set_received_subvol(file, args64);
5290 if (ret)
5291 goto out;
5293 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5294 args32->stransid = args64->stransid;
5295 args32->rtransid = args64->rtransid;
5296 args32->stime.sec = args64->stime.sec;
5297 args32->stime.nsec = args64->stime.nsec;
5298 args32->rtime.sec = args64->rtime.sec;
5299 args32->rtime.nsec = args64->rtime.nsec;
5300 args32->flags = args64->flags;
5302 ret = copy_to_user(arg, args32, sizeof(*args32));
5303 if (ret)
5304 ret = -EFAULT;
5306 out:
5307 kfree(args32);
5308 kfree(args64);
5309 return ret;
5311 #endif
5313 static long btrfs_ioctl_set_received_subvol(struct file *file,
5314 void __user *arg)
5316 struct btrfs_ioctl_received_subvol_args *sa = NULL;
5317 int ret = 0;
5319 sa = memdup_user(arg, sizeof(*sa));
5320 if (IS_ERR(sa)) {
5321 ret = PTR_ERR(sa);
5322 sa = NULL;
5323 goto out;
5326 ret = _btrfs_ioctl_set_received_subvol(file, sa);
5328 if (ret)
5329 goto out;
5331 ret = copy_to_user(arg, sa, sizeof(*sa));
5332 if (ret)
5333 ret = -EFAULT;
5335 out:
5336 kfree(sa);
5337 return ret;
5340 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5342 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5343 size_t len;
5344 int ret;
5345 char label[BTRFS_LABEL_SIZE];
5347 spin_lock(&root->fs_info->super_lock);
5348 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5349 spin_unlock(&root->fs_info->super_lock);
5351 len = strnlen(label, BTRFS_LABEL_SIZE);
5353 if (len == BTRFS_LABEL_SIZE) {
5354 btrfs_warn(root->fs_info,
5355 "label is too long, return the first %zu bytes", --len);
5358 ret = copy_to_user(arg, label, len);
5360 return ret ? -EFAULT : 0;
5363 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5365 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5366 struct btrfs_super_block *super_block = root->fs_info->super_copy;
5367 struct btrfs_trans_handle *trans;
5368 char label[BTRFS_LABEL_SIZE];
5369 int ret;
5371 if (!capable(CAP_SYS_ADMIN))
5372 return -EPERM;
5374 if (copy_from_user(label, arg, sizeof(label)))
5375 return -EFAULT;
5377 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5378 btrfs_err(root->fs_info, "unable to set label with more than %d bytes",
5379 BTRFS_LABEL_SIZE - 1);
5380 return -EINVAL;
5383 ret = mnt_want_write_file(file);
5384 if (ret)
5385 return ret;
5387 trans = btrfs_start_transaction(root, 0);
5388 if (IS_ERR(trans)) {
5389 ret = PTR_ERR(trans);
5390 goto out_unlock;
5393 spin_lock(&root->fs_info->super_lock);
5394 strcpy(super_block->label, label);
5395 spin_unlock(&root->fs_info->super_lock);
5396 ret = btrfs_commit_transaction(trans, root);
5398 out_unlock:
5399 mnt_drop_write_file(file);
5400 return ret;
5403 #define INIT_FEATURE_FLAGS(suffix) \
5404 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5405 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5406 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5408 static int btrfs_ioctl_get_supported_features(struct file *file,
5409 void __user *arg)
5411 static struct btrfs_ioctl_feature_flags features[3] = {
5412 INIT_FEATURE_FLAGS(SUPP),
5413 INIT_FEATURE_FLAGS(SAFE_SET),
5414 INIT_FEATURE_FLAGS(SAFE_CLEAR)
5417 if (copy_to_user(arg, &features, sizeof(features)))
5418 return -EFAULT;
5420 return 0;
5423 static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
5425 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5426 struct btrfs_super_block *super_block = root->fs_info->super_copy;
5427 struct btrfs_ioctl_feature_flags features;
5429 features.compat_flags = btrfs_super_compat_flags(super_block);
5430 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5431 features.incompat_flags = btrfs_super_incompat_flags(super_block);
5433 if (copy_to_user(arg, &features, sizeof(features)))
5434 return -EFAULT;
5436 return 0;
5439 static int check_feature_bits(struct btrfs_root *root,
5440 enum btrfs_feature_set set,
5441 u64 change_mask, u64 flags, u64 supported_flags,
5442 u64 safe_set, u64 safe_clear)
5444 const char *type = btrfs_feature_set_names[set];
5445 char *names;
5446 u64 disallowed, unsupported;
5447 u64 set_mask = flags & change_mask;
5448 u64 clear_mask = ~flags & change_mask;
5450 unsupported = set_mask & ~supported_flags;
5451 if (unsupported) {
5452 names = btrfs_printable_features(set, unsupported);
5453 if (names) {
5454 btrfs_warn(root->fs_info,
5455 "this kernel does not support the %s feature bit%s",
5456 names, strchr(names, ',') ? "s" : "");
5457 kfree(names);
5458 } else
5459 btrfs_warn(root->fs_info,
5460 "this kernel does not support %s bits 0x%llx",
5461 type, unsupported);
5462 return -EOPNOTSUPP;
5465 disallowed = set_mask & ~safe_set;
5466 if (disallowed) {
5467 names = btrfs_printable_features(set, disallowed);
5468 if (names) {
5469 btrfs_warn(root->fs_info,
5470 "can't set the %s feature bit%s while mounted",
5471 names, strchr(names, ',') ? "s" : "");
5472 kfree(names);
5473 } else
5474 btrfs_warn(root->fs_info,
5475 "can't set %s bits 0x%llx while mounted",
5476 type, disallowed);
5477 return -EPERM;
5480 disallowed = clear_mask & ~safe_clear;
5481 if (disallowed) {
5482 names = btrfs_printable_features(set, disallowed);
5483 if (names) {
5484 btrfs_warn(root->fs_info,
5485 "can't clear the %s feature bit%s while mounted",
5486 names, strchr(names, ',') ? "s" : "");
5487 kfree(names);
5488 } else
5489 btrfs_warn(root->fs_info,
5490 "can't clear %s bits 0x%llx while mounted",
5491 type, disallowed);
5492 return -EPERM;
5495 return 0;
5498 #define check_feature(root, change_mask, flags, mask_base) \
5499 check_feature_bits(root, FEAT_##mask_base, change_mask, flags, \
5500 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
5501 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
5502 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5504 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5506 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5507 struct btrfs_super_block *super_block = root->fs_info->super_copy;
5508 struct btrfs_ioctl_feature_flags flags[2];
5509 struct btrfs_trans_handle *trans;
5510 u64 newflags;
5511 int ret;
5513 if (!capable(CAP_SYS_ADMIN))
5514 return -EPERM;
5516 if (copy_from_user(flags, arg, sizeof(flags)))
5517 return -EFAULT;
5519 /* Nothing to do */
5520 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5521 !flags[0].incompat_flags)
5522 return 0;
5524 ret = check_feature(root, flags[0].compat_flags,
5525 flags[1].compat_flags, COMPAT);
5526 if (ret)
5527 return ret;
5529 ret = check_feature(root, flags[0].compat_ro_flags,
5530 flags[1].compat_ro_flags, COMPAT_RO);
5531 if (ret)
5532 return ret;
5534 ret = check_feature(root, flags[0].incompat_flags,
5535 flags[1].incompat_flags, INCOMPAT);
5536 if (ret)
5537 return ret;
5539 trans = btrfs_start_transaction(root, 0);
5540 if (IS_ERR(trans))
5541 return PTR_ERR(trans);
5543 spin_lock(&root->fs_info->super_lock);
5544 newflags = btrfs_super_compat_flags(super_block);
5545 newflags |= flags[0].compat_flags & flags[1].compat_flags;
5546 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5547 btrfs_set_super_compat_flags(super_block, newflags);
5549 newflags = btrfs_super_compat_ro_flags(super_block);
5550 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5551 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5552 btrfs_set_super_compat_ro_flags(super_block, newflags);
5554 newflags = btrfs_super_incompat_flags(super_block);
5555 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5556 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5557 btrfs_set_super_incompat_flags(super_block, newflags);
5558 spin_unlock(&root->fs_info->super_lock);
5560 return btrfs_commit_transaction(trans, root);
5563 long btrfs_ioctl(struct file *file, unsigned int
5564 cmd, unsigned long arg)
5566 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5567 void __user *argp = (void __user *)arg;
5569 switch (cmd) {
5570 case FS_IOC_GETFLAGS:
5571 return btrfs_ioctl_getflags(file, argp);
5572 case FS_IOC_SETFLAGS:
5573 return btrfs_ioctl_setflags(file, argp);
5574 case FS_IOC_GETVERSION:
5575 return btrfs_ioctl_getversion(file, argp);
5576 case FITRIM:
5577 return btrfs_ioctl_fitrim(file, argp);
5578 case BTRFS_IOC_SNAP_CREATE:
5579 return btrfs_ioctl_snap_create(file, argp, 0);
5580 case BTRFS_IOC_SNAP_CREATE_V2:
5581 return btrfs_ioctl_snap_create_v2(file, argp, 0);
5582 case BTRFS_IOC_SUBVOL_CREATE:
5583 return btrfs_ioctl_snap_create(file, argp, 1);
5584 case BTRFS_IOC_SUBVOL_CREATE_V2:
5585 return btrfs_ioctl_snap_create_v2(file, argp, 1);
5586 case BTRFS_IOC_SNAP_DESTROY:
5587 return btrfs_ioctl_snap_destroy(file, argp);
5588 case BTRFS_IOC_SUBVOL_GETFLAGS:
5589 return btrfs_ioctl_subvol_getflags(file, argp);
5590 case BTRFS_IOC_SUBVOL_SETFLAGS:
5591 return btrfs_ioctl_subvol_setflags(file, argp);
5592 case BTRFS_IOC_DEFAULT_SUBVOL:
5593 return btrfs_ioctl_default_subvol(file, argp);
5594 case BTRFS_IOC_DEFRAG:
5595 return btrfs_ioctl_defrag(file, NULL);
5596 case BTRFS_IOC_DEFRAG_RANGE:
5597 return btrfs_ioctl_defrag(file, argp);
5598 case BTRFS_IOC_RESIZE:
5599 return btrfs_ioctl_resize(file, argp);
5600 case BTRFS_IOC_ADD_DEV:
5601 return btrfs_ioctl_add_dev(root, argp);
5602 case BTRFS_IOC_RM_DEV:
5603 return btrfs_ioctl_rm_dev(file, argp);
5604 case BTRFS_IOC_FS_INFO:
5605 return btrfs_ioctl_fs_info(root, argp);
5606 case BTRFS_IOC_DEV_INFO:
5607 return btrfs_ioctl_dev_info(root, argp);
5608 case BTRFS_IOC_BALANCE:
5609 return btrfs_ioctl_balance(file, NULL);
5610 case BTRFS_IOC_CLONE:
5611 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
5612 case BTRFS_IOC_CLONE_RANGE:
5613 return btrfs_ioctl_clone_range(file, argp);
5614 case BTRFS_IOC_TRANS_START:
5615 return btrfs_ioctl_trans_start(file);
5616 case BTRFS_IOC_TRANS_END:
5617 return btrfs_ioctl_trans_end(file);
5618 case BTRFS_IOC_TREE_SEARCH:
5619 return btrfs_ioctl_tree_search(file, argp);
5620 case BTRFS_IOC_TREE_SEARCH_V2:
5621 return btrfs_ioctl_tree_search_v2(file, argp);
5622 case BTRFS_IOC_INO_LOOKUP:
5623 return btrfs_ioctl_ino_lookup(file, argp);
5624 case BTRFS_IOC_INO_PATHS:
5625 return btrfs_ioctl_ino_to_path(root, argp);
5626 case BTRFS_IOC_LOGICAL_INO:
5627 return btrfs_ioctl_logical_to_ino(root, argp);
5628 case BTRFS_IOC_SPACE_INFO:
5629 return btrfs_ioctl_space_info(root, argp);
5630 case BTRFS_IOC_SYNC: {
5631 int ret;
5633 ret = btrfs_start_delalloc_roots(root->fs_info, 0, -1);
5634 if (ret)
5635 return ret;
5636 ret = btrfs_sync_fs(file_inode(file)->i_sb, 1);
5638 * The transaction thread may want to do more work,
5639 * namely it pokes the cleaner ktread that will start
5640 * processing uncleaned subvols.
5642 wake_up_process(root->fs_info->transaction_kthread);
5643 return ret;
5645 case BTRFS_IOC_START_SYNC:
5646 return btrfs_ioctl_start_sync(root, argp);
5647 case BTRFS_IOC_WAIT_SYNC:
5648 return btrfs_ioctl_wait_sync(root, argp);
5649 case BTRFS_IOC_SCRUB:
5650 return btrfs_ioctl_scrub(file, argp);
5651 case BTRFS_IOC_SCRUB_CANCEL:
5652 return btrfs_ioctl_scrub_cancel(root, argp);
5653 case BTRFS_IOC_SCRUB_PROGRESS:
5654 return btrfs_ioctl_scrub_progress(root, argp);
5655 case BTRFS_IOC_BALANCE_V2:
5656 return btrfs_ioctl_balance(file, argp);
5657 case BTRFS_IOC_BALANCE_CTL:
5658 return btrfs_ioctl_balance_ctl(root, arg);
5659 case BTRFS_IOC_BALANCE_PROGRESS:
5660 return btrfs_ioctl_balance_progress(root, argp);
5661 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5662 return btrfs_ioctl_set_received_subvol(file, argp);
5663 #ifdef CONFIG_64BIT
5664 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5665 return btrfs_ioctl_set_received_subvol_32(file, argp);
5666 #endif
5667 case BTRFS_IOC_SEND:
5668 return btrfs_ioctl_send(file, argp);
5669 case BTRFS_IOC_GET_DEV_STATS:
5670 return btrfs_ioctl_get_dev_stats(root, argp);
5671 case BTRFS_IOC_QUOTA_CTL:
5672 return btrfs_ioctl_quota_ctl(file, argp);
5673 case BTRFS_IOC_QGROUP_ASSIGN:
5674 return btrfs_ioctl_qgroup_assign(file, argp);
5675 case BTRFS_IOC_QGROUP_CREATE:
5676 return btrfs_ioctl_qgroup_create(file, argp);
5677 case BTRFS_IOC_QGROUP_LIMIT:
5678 return btrfs_ioctl_qgroup_limit(file, argp);
5679 case BTRFS_IOC_QUOTA_RESCAN:
5680 return btrfs_ioctl_quota_rescan(file, argp);
5681 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5682 return btrfs_ioctl_quota_rescan_status(file, argp);
5683 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5684 return btrfs_ioctl_quota_rescan_wait(file, argp);
5685 case BTRFS_IOC_DEV_REPLACE:
5686 return btrfs_ioctl_dev_replace(root, argp);
5687 case BTRFS_IOC_GET_FSLABEL:
5688 return btrfs_ioctl_get_fslabel(file, argp);
5689 case BTRFS_IOC_SET_FSLABEL:
5690 return btrfs_ioctl_set_fslabel(file, argp);
5691 case BTRFS_IOC_FILE_EXTENT_SAME:
5692 return btrfs_ioctl_file_extent_same(file, argp);
5693 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5694 return btrfs_ioctl_get_supported_features(file, argp);
5695 case BTRFS_IOC_GET_FEATURES:
5696 return btrfs_ioctl_get_features(file, argp);
5697 case BTRFS_IOC_SET_FEATURES:
5698 return btrfs_ioctl_set_features(file, argp);
5701 return -ENOTTY;