mm: fix exec activate_mm vs TLB shootdown and lazy tlb switching race
[linux/fpc-iii.git] / fs / btrfs / ioctl.c
blobd3f76e3efd44c9051b3b1e3bab4eb64a633f73cb
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/compat.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/security.h>
39 #include <linux/xattr.h>
40 #include <linux/mm.h>
41 #include <linux/slab.h>
42 #include <linux/blkdev.h>
43 #include <linux/uuid.h>
44 #include <linux/btrfs.h>
45 #include <linux/uaccess.h>
46 #include "ctree.h"
47 #include "disk-io.h"
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "volumes.h"
52 #include "locking.h"
53 #include "inode-map.h"
54 #include "backref.h"
55 #include "rcu-string.h"
56 #include "send.h"
57 #include "dev-replace.h"
58 #include "props.h"
59 #include "sysfs.h"
60 #include "qgroup.h"
61 #include "tree-log.h"
62 #include "compression.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_NOCOMPRESS)
128 iflags |= FS_NOCOMP_FL;
129 else if (flags & BTRFS_INODE_COMPRESS)
130 iflags |= FS_COMPR_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);
159 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
161 struct btrfs_inode *ip = BTRFS_I(file_inode(file));
162 unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
164 if (copy_to_user(arg, &flags, sizeof(flags)))
165 return -EFAULT;
166 return 0;
169 static int check_flags(unsigned int flags)
171 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
172 FS_NOATIME_FL | FS_NODUMP_FL | \
173 FS_SYNC_FL | FS_DIRSYNC_FL | \
174 FS_NOCOMP_FL | FS_COMPR_FL |
175 FS_NOCOW_FL))
176 return -EOPNOTSUPP;
178 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
179 return -EINVAL;
181 return 0;
184 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
186 struct inode *inode = file_inode(file);
187 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
188 struct btrfs_inode *ip = BTRFS_I(inode);
189 struct btrfs_root *root = ip->root;
190 struct btrfs_trans_handle *trans;
191 unsigned int flags, oldflags;
192 int ret;
193 u64 ip_oldflags;
194 unsigned int i_oldflags;
195 umode_t mode;
197 if (!inode_owner_or_capable(inode))
198 return -EPERM;
200 if (btrfs_root_readonly(root))
201 return -EROFS;
203 if (copy_from_user(&flags, arg, sizeof(flags)))
204 return -EFAULT;
206 ret = check_flags(flags);
207 if (ret)
208 return ret;
210 ret = mnt_want_write_file(file);
211 if (ret)
212 return ret;
214 inode_lock(inode);
216 ip_oldflags = ip->flags;
217 i_oldflags = inode->i_flags;
218 mode = inode->i_mode;
220 flags = btrfs_mask_flags(inode->i_mode, flags);
221 oldflags = btrfs_flags_to_ioctl(ip->flags);
222 if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
223 if (!capable(CAP_LINUX_IMMUTABLE)) {
224 ret = -EPERM;
225 goto out_unlock;
229 if (flags & FS_SYNC_FL)
230 ip->flags |= BTRFS_INODE_SYNC;
231 else
232 ip->flags &= ~BTRFS_INODE_SYNC;
233 if (flags & FS_IMMUTABLE_FL)
234 ip->flags |= BTRFS_INODE_IMMUTABLE;
235 else
236 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
237 if (flags & FS_APPEND_FL)
238 ip->flags |= BTRFS_INODE_APPEND;
239 else
240 ip->flags &= ~BTRFS_INODE_APPEND;
241 if (flags & FS_NODUMP_FL)
242 ip->flags |= BTRFS_INODE_NODUMP;
243 else
244 ip->flags &= ~BTRFS_INODE_NODUMP;
245 if (flags & FS_NOATIME_FL)
246 ip->flags |= BTRFS_INODE_NOATIME;
247 else
248 ip->flags &= ~BTRFS_INODE_NOATIME;
249 if (flags & FS_DIRSYNC_FL)
250 ip->flags |= BTRFS_INODE_DIRSYNC;
251 else
252 ip->flags &= ~BTRFS_INODE_DIRSYNC;
253 if (flags & FS_NOCOW_FL) {
254 if (S_ISREG(mode)) {
256 * It's safe to turn csums off here, no extents exist.
257 * Otherwise we want the flag to reflect the real COW
258 * status of the file and will not set it.
260 if (inode->i_size == 0)
261 ip->flags |= BTRFS_INODE_NODATACOW
262 | BTRFS_INODE_NODATASUM;
263 } else {
264 ip->flags |= BTRFS_INODE_NODATACOW;
266 } else {
268 * Revert back under same assumptions as above
270 if (S_ISREG(mode)) {
271 if (inode->i_size == 0)
272 ip->flags &= ~(BTRFS_INODE_NODATACOW
273 | BTRFS_INODE_NODATASUM);
274 } else {
275 ip->flags &= ~BTRFS_INODE_NODATACOW;
280 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
281 * flag may be changed automatically if compression code won't make
282 * things smaller.
284 if (flags & FS_NOCOMP_FL) {
285 ip->flags &= ~BTRFS_INODE_COMPRESS;
286 ip->flags |= BTRFS_INODE_NOCOMPRESS;
288 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
289 if (ret && ret != -ENODATA)
290 goto out_drop;
291 } else if (flags & FS_COMPR_FL) {
292 const char *comp;
294 ip->flags |= BTRFS_INODE_COMPRESS;
295 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
297 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
298 comp = "lzo";
299 else if (fs_info->compress_type == BTRFS_COMPRESS_ZLIB)
300 comp = "zlib";
301 else
302 comp = "zstd";
303 ret = btrfs_set_prop(inode, "btrfs.compression",
304 comp, strlen(comp), 0);
305 if (ret)
306 goto out_drop;
308 } else {
309 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
310 if (ret && ret != -ENODATA)
311 goto out_drop;
312 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
315 trans = btrfs_start_transaction(root, 1);
316 if (IS_ERR(trans)) {
317 ret = PTR_ERR(trans);
318 goto out_drop;
321 btrfs_update_iflags(inode);
322 inode_inc_iversion(inode);
323 inode->i_ctime = current_time(inode);
324 ret = btrfs_update_inode(trans, root, inode);
326 btrfs_end_transaction(trans);
327 out_drop:
328 if (ret) {
329 ip->flags = ip_oldflags;
330 inode->i_flags = i_oldflags;
333 out_unlock:
334 inode_unlock(inode);
335 mnt_drop_write_file(file);
336 return ret;
339 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
341 struct inode *inode = file_inode(file);
343 return put_user(inode->i_generation, arg);
346 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
348 struct inode *inode = file_inode(file);
349 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
350 struct btrfs_device *device;
351 struct request_queue *q;
352 struct fstrim_range range;
353 u64 minlen = ULLONG_MAX;
354 u64 num_devices = 0;
355 int ret;
357 if (!capable(CAP_SYS_ADMIN))
358 return -EPERM;
361 * If the fs is mounted with nologreplay, which requires it to be
362 * mounted in RO mode as well, we can not allow discard on free space
363 * inside block groups, because log trees refer to extents that are not
364 * pinned in a block group's free space cache (pinning the extents is
365 * precisely the first phase of replaying a log tree).
367 if (btrfs_test_opt(fs_info, NOLOGREPLAY))
368 return -EROFS;
370 rcu_read_lock();
371 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
372 dev_list) {
373 if (!device->bdev)
374 continue;
375 q = bdev_get_queue(device->bdev);
376 if (blk_queue_discard(q)) {
377 num_devices++;
378 minlen = min_t(u64, q->limits.discard_granularity,
379 minlen);
382 rcu_read_unlock();
384 if (!num_devices)
385 return -EOPNOTSUPP;
386 if (copy_from_user(&range, arg, sizeof(range)))
387 return -EFAULT;
390 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
391 * block group is in the logical address space, which can be any
392 * sectorsize aligned bytenr in the range [0, U64_MAX].
394 if (range.len < fs_info->sb->s_blocksize)
395 return -EINVAL;
397 range.minlen = max(range.minlen, minlen);
398 ret = btrfs_trim_fs(fs_info, &range);
399 if (ret < 0)
400 return ret;
402 if (copy_to_user(arg, &range, sizeof(range)))
403 return -EFAULT;
405 return 0;
408 int btrfs_is_empty_uuid(u8 *uuid)
410 int i;
412 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
413 if (uuid[i])
414 return 0;
416 return 1;
419 static noinline int create_subvol(struct inode *dir,
420 struct dentry *dentry,
421 const char *name, int namelen,
422 u64 *async_transid,
423 struct btrfs_qgroup_inherit *inherit)
425 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
426 struct btrfs_trans_handle *trans;
427 struct btrfs_key key;
428 struct btrfs_root_item *root_item;
429 struct btrfs_inode_item *inode_item;
430 struct extent_buffer *leaf;
431 struct btrfs_root *root = BTRFS_I(dir)->root;
432 struct btrfs_root *new_root;
433 struct btrfs_block_rsv block_rsv;
434 struct timespec cur_time = current_time(dir);
435 struct inode *inode;
436 int ret;
437 int err;
438 u64 objectid;
439 u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
440 u64 index = 0;
441 u64 qgroup_reserved;
442 uuid_le new_uuid;
444 root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
445 if (!root_item)
446 return -ENOMEM;
448 ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
449 if (ret)
450 goto fail_free;
453 * Don't create subvolume whose level is not zero. Or qgroup will be
454 * screwed up since it assumes subvolume qgroup's level to be 0.
456 if (btrfs_qgroup_level(objectid)) {
457 ret = -ENOSPC;
458 goto fail_free;
461 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
463 * The same as the snapshot creation, please see the comment
464 * of create_snapshot().
466 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
467 8, &qgroup_reserved, false);
468 if (ret)
469 goto fail_free;
471 trans = btrfs_start_transaction(root, 0);
472 if (IS_ERR(trans)) {
473 ret = PTR_ERR(trans);
474 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
475 goto fail_free;
477 trans->block_rsv = &block_rsv;
478 trans->bytes_reserved = block_rsv.size;
480 ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
481 if (ret)
482 goto fail;
484 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
485 if (IS_ERR(leaf)) {
486 ret = PTR_ERR(leaf);
487 goto fail;
490 memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
491 btrfs_set_header_bytenr(leaf, leaf->start);
492 btrfs_set_header_generation(leaf, trans->transid);
493 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
494 btrfs_set_header_owner(leaf, objectid);
496 write_extent_buffer_fsid(leaf, fs_info->fsid);
497 write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
498 btrfs_mark_buffer_dirty(leaf);
500 inode_item = &root_item->inode;
501 btrfs_set_stack_inode_generation(inode_item, 1);
502 btrfs_set_stack_inode_size(inode_item, 3);
503 btrfs_set_stack_inode_nlink(inode_item, 1);
504 btrfs_set_stack_inode_nbytes(inode_item,
505 fs_info->nodesize);
506 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
508 btrfs_set_root_flags(root_item, 0);
509 btrfs_set_root_limit(root_item, 0);
510 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
512 btrfs_set_root_bytenr(root_item, leaf->start);
513 btrfs_set_root_generation(root_item, trans->transid);
514 btrfs_set_root_level(root_item, 0);
515 btrfs_set_root_refs(root_item, 1);
516 btrfs_set_root_used(root_item, leaf->len);
517 btrfs_set_root_last_snapshot(root_item, 0);
519 btrfs_set_root_generation_v2(root_item,
520 btrfs_root_generation(root_item));
521 uuid_le_gen(&new_uuid);
522 memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
523 btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
524 btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
525 root_item->ctime = root_item->otime;
526 btrfs_set_root_ctransid(root_item, trans->transid);
527 btrfs_set_root_otransid(root_item, trans->transid);
529 btrfs_tree_unlock(leaf);
530 free_extent_buffer(leaf);
531 leaf = NULL;
533 btrfs_set_root_dirid(root_item, new_dirid);
535 key.objectid = objectid;
536 key.offset = 0;
537 key.type = BTRFS_ROOT_ITEM_KEY;
538 ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
539 root_item);
540 if (ret)
541 goto fail;
543 key.offset = (u64)-1;
544 new_root = btrfs_read_fs_root_no_name(fs_info, &key);
545 if (IS_ERR(new_root)) {
546 ret = PTR_ERR(new_root);
547 btrfs_abort_transaction(trans, ret);
548 goto fail;
551 btrfs_record_root_in_trans(trans, new_root);
553 ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
554 if (ret) {
555 /* We potentially lose an unused inode item here */
556 btrfs_abort_transaction(trans, ret);
557 goto fail;
560 mutex_lock(&new_root->objectid_mutex);
561 new_root->highest_objectid = new_dirid;
562 mutex_unlock(&new_root->objectid_mutex);
565 * insert the directory item
567 ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
568 if (ret) {
569 btrfs_abort_transaction(trans, ret);
570 goto fail;
573 ret = btrfs_insert_dir_item(trans, root,
574 name, namelen, BTRFS_I(dir), &key,
575 BTRFS_FT_DIR, index);
576 if (ret) {
577 btrfs_abort_transaction(trans, ret);
578 goto fail;
581 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
582 ret = btrfs_update_inode(trans, root, dir);
583 if (ret) {
584 btrfs_abort_transaction(trans, ret);
585 goto fail;
588 ret = btrfs_add_root_ref(trans, fs_info,
589 objectid, root->root_key.objectid,
590 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
591 if (ret) {
592 btrfs_abort_transaction(trans, ret);
593 goto fail;
596 ret = btrfs_uuid_tree_add(trans, fs_info, root_item->uuid,
597 BTRFS_UUID_KEY_SUBVOL, objectid);
598 if (ret)
599 btrfs_abort_transaction(trans, ret);
601 fail:
602 kfree(root_item);
603 trans->block_rsv = NULL;
604 trans->bytes_reserved = 0;
605 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
607 if (async_transid) {
608 *async_transid = trans->transid;
609 err = btrfs_commit_transaction_async(trans, 1);
610 if (err)
611 err = btrfs_commit_transaction(trans);
612 } else {
613 err = btrfs_commit_transaction(trans);
615 if (err && !ret)
616 ret = err;
618 if (!ret) {
619 inode = btrfs_lookup_dentry(dir, dentry);
620 if (IS_ERR(inode))
621 return PTR_ERR(inode);
622 d_instantiate(dentry, inode);
624 return ret;
626 fail_free:
627 kfree(root_item);
628 return ret;
631 static void btrfs_wait_for_no_snapshotting_writes(struct btrfs_root *root)
633 s64 writers;
634 DEFINE_WAIT(wait);
636 do {
637 prepare_to_wait(&root->subv_writers->wait, &wait,
638 TASK_UNINTERRUPTIBLE);
640 writers = percpu_counter_sum(&root->subv_writers->counter);
641 if (writers)
642 schedule();
644 finish_wait(&root->subv_writers->wait, &wait);
645 } while (writers);
648 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
649 struct dentry *dentry,
650 u64 *async_transid, bool readonly,
651 struct btrfs_qgroup_inherit *inherit)
653 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
654 struct inode *inode;
655 struct btrfs_pending_snapshot *pending_snapshot;
656 struct btrfs_trans_handle *trans;
657 int ret;
658 bool snapshot_force_cow = false;
660 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
661 return -EINVAL;
663 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
664 if (!pending_snapshot)
665 return -ENOMEM;
667 pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
668 GFP_KERNEL);
669 pending_snapshot->path = btrfs_alloc_path();
670 if (!pending_snapshot->root_item || !pending_snapshot->path) {
671 ret = -ENOMEM;
672 goto free_pending;
676 * Force new buffered writes to reserve space even when NOCOW is
677 * possible. This is to avoid later writeback (running dealloc) to
678 * fallback to COW mode and unexpectedly fail with ENOSPC.
680 atomic_inc(&root->will_be_snapshotted);
681 smp_mb__after_atomic();
682 btrfs_wait_for_no_snapshotting_writes(root);
684 ret = btrfs_start_delalloc_inodes(root, 0);
685 if (ret)
686 goto dec_and_free;
689 * All previous writes have started writeback in NOCOW mode, so now
690 * we force future writes to fallback to COW mode during snapshot
691 * creation.
693 atomic_inc(&root->snapshot_force_cow);
694 snapshot_force_cow = true;
696 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
698 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
699 BTRFS_BLOCK_RSV_TEMP);
701 * 1 - parent dir inode
702 * 2 - dir entries
703 * 1 - root item
704 * 2 - root ref/backref
705 * 1 - root of snapshot
706 * 1 - UUID item
708 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
709 &pending_snapshot->block_rsv, 8,
710 &pending_snapshot->qgroup_reserved,
711 false);
712 if (ret)
713 goto dec_and_free;
715 pending_snapshot->dentry = dentry;
716 pending_snapshot->root = root;
717 pending_snapshot->readonly = readonly;
718 pending_snapshot->dir = dir;
719 pending_snapshot->inherit = inherit;
721 trans = btrfs_start_transaction(root, 0);
722 if (IS_ERR(trans)) {
723 ret = PTR_ERR(trans);
724 goto fail;
727 spin_lock(&fs_info->trans_lock);
728 list_add(&pending_snapshot->list,
729 &trans->transaction->pending_snapshots);
730 spin_unlock(&fs_info->trans_lock);
731 if (async_transid) {
732 *async_transid = trans->transid;
733 ret = btrfs_commit_transaction_async(trans, 1);
734 if (ret)
735 ret = btrfs_commit_transaction(trans);
736 } else {
737 ret = btrfs_commit_transaction(trans);
739 if (ret)
740 goto fail;
742 ret = pending_snapshot->error;
743 if (ret)
744 goto fail;
746 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
747 if (ret)
748 goto fail;
750 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
751 if (IS_ERR(inode)) {
752 ret = PTR_ERR(inode);
753 goto fail;
756 d_instantiate(dentry, inode);
757 ret = 0;
758 fail:
759 btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
760 dec_and_free:
761 if (snapshot_force_cow)
762 atomic_dec(&root->snapshot_force_cow);
763 if (atomic_dec_and_test(&root->will_be_snapshotted))
764 wake_up_atomic_t(&root->will_be_snapshotted);
765 free_pending:
766 kfree(pending_snapshot->root_item);
767 btrfs_free_path(pending_snapshot->path);
768 kfree(pending_snapshot);
770 return ret;
773 /* copy of may_delete in fs/namei.c()
774 * Check whether we can remove a link victim from directory dir, check
775 * whether the type of victim is right.
776 * 1. We can't do it if dir is read-only (done in permission())
777 * 2. We should have write and exec permissions on dir
778 * 3. We can't remove anything from append-only dir
779 * 4. We can't do anything with immutable dir (done in permission())
780 * 5. If the sticky bit on dir is set we should either
781 * a. be owner of dir, or
782 * b. be owner of victim, or
783 * c. have CAP_FOWNER capability
784 * 6. If the victim is append-only or immutable we can't do anything with
785 * links pointing to it.
786 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
787 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
788 * 9. We can't remove a root or mountpoint.
789 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
790 * nfs_async_unlink().
793 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
795 int error;
797 if (d_really_is_negative(victim))
798 return -ENOENT;
800 BUG_ON(d_inode(victim->d_parent) != dir);
801 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
803 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
804 if (error)
805 return error;
806 if (IS_APPEND(dir))
807 return -EPERM;
808 if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
809 IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
810 return -EPERM;
811 if (isdir) {
812 if (!d_is_dir(victim))
813 return -ENOTDIR;
814 if (IS_ROOT(victim))
815 return -EBUSY;
816 } else if (d_is_dir(victim))
817 return -EISDIR;
818 if (IS_DEADDIR(dir))
819 return -ENOENT;
820 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
821 return -EBUSY;
822 return 0;
825 /* copy of may_create in fs/namei.c() */
826 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
828 if (d_really_is_positive(child))
829 return -EEXIST;
830 if (IS_DEADDIR(dir))
831 return -ENOENT;
832 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
836 * Create a new subvolume below @parent. This is largely modeled after
837 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
838 * inside this filesystem so it's quite a bit simpler.
840 static noinline int btrfs_mksubvol(const struct path *parent,
841 const char *name, int namelen,
842 struct btrfs_root *snap_src,
843 u64 *async_transid, bool readonly,
844 struct btrfs_qgroup_inherit *inherit)
846 struct inode *dir = d_inode(parent->dentry);
847 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
848 struct dentry *dentry;
849 int error;
851 error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
852 if (error == -EINTR)
853 return error;
855 dentry = lookup_one_len(name, parent->dentry, namelen);
856 error = PTR_ERR(dentry);
857 if (IS_ERR(dentry))
858 goto out_unlock;
860 error = btrfs_may_create(dir, dentry);
861 if (error)
862 goto out_dput;
865 * even if this name doesn't exist, we may get hash collisions.
866 * check for them now when we can safely fail
868 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
869 dir->i_ino, name,
870 namelen);
871 if (error)
872 goto out_dput;
874 down_read(&fs_info->subvol_sem);
876 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
877 goto out_up_read;
879 if (snap_src) {
880 error = create_snapshot(snap_src, dir, dentry,
881 async_transid, readonly, inherit);
882 } else {
883 error = create_subvol(dir, dentry, name, namelen,
884 async_transid, inherit);
886 if (!error)
887 fsnotify_mkdir(dir, dentry);
888 out_up_read:
889 up_read(&fs_info->subvol_sem);
890 out_dput:
891 dput(dentry);
892 out_unlock:
893 inode_unlock(dir);
894 return error;
898 * When we're defragging a range, we don't want to kick it off again
899 * if it is really just waiting for delalloc to send it down.
900 * If we find a nice big extent or delalloc range for the bytes in the
901 * file you want to defrag, we return 0 to let you know to skip this
902 * part of the file
904 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
906 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
907 struct extent_map *em = NULL;
908 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
909 u64 end;
911 read_lock(&em_tree->lock);
912 em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
913 read_unlock(&em_tree->lock);
915 if (em) {
916 end = extent_map_end(em);
917 free_extent_map(em);
918 if (end - offset > thresh)
919 return 0;
921 /* if we already have a nice delalloc here, just stop */
922 thresh /= 2;
923 end = count_range_bits(io_tree, &offset, offset + thresh,
924 thresh, EXTENT_DELALLOC, 1);
925 if (end >= thresh)
926 return 0;
927 return 1;
931 * helper function to walk through a file and find extents
932 * newer than a specific transid, and smaller than thresh.
934 * This is used by the defragging code to find new and small
935 * extents
937 static int find_new_extents(struct btrfs_root *root,
938 struct inode *inode, u64 newer_than,
939 u64 *off, u32 thresh)
941 struct btrfs_path *path;
942 struct btrfs_key min_key;
943 struct extent_buffer *leaf;
944 struct btrfs_file_extent_item *extent;
945 int type;
946 int ret;
947 u64 ino = btrfs_ino(BTRFS_I(inode));
949 path = btrfs_alloc_path();
950 if (!path)
951 return -ENOMEM;
953 min_key.objectid = ino;
954 min_key.type = BTRFS_EXTENT_DATA_KEY;
955 min_key.offset = *off;
957 while (1) {
958 ret = btrfs_search_forward(root, &min_key, path, newer_than);
959 if (ret != 0)
960 goto none;
961 process_slot:
962 if (min_key.objectid != ino)
963 goto none;
964 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
965 goto none;
967 leaf = path->nodes[0];
968 extent = btrfs_item_ptr(leaf, path->slots[0],
969 struct btrfs_file_extent_item);
971 type = btrfs_file_extent_type(leaf, extent);
972 if (type == BTRFS_FILE_EXTENT_REG &&
973 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
974 check_defrag_in_cache(inode, min_key.offset, thresh)) {
975 *off = min_key.offset;
976 btrfs_free_path(path);
977 return 0;
980 path->slots[0]++;
981 if (path->slots[0] < btrfs_header_nritems(leaf)) {
982 btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
983 goto process_slot;
986 if (min_key.offset == (u64)-1)
987 goto none;
989 min_key.offset++;
990 btrfs_release_path(path);
992 none:
993 btrfs_free_path(path);
994 return -ENOENT;
997 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
999 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1000 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1001 struct extent_map *em;
1002 u64 len = PAGE_SIZE;
1005 * hopefully we have this extent in the tree already, try without
1006 * the full extent lock
1008 read_lock(&em_tree->lock);
1009 em = lookup_extent_mapping(em_tree, start, len);
1010 read_unlock(&em_tree->lock);
1012 if (!em) {
1013 struct extent_state *cached = NULL;
1014 u64 end = start + len - 1;
1016 /* get the big lock and read metadata off disk */
1017 lock_extent_bits(io_tree, start, end, &cached);
1018 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1019 unlock_extent_cached(io_tree, start, end, &cached, GFP_NOFS);
1021 if (IS_ERR(em))
1022 return NULL;
1025 return em;
1028 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1030 struct extent_map *next;
1031 bool ret = true;
1033 /* this is the last extent */
1034 if (em->start + em->len >= i_size_read(inode))
1035 return false;
1037 next = defrag_lookup_extent(inode, em->start + em->len);
1038 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1039 ret = false;
1040 else if ((em->block_start + em->block_len == next->block_start) &&
1041 (em->block_len > SZ_128K && next->block_len > SZ_128K))
1042 ret = false;
1044 free_extent_map(next);
1045 return ret;
1048 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1049 u64 *last_len, u64 *skip, u64 *defrag_end,
1050 int compress)
1052 struct extent_map *em;
1053 int ret = 1;
1054 bool next_mergeable = true;
1055 bool prev_mergeable = true;
1058 * make sure that once we start defragging an extent, we keep on
1059 * defragging it
1061 if (start < *defrag_end)
1062 return 1;
1064 *skip = 0;
1066 em = defrag_lookup_extent(inode, start);
1067 if (!em)
1068 return 0;
1070 /* this will cover holes, and inline extents */
1071 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1072 ret = 0;
1073 goto out;
1076 if (!*defrag_end)
1077 prev_mergeable = false;
1079 next_mergeable = defrag_check_next_extent(inode, em);
1081 * we hit a real extent, if it is big or the next extent is not a
1082 * real extent, don't bother defragging it
1084 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1085 (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1086 ret = 0;
1087 out:
1089 * last_len ends up being a counter of how many bytes we've defragged.
1090 * every time we choose not to defrag an extent, we reset *last_len
1091 * so that the next tiny extent will force a defrag.
1093 * The end result of this is that tiny extents before a single big
1094 * extent will force at least part of that big extent to be defragged.
1096 if (ret) {
1097 *defrag_end = extent_map_end(em);
1098 } else {
1099 *last_len = 0;
1100 *skip = extent_map_end(em);
1101 *defrag_end = 0;
1104 free_extent_map(em);
1105 return ret;
1109 * it doesn't do much good to defrag one or two pages
1110 * at a time. This pulls in a nice chunk of pages
1111 * to COW and defrag.
1113 * It also makes sure the delalloc code has enough
1114 * dirty data to avoid making new small extents as part
1115 * of the defrag
1117 * It's a good idea to start RA on this range
1118 * before calling this.
1120 static int cluster_pages_for_defrag(struct inode *inode,
1121 struct page **pages,
1122 unsigned long start_index,
1123 unsigned long num_pages)
1125 unsigned long file_end;
1126 u64 isize = i_size_read(inode);
1127 u64 page_start;
1128 u64 page_end;
1129 u64 page_cnt;
1130 int ret;
1131 int i;
1132 int i_done;
1133 struct btrfs_ordered_extent *ordered;
1134 struct extent_state *cached_state = NULL;
1135 struct extent_io_tree *tree;
1136 struct extent_changeset *data_reserved = NULL;
1137 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1139 file_end = (isize - 1) >> PAGE_SHIFT;
1140 if (!isize || start_index > file_end)
1141 return 0;
1143 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1145 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
1146 start_index << PAGE_SHIFT,
1147 page_cnt << PAGE_SHIFT);
1148 if (ret)
1149 return ret;
1150 i_done = 0;
1151 tree = &BTRFS_I(inode)->io_tree;
1153 /* step one, lock all the pages */
1154 for (i = 0; i < page_cnt; i++) {
1155 struct page *page;
1156 again:
1157 page = find_or_create_page(inode->i_mapping,
1158 start_index + i, mask);
1159 if (!page)
1160 break;
1162 page_start = page_offset(page);
1163 page_end = page_start + PAGE_SIZE - 1;
1164 while (1) {
1165 lock_extent_bits(tree, page_start, page_end,
1166 &cached_state);
1167 ordered = btrfs_lookup_ordered_extent(inode,
1168 page_start);
1169 unlock_extent_cached(tree, page_start, page_end,
1170 &cached_state, GFP_NOFS);
1171 if (!ordered)
1172 break;
1174 unlock_page(page);
1175 btrfs_start_ordered_extent(inode, ordered, 1);
1176 btrfs_put_ordered_extent(ordered);
1177 lock_page(page);
1179 * we unlocked the page above, so we need check if
1180 * it was released or not.
1182 if (page->mapping != inode->i_mapping) {
1183 unlock_page(page);
1184 put_page(page);
1185 goto again;
1189 if (!PageUptodate(page)) {
1190 btrfs_readpage(NULL, page);
1191 lock_page(page);
1192 if (!PageUptodate(page)) {
1193 unlock_page(page);
1194 put_page(page);
1195 ret = -EIO;
1196 break;
1200 if (page->mapping != inode->i_mapping) {
1201 unlock_page(page);
1202 put_page(page);
1203 goto again;
1206 pages[i] = page;
1207 i_done++;
1209 if (!i_done || ret)
1210 goto out;
1212 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1213 goto out;
1216 * so now we have a nice long stream of locked
1217 * and up to date pages, lets wait on them
1219 for (i = 0; i < i_done; i++)
1220 wait_on_page_writeback(pages[i]);
1222 page_start = page_offset(pages[0]);
1223 page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1225 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1226 page_start, page_end - 1, &cached_state);
1227 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1228 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1229 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1230 &cached_state, GFP_NOFS);
1232 if (i_done != page_cnt) {
1233 spin_lock(&BTRFS_I(inode)->lock);
1234 BTRFS_I(inode)->outstanding_extents++;
1235 spin_unlock(&BTRFS_I(inode)->lock);
1236 btrfs_delalloc_release_space(inode, data_reserved,
1237 start_index << PAGE_SHIFT,
1238 (page_cnt - i_done) << PAGE_SHIFT);
1242 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1243 &cached_state);
1245 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1246 page_start, page_end - 1, &cached_state,
1247 GFP_NOFS);
1249 for (i = 0; i < i_done; i++) {
1250 clear_page_dirty_for_io(pages[i]);
1251 ClearPageChecked(pages[i]);
1252 set_page_extent_mapped(pages[i]);
1253 set_page_dirty(pages[i]);
1254 unlock_page(pages[i]);
1255 put_page(pages[i]);
1257 extent_changeset_free(data_reserved);
1258 return i_done;
1259 out:
1260 for (i = 0; i < i_done; i++) {
1261 unlock_page(pages[i]);
1262 put_page(pages[i]);
1264 btrfs_delalloc_release_space(inode, data_reserved,
1265 start_index << PAGE_SHIFT,
1266 page_cnt << PAGE_SHIFT);
1267 extent_changeset_free(data_reserved);
1268 return ret;
1272 int btrfs_defrag_file(struct inode *inode, struct file *file,
1273 struct btrfs_ioctl_defrag_range_args *range,
1274 u64 newer_than, unsigned long max_to_defrag)
1276 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1277 struct btrfs_root *root = BTRFS_I(inode)->root;
1278 struct file_ra_state *ra = NULL;
1279 unsigned long last_index;
1280 u64 isize = i_size_read(inode);
1281 u64 last_len = 0;
1282 u64 skip = 0;
1283 u64 defrag_end = 0;
1284 u64 newer_off = range->start;
1285 unsigned long i;
1286 unsigned long ra_index = 0;
1287 int ret;
1288 int defrag_count = 0;
1289 int compress_type = BTRFS_COMPRESS_ZLIB;
1290 u32 extent_thresh = range->extent_thresh;
1291 unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1292 unsigned long cluster = max_cluster;
1293 u64 new_align = ~((u64)SZ_128K - 1);
1294 struct page **pages = NULL;
1295 bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1297 if (isize == 0)
1298 return 0;
1300 if (range->start >= isize)
1301 return -EINVAL;
1303 if (do_compress) {
1304 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1305 return -EINVAL;
1306 if (range->compress_type)
1307 compress_type = range->compress_type;
1310 if (extent_thresh == 0)
1311 extent_thresh = SZ_256K;
1314 * If we were not given a file, allocate a readahead context. As
1315 * readahead is just an optimization, defrag will work without it so
1316 * we don't error out.
1318 if (!file) {
1319 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1320 if (ra)
1321 file_ra_state_init(ra, inode->i_mapping);
1322 } else {
1323 ra = &file->f_ra;
1326 pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1327 if (!pages) {
1328 ret = -ENOMEM;
1329 goto out_ra;
1332 /* find the last page to defrag */
1333 if (range->start + range->len > range->start) {
1334 last_index = min_t(u64, isize - 1,
1335 range->start + range->len - 1) >> PAGE_SHIFT;
1336 } else {
1337 last_index = (isize - 1) >> PAGE_SHIFT;
1340 if (newer_than) {
1341 ret = find_new_extents(root, inode, newer_than,
1342 &newer_off, SZ_64K);
1343 if (!ret) {
1344 range->start = newer_off;
1346 * we always align our defrag to help keep
1347 * the extents in the file evenly spaced
1349 i = (newer_off & new_align) >> PAGE_SHIFT;
1350 } else
1351 goto out_ra;
1352 } else {
1353 i = range->start >> PAGE_SHIFT;
1355 if (!max_to_defrag)
1356 max_to_defrag = last_index - i + 1;
1359 * make writeback starts from i, so the defrag range can be
1360 * written sequentially.
1362 if (i < inode->i_mapping->writeback_index)
1363 inode->i_mapping->writeback_index = i;
1365 while (i <= last_index && defrag_count < max_to_defrag &&
1366 (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1368 * make sure we stop running if someone unmounts
1369 * the FS
1371 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1372 break;
1374 if (btrfs_defrag_cancelled(fs_info)) {
1375 btrfs_debug(fs_info, "defrag_file cancelled");
1376 ret = -EAGAIN;
1377 break;
1380 if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1381 extent_thresh, &last_len, &skip,
1382 &defrag_end, do_compress)){
1383 unsigned long next;
1385 * the should_defrag function tells us how much to skip
1386 * bump our counter by the suggested amount
1388 next = DIV_ROUND_UP(skip, PAGE_SIZE);
1389 i = max(i + 1, next);
1390 continue;
1393 if (!newer_than) {
1394 cluster = (PAGE_ALIGN(defrag_end) >>
1395 PAGE_SHIFT) - i;
1396 cluster = min(cluster, max_cluster);
1397 } else {
1398 cluster = max_cluster;
1401 if (i + cluster > ra_index) {
1402 ra_index = max(i, ra_index);
1403 if (ra)
1404 page_cache_sync_readahead(inode->i_mapping, ra,
1405 file, ra_index, cluster);
1406 ra_index += cluster;
1409 inode_lock(inode);
1410 if (do_compress)
1411 BTRFS_I(inode)->defrag_compress = compress_type;
1412 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1413 if (ret < 0) {
1414 inode_unlock(inode);
1415 goto out_ra;
1418 defrag_count += ret;
1419 balance_dirty_pages_ratelimited(inode->i_mapping);
1420 inode_unlock(inode);
1422 if (newer_than) {
1423 if (newer_off == (u64)-1)
1424 break;
1426 if (ret > 0)
1427 i += ret;
1429 newer_off = max(newer_off + 1,
1430 (u64)i << PAGE_SHIFT);
1432 ret = find_new_extents(root, inode, newer_than,
1433 &newer_off, SZ_64K);
1434 if (!ret) {
1435 range->start = newer_off;
1436 i = (newer_off & new_align) >> PAGE_SHIFT;
1437 } else {
1438 break;
1440 } else {
1441 if (ret > 0) {
1442 i += ret;
1443 last_len += ret << PAGE_SHIFT;
1444 } else {
1445 i++;
1446 last_len = 0;
1451 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1452 filemap_flush(inode->i_mapping);
1453 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1454 &BTRFS_I(inode)->runtime_flags))
1455 filemap_flush(inode->i_mapping);
1458 if (do_compress) {
1459 /* the filemap_flush will queue IO into the worker threads, but
1460 * we have to make sure the IO is actually started and that
1461 * ordered extents get created before we return
1463 atomic_inc(&fs_info->async_submit_draining);
1464 while (atomic_read(&fs_info->nr_async_submits) ||
1465 atomic_read(&fs_info->async_delalloc_pages)) {
1466 wait_event(fs_info->async_submit_wait,
1467 (atomic_read(&fs_info->nr_async_submits) == 0 &&
1468 atomic_read(&fs_info->async_delalloc_pages) == 0));
1470 atomic_dec(&fs_info->async_submit_draining);
1473 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1474 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1475 } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1476 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1479 ret = defrag_count;
1481 out_ra:
1482 if (do_compress) {
1483 inode_lock(inode);
1484 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1485 inode_unlock(inode);
1487 if (!file)
1488 kfree(ra);
1489 kfree(pages);
1490 return ret;
1493 static noinline int btrfs_ioctl_resize(struct file *file,
1494 void __user *arg)
1496 struct inode *inode = file_inode(file);
1497 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1498 u64 new_size;
1499 u64 old_size;
1500 u64 devid = 1;
1501 struct btrfs_root *root = BTRFS_I(inode)->root;
1502 struct btrfs_ioctl_vol_args *vol_args;
1503 struct btrfs_trans_handle *trans;
1504 struct btrfs_device *device = NULL;
1505 char *sizestr;
1506 char *retptr;
1507 char *devstr = NULL;
1508 int ret = 0;
1509 int mod = 0;
1511 if (!capable(CAP_SYS_ADMIN))
1512 return -EPERM;
1514 ret = mnt_want_write_file(file);
1515 if (ret)
1516 return ret;
1518 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
1519 mnt_drop_write_file(file);
1520 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1523 mutex_lock(&fs_info->volume_mutex);
1524 vol_args = memdup_user(arg, sizeof(*vol_args));
1525 if (IS_ERR(vol_args)) {
1526 ret = PTR_ERR(vol_args);
1527 goto out;
1530 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1532 sizestr = vol_args->name;
1533 devstr = strchr(sizestr, ':');
1534 if (devstr) {
1535 sizestr = devstr + 1;
1536 *devstr = '\0';
1537 devstr = vol_args->name;
1538 ret = kstrtoull(devstr, 10, &devid);
1539 if (ret)
1540 goto out_free;
1541 if (!devid) {
1542 ret = -EINVAL;
1543 goto out_free;
1545 btrfs_info(fs_info, "resizing devid %llu", devid);
1548 device = btrfs_find_device(fs_info, devid, NULL, NULL);
1549 if (!device) {
1550 btrfs_info(fs_info, "resizer unable to find device %llu",
1551 devid);
1552 ret = -ENODEV;
1553 goto out_free;
1556 if (!device->writeable) {
1557 btrfs_info(fs_info,
1558 "resizer unable to apply on readonly device %llu",
1559 devid);
1560 ret = -EPERM;
1561 goto out_free;
1564 if (!strcmp(sizestr, "max"))
1565 new_size = device->bdev->bd_inode->i_size;
1566 else {
1567 if (sizestr[0] == '-') {
1568 mod = -1;
1569 sizestr++;
1570 } else if (sizestr[0] == '+') {
1571 mod = 1;
1572 sizestr++;
1574 new_size = memparse(sizestr, &retptr);
1575 if (*retptr != '\0' || new_size == 0) {
1576 ret = -EINVAL;
1577 goto out_free;
1581 if (device->is_tgtdev_for_dev_replace) {
1582 ret = -EPERM;
1583 goto out_free;
1586 old_size = btrfs_device_get_total_bytes(device);
1588 if (mod < 0) {
1589 if (new_size > old_size) {
1590 ret = -EINVAL;
1591 goto out_free;
1593 new_size = old_size - new_size;
1594 } else if (mod > 0) {
1595 if (new_size > ULLONG_MAX - old_size) {
1596 ret = -ERANGE;
1597 goto out_free;
1599 new_size = old_size + new_size;
1602 if (new_size < SZ_256M) {
1603 ret = -EINVAL;
1604 goto out_free;
1606 if (new_size > device->bdev->bd_inode->i_size) {
1607 ret = -EFBIG;
1608 goto out_free;
1611 new_size = round_down(new_size, fs_info->sectorsize);
1613 btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1614 rcu_str_deref(device->name), new_size);
1616 if (new_size > old_size) {
1617 trans = btrfs_start_transaction(root, 0);
1618 if (IS_ERR(trans)) {
1619 ret = PTR_ERR(trans);
1620 goto out_free;
1622 ret = btrfs_grow_device(trans, device, new_size);
1623 btrfs_commit_transaction(trans);
1624 } else if (new_size < old_size) {
1625 ret = btrfs_shrink_device(device, new_size);
1626 } /* equal, nothing need to do */
1628 out_free:
1629 kfree(vol_args);
1630 out:
1631 mutex_unlock(&fs_info->volume_mutex);
1632 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
1633 mnt_drop_write_file(file);
1634 return ret;
1637 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1638 const char *name, unsigned long fd, int subvol,
1639 u64 *transid, bool readonly,
1640 struct btrfs_qgroup_inherit *inherit)
1642 int namelen;
1643 int ret = 0;
1645 if (!S_ISDIR(file_inode(file)->i_mode))
1646 return -ENOTDIR;
1648 ret = mnt_want_write_file(file);
1649 if (ret)
1650 goto out;
1652 namelen = strlen(name);
1653 if (strchr(name, '/')) {
1654 ret = -EINVAL;
1655 goto out_drop_write;
1658 if (name[0] == '.' &&
1659 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1660 ret = -EEXIST;
1661 goto out_drop_write;
1664 if (subvol) {
1665 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1666 NULL, transid, readonly, inherit);
1667 } else {
1668 struct fd src = fdget(fd);
1669 struct inode *src_inode;
1670 if (!src.file) {
1671 ret = -EINVAL;
1672 goto out_drop_write;
1675 src_inode = file_inode(src.file);
1676 if (src_inode->i_sb != file_inode(file)->i_sb) {
1677 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1678 "Snapshot src from another FS");
1679 ret = -EXDEV;
1680 } else if (!inode_owner_or_capable(src_inode)) {
1682 * Subvolume creation is not restricted, but snapshots
1683 * are limited to own subvolumes only
1685 ret = -EPERM;
1686 } else {
1687 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1688 BTRFS_I(src_inode)->root,
1689 transid, readonly, inherit);
1691 fdput(src);
1693 out_drop_write:
1694 mnt_drop_write_file(file);
1695 out:
1696 return ret;
1699 static noinline int btrfs_ioctl_snap_create(struct file *file,
1700 void __user *arg, int subvol)
1702 struct btrfs_ioctl_vol_args *vol_args;
1703 int ret;
1705 if (!S_ISDIR(file_inode(file)->i_mode))
1706 return -ENOTDIR;
1708 vol_args = memdup_user(arg, sizeof(*vol_args));
1709 if (IS_ERR(vol_args))
1710 return PTR_ERR(vol_args);
1711 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1713 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1714 vol_args->fd, subvol,
1715 NULL, false, NULL);
1717 kfree(vol_args);
1718 return ret;
1721 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1722 void __user *arg, int subvol)
1724 struct btrfs_ioctl_vol_args_v2 *vol_args;
1725 int ret;
1726 u64 transid = 0;
1727 u64 *ptr = NULL;
1728 bool readonly = false;
1729 struct btrfs_qgroup_inherit *inherit = NULL;
1731 if (!S_ISDIR(file_inode(file)->i_mode))
1732 return -ENOTDIR;
1734 vol_args = memdup_user(arg, sizeof(*vol_args));
1735 if (IS_ERR(vol_args))
1736 return PTR_ERR(vol_args);
1737 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1739 if (vol_args->flags &
1740 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1741 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1742 ret = -EOPNOTSUPP;
1743 goto free_args;
1746 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1747 ptr = &transid;
1748 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1749 readonly = true;
1750 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1751 if (vol_args->size > PAGE_SIZE) {
1752 ret = -EINVAL;
1753 goto free_args;
1755 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1756 if (IS_ERR(inherit)) {
1757 ret = PTR_ERR(inherit);
1758 goto free_args;
1762 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1763 vol_args->fd, subvol, ptr,
1764 readonly, inherit);
1765 if (ret)
1766 goto free_inherit;
1768 if (ptr && copy_to_user(arg +
1769 offsetof(struct btrfs_ioctl_vol_args_v2,
1770 transid),
1771 ptr, sizeof(*ptr)))
1772 ret = -EFAULT;
1774 free_inherit:
1775 kfree(inherit);
1776 free_args:
1777 kfree(vol_args);
1778 return ret;
1781 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1782 void __user *arg)
1784 struct inode *inode = file_inode(file);
1785 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1786 struct btrfs_root *root = BTRFS_I(inode)->root;
1787 int ret = 0;
1788 u64 flags = 0;
1790 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1791 return -EINVAL;
1793 down_read(&fs_info->subvol_sem);
1794 if (btrfs_root_readonly(root))
1795 flags |= BTRFS_SUBVOL_RDONLY;
1796 up_read(&fs_info->subvol_sem);
1798 if (copy_to_user(arg, &flags, sizeof(flags)))
1799 ret = -EFAULT;
1801 return ret;
1804 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1805 void __user *arg)
1807 struct inode *inode = file_inode(file);
1808 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1809 struct btrfs_root *root = BTRFS_I(inode)->root;
1810 struct btrfs_trans_handle *trans;
1811 u64 root_flags;
1812 u64 flags;
1813 int ret = 0;
1815 if (!inode_owner_or_capable(inode))
1816 return -EPERM;
1818 ret = mnt_want_write_file(file);
1819 if (ret)
1820 goto out;
1822 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1823 ret = -EINVAL;
1824 goto out_drop_write;
1827 if (copy_from_user(&flags, arg, sizeof(flags))) {
1828 ret = -EFAULT;
1829 goto out_drop_write;
1832 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1833 ret = -EINVAL;
1834 goto out_drop_write;
1837 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1838 ret = -EOPNOTSUPP;
1839 goto out_drop_write;
1842 down_write(&fs_info->subvol_sem);
1844 /* nothing to do */
1845 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1846 goto out_drop_sem;
1848 root_flags = btrfs_root_flags(&root->root_item);
1849 if (flags & BTRFS_SUBVOL_RDONLY) {
1850 btrfs_set_root_flags(&root->root_item,
1851 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1852 } else {
1854 * Block RO -> RW transition if this subvolume is involved in
1855 * send
1857 spin_lock(&root->root_item_lock);
1858 if (root->send_in_progress == 0) {
1859 btrfs_set_root_flags(&root->root_item,
1860 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1861 spin_unlock(&root->root_item_lock);
1862 } else {
1863 spin_unlock(&root->root_item_lock);
1864 btrfs_warn(fs_info,
1865 "Attempt to set subvolume %llu read-write during send",
1866 root->root_key.objectid);
1867 ret = -EPERM;
1868 goto out_drop_sem;
1872 trans = btrfs_start_transaction(root, 1);
1873 if (IS_ERR(trans)) {
1874 ret = PTR_ERR(trans);
1875 goto out_reset;
1878 ret = btrfs_update_root(trans, fs_info->tree_root,
1879 &root->root_key, &root->root_item);
1880 if (ret < 0) {
1881 btrfs_end_transaction(trans);
1882 goto out_reset;
1885 ret = btrfs_commit_transaction(trans);
1887 out_reset:
1888 if (ret)
1889 btrfs_set_root_flags(&root->root_item, root_flags);
1890 out_drop_sem:
1891 up_write(&fs_info->subvol_sem);
1892 out_drop_write:
1893 mnt_drop_write_file(file);
1894 out:
1895 return ret;
1899 * helper to check if the subvolume references other subvolumes
1901 static noinline int may_destroy_subvol(struct btrfs_root *root)
1903 struct btrfs_fs_info *fs_info = root->fs_info;
1904 struct btrfs_path *path;
1905 struct btrfs_dir_item *di;
1906 struct btrfs_key key;
1907 u64 dir_id;
1908 int ret;
1910 path = btrfs_alloc_path();
1911 if (!path)
1912 return -ENOMEM;
1914 /* Make sure this root isn't set as the default subvol */
1915 dir_id = btrfs_super_root_dir(fs_info->super_copy);
1916 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
1917 dir_id, "default", 7, 0);
1918 if (di && !IS_ERR(di)) {
1919 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1920 if (key.objectid == root->root_key.objectid) {
1921 ret = -EPERM;
1922 btrfs_err(fs_info,
1923 "deleting default subvolume %llu is not allowed",
1924 key.objectid);
1925 goto out;
1927 btrfs_release_path(path);
1930 key.objectid = root->root_key.objectid;
1931 key.type = BTRFS_ROOT_REF_KEY;
1932 key.offset = (u64)-1;
1934 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1935 if (ret < 0)
1936 goto out;
1937 BUG_ON(ret == 0);
1939 ret = 0;
1940 if (path->slots[0] > 0) {
1941 path->slots[0]--;
1942 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1943 if (key.objectid == root->root_key.objectid &&
1944 key.type == BTRFS_ROOT_REF_KEY)
1945 ret = -ENOTEMPTY;
1947 out:
1948 btrfs_free_path(path);
1949 return ret;
1952 static noinline int key_in_sk(struct btrfs_key *key,
1953 struct btrfs_ioctl_search_key *sk)
1955 struct btrfs_key test;
1956 int ret;
1958 test.objectid = sk->min_objectid;
1959 test.type = sk->min_type;
1960 test.offset = sk->min_offset;
1962 ret = btrfs_comp_cpu_keys(key, &test);
1963 if (ret < 0)
1964 return 0;
1966 test.objectid = sk->max_objectid;
1967 test.type = sk->max_type;
1968 test.offset = sk->max_offset;
1970 ret = btrfs_comp_cpu_keys(key, &test);
1971 if (ret > 0)
1972 return 0;
1973 return 1;
1976 static noinline int copy_to_sk(struct btrfs_path *path,
1977 struct btrfs_key *key,
1978 struct btrfs_ioctl_search_key *sk,
1979 size_t *buf_size,
1980 char __user *ubuf,
1981 unsigned long *sk_offset,
1982 int *num_found)
1984 u64 found_transid;
1985 struct extent_buffer *leaf;
1986 struct btrfs_ioctl_search_header sh;
1987 struct btrfs_key test;
1988 unsigned long item_off;
1989 unsigned long item_len;
1990 int nritems;
1991 int i;
1992 int slot;
1993 int ret = 0;
1995 leaf = path->nodes[0];
1996 slot = path->slots[0];
1997 nritems = btrfs_header_nritems(leaf);
1999 if (btrfs_header_generation(leaf) > sk->max_transid) {
2000 i = nritems;
2001 goto advance_key;
2003 found_transid = btrfs_header_generation(leaf);
2005 for (i = slot; i < nritems; i++) {
2006 item_off = btrfs_item_ptr_offset(leaf, i);
2007 item_len = btrfs_item_size_nr(leaf, i);
2009 btrfs_item_key_to_cpu(leaf, key, i);
2010 if (!key_in_sk(key, sk))
2011 continue;
2013 if (sizeof(sh) + item_len > *buf_size) {
2014 if (*num_found) {
2015 ret = 1;
2016 goto out;
2020 * return one empty item back for v1, which does not
2021 * handle -EOVERFLOW
2024 *buf_size = sizeof(sh) + item_len;
2025 item_len = 0;
2026 ret = -EOVERFLOW;
2029 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2030 ret = 1;
2031 goto out;
2034 sh.objectid = key->objectid;
2035 sh.offset = key->offset;
2036 sh.type = key->type;
2037 sh.len = item_len;
2038 sh.transid = found_transid;
2041 * Copy search result header. If we fault then loop again so we
2042 * can fault in the pages and -EFAULT there if there's a
2043 * problem. Otherwise we'll fault and then copy the buffer in
2044 * properly this next time through
2046 if (probe_user_write(ubuf + *sk_offset, &sh, sizeof(sh))) {
2047 ret = 0;
2048 goto out;
2051 *sk_offset += sizeof(sh);
2053 if (item_len) {
2054 char __user *up = ubuf + *sk_offset;
2056 * Copy the item, same behavior as above, but reset the
2057 * * sk_offset so we copy the full thing again.
2059 if (read_extent_buffer_to_user_nofault(leaf, up,
2060 item_off, item_len)) {
2061 ret = 0;
2062 *sk_offset -= sizeof(sh);
2063 goto out;
2066 *sk_offset += item_len;
2068 (*num_found)++;
2070 if (ret) /* -EOVERFLOW from above */
2071 goto out;
2073 if (*num_found >= sk->nr_items) {
2074 ret = 1;
2075 goto out;
2078 advance_key:
2079 ret = 0;
2080 test.objectid = sk->max_objectid;
2081 test.type = sk->max_type;
2082 test.offset = sk->max_offset;
2083 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2084 ret = 1;
2085 else if (key->offset < (u64)-1)
2086 key->offset++;
2087 else if (key->type < (u8)-1) {
2088 key->offset = 0;
2089 key->type++;
2090 } else if (key->objectid < (u64)-1) {
2091 key->offset = 0;
2092 key->type = 0;
2093 key->objectid++;
2094 } else
2095 ret = 1;
2096 out:
2098 * 0: all items from this leaf copied, continue with next
2099 * 1: * more items can be copied, but unused buffer is too small
2100 * * all items were found
2101 * Either way, it will stops the loop which iterates to the next
2102 * leaf
2103 * -EOVERFLOW: item was to large for buffer
2104 * -EFAULT: could not copy extent buffer back to userspace
2106 return ret;
2109 static noinline int search_ioctl(struct inode *inode,
2110 struct btrfs_ioctl_search_key *sk,
2111 size_t *buf_size,
2112 char __user *ubuf)
2114 struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2115 struct btrfs_root *root;
2116 struct btrfs_key key;
2117 struct btrfs_path *path;
2118 int ret;
2119 int num_found = 0;
2120 unsigned long sk_offset = 0;
2122 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2123 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2124 return -EOVERFLOW;
2127 path = btrfs_alloc_path();
2128 if (!path)
2129 return -ENOMEM;
2131 if (sk->tree_id == 0) {
2132 /* search the root of the inode that was passed */
2133 root = BTRFS_I(inode)->root;
2134 } else {
2135 key.objectid = sk->tree_id;
2136 key.type = BTRFS_ROOT_ITEM_KEY;
2137 key.offset = (u64)-1;
2138 root = btrfs_read_fs_root_no_name(info, &key);
2139 if (IS_ERR(root)) {
2140 btrfs_free_path(path);
2141 return -ENOENT;
2145 key.objectid = sk->min_objectid;
2146 key.type = sk->min_type;
2147 key.offset = sk->min_offset;
2149 while (1) {
2150 ret = fault_in_pages_writeable(ubuf + sk_offset,
2151 *buf_size - sk_offset);
2152 if (ret)
2153 break;
2155 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2156 if (ret != 0) {
2157 if (ret > 0)
2158 ret = 0;
2159 goto err;
2161 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2162 &sk_offset, &num_found);
2163 btrfs_release_path(path);
2164 if (ret)
2165 break;
2168 if (ret > 0)
2169 ret = 0;
2170 err:
2171 sk->nr_items = num_found;
2172 btrfs_free_path(path);
2173 return ret;
2176 static noinline int btrfs_ioctl_tree_search(struct file *file,
2177 void __user *argp)
2179 struct btrfs_ioctl_search_args __user *uargs;
2180 struct btrfs_ioctl_search_key sk;
2181 struct inode *inode;
2182 int ret;
2183 size_t buf_size;
2185 if (!capable(CAP_SYS_ADMIN))
2186 return -EPERM;
2188 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2190 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2191 return -EFAULT;
2193 buf_size = sizeof(uargs->buf);
2195 inode = file_inode(file);
2196 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2199 * In the origin implementation an overflow is handled by returning a
2200 * search header with a len of zero, so reset ret.
2202 if (ret == -EOVERFLOW)
2203 ret = 0;
2205 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2206 ret = -EFAULT;
2207 return ret;
2210 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2211 void __user *argp)
2213 struct btrfs_ioctl_search_args_v2 __user *uarg;
2214 struct btrfs_ioctl_search_args_v2 args;
2215 struct inode *inode;
2216 int ret;
2217 size_t buf_size;
2218 const size_t buf_limit = SZ_16M;
2220 if (!capable(CAP_SYS_ADMIN))
2221 return -EPERM;
2223 /* copy search header and buffer size */
2224 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2225 if (copy_from_user(&args, uarg, sizeof(args)))
2226 return -EFAULT;
2228 buf_size = args.buf_size;
2230 /* limit result size to 16MB */
2231 if (buf_size > buf_limit)
2232 buf_size = buf_limit;
2234 inode = file_inode(file);
2235 ret = search_ioctl(inode, &args.key, &buf_size,
2236 (char *)(&uarg->buf[0]));
2237 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2238 ret = -EFAULT;
2239 else if (ret == -EOVERFLOW &&
2240 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2241 ret = -EFAULT;
2243 return ret;
2247 * Search INODE_REFs to identify path name of 'dirid' directory
2248 * in a 'tree_id' tree. and sets path name to 'name'.
2250 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2251 u64 tree_id, u64 dirid, char *name)
2253 struct btrfs_root *root;
2254 struct btrfs_key key;
2255 char *ptr;
2256 int ret = -1;
2257 int slot;
2258 int len;
2259 int total_len = 0;
2260 struct btrfs_inode_ref *iref;
2261 struct extent_buffer *l;
2262 struct btrfs_path *path;
2264 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2265 name[0]='\0';
2266 return 0;
2269 path = btrfs_alloc_path();
2270 if (!path)
2271 return -ENOMEM;
2273 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2275 key.objectid = tree_id;
2276 key.type = BTRFS_ROOT_ITEM_KEY;
2277 key.offset = (u64)-1;
2278 root = btrfs_read_fs_root_no_name(info, &key);
2279 if (IS_ERR(root)) {
2280 btrfs_err(info, "could not find root %llu", tree_id);
2281 ret = -ENOENT;
2282 goto out;
2285 key.objectid = dirid;
2286 key.type = BTRFS_INODE_REF_KEY;
2287 key.offset = (u64)-1;
2289 while (1) {
2290 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2291 if (ret < 0)
2292 goto out;
2293 else if (ret > 0) {
2294 ret = btrfs_previous_item(root, path, dirid,
2295 BTRFS_INODE_REF_KEY);
2296 if (ret < 0)
2297 goto out;
2298 else if (ret > 0) {
2299 ret = -ENOENT;
2300 goto out;
2304 l = path->nodes[0];
2305 slot = path->slots[0];
2306 btrfs_item_key_to_cpu(l, &key, slot);
2308 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2309 len = btrfs_inode_ref_name_len(l, iref);
2310 ptr -= len + 1;
2311 total_len += len + 1;
2312 if (ptr < name) {
2313 ret = -ENAMETOOLONG;
2314 goto out;
2317 *(ptr + len) = '/';
2318 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2320 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2321 break;
2323 btrfs_release_path(path);
2324 key.objectid = key.offset;
2325 key.offset = (u64)-1;
2326 dirid = key.objectid;
2328 memmove(name, ptr, total_len);
2329 name[total_len] = '\0';
2330 ret = 0;
2331 out:
2332 btrfs_free_path(path);
2333 return ret;
2336 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2337 void __user *argp)
2339 struct btrfs_ioctl_ino_lookup_args *args;
2340 struct inode *inode;
2341 int ret = 0;
2343 args = memdup_user(argp, sizeof(*args));
2344 if (IS_ERR(args))
2345 return PTR_ERR(args);
2347 inode = file_inode(file);
2350 * Unprivileged query to obtain the containing subvolume root id. The
2351 * path is reset so it's consistent with btrfs_search_path_in_tree.
2353 if (args->treeid == 0)
2354 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2356 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2357 args->name[0] = 0;
2358 goto out;
2361 if (!capable(CAP_SYS_ADMIN)) {
2362 ret = -EPERM;
2363 goto out;
2366 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2367 args->treeid, args->objectid,
2368 args->name);
2370 out:
2371 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2372 ret = -EFAULT;
2374 kfree(args);
2375 return ret;
2378 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2379 void __user *arg)
2381 struct dentry *parent = file->f_path.dentry;
2382 struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2383 struct dentry *dentry;
2384 struct inode *dir = d_inode(parent);
2385 struct inode *inode;
2386 struct btrfs_root *root = BTRFS_I(dir)->root;
2387 struct btrfs_root *dest = NULL;
2388 struct btrfs_ioctl_vol_args *vol_args;
2389 struct btrfs_trans_handle *trans;
2390 struct btrfs_block_rsv block_rsv;
2391 u64 root_flags;
2392 u64 qgroup_reserved;
2393 int namelen;
2394 int ret;
2395 int err = 0;
2397 if (!S_ISDIR(dir->i_mode))
2398 return -ENOTDIR;
2400 vol_args = memdup_user(arg, sizeof(*vol_args));
2401 if (IS_ERR(vol_args))
2402 return PTR_ERR(vol_args);
2404 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2405 namelen = strlen(vol_args->name);
2406 if (strchr(vol_args->name, '/') ||
2407 strncmp(vol_args->name, "..", namelen) == 0) {
2408 err = -EINVAL;
2409 goto out;
2412 err = mnt_want_write_file(file);
2413 if (err)
2414 goto out;
2417 err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
2418 if (err == -EINTR)
2419 goto out_drop_write;
2420 dentry = lookup_one_len(vol_args->name, parent, namelen);
2421 if (IS_ERR(dentry)) {
2422 err = PTR_ERR(dentry);
2423 goto out_unlock_dir;
2426 if (d_really_is_negative(dentry)) {
2427 err = -ENOENT;
2428 goto out_dput;
2431 inode = d_inode(dentry);
2432 dest = BTRFS_I(inode)->root;
2433 if (!capable(CAP_SYS_ADMIN)) {
2435 * Regular user. Only allow this with a special mount
2436 * option, when the user has write+exec access to the
2437 * subvol root, and when rmdir(2) would have been
2438 * allowed.
2440 * Note that this is _not_ check that the subvol is
2441 * empty or doesn't contain data that we wouldn't
2442 * otherwise be able to delete.
2444 * Users who want to delete empty subvols should try
2445 * rmdir(2).
2447 err = -EPERM;
2448 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
2449 goto out_dput;
2452 * Do not allow deletion if the parent dir is the same
2453 * as the dir to be deleted. That means the ioctl
2454 * must be called on the dentry referencing the root
2455 * of the subvol, not a random directory contained
2456 * within it.
2458 err = -EINVAL;
2459 if (root == dest)
2460 goto out_dput;
2462 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2463 if (err)
2464 goto out_dput;
2467 /* check if subvolume may be deleted by a user */
2468 err = btrfs_may_delete(dir, dentry, 1);
2469 if (err)
2470 goto out_dput;
2472 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2473 err = -EINVAL;
2474 goto out_dput;
2477 inode_lock(inode);
2480 * Don't allow to delete a subvolume with send in progress. This is
2481 * inside the i_mutex so the error handling that has to drop the bit
2482 * again is not run concurrently.
2484 spin_lock(&dest->root_item_lock);
2485 root_flags = btrfs_root_flags(&dest->root_item);
2486 if (dest->send_in_progress == 0) {
2487 btrfs_set_root_flags(&dest->root_item,
2488 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2489 spin_unlock(&dest->root_item_lock);
2490 } else {
2491 spin_unlock(&dest->root_item_lock);
2492 btrfs_warn(fs_info,
2493 "Attempt to delete subvolume %llu during send",
2494 dest->root_key.objectid);
2495 err = -EPERM;
2496 goto out_unlock_inode;
2499 down_write(&fs_info->subvol_sem);
2501 err = may_destroy_subvol(dest);
2502 if (err)
2503 goto out_up_write;
2505 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2507 * One for dir inode, two for dir entries, two for root
2508 * ref/backref.
2510 err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2511 5, &qgroup_reserved, true);
2512 if (err)
2513 goto out_up_write;
2515 trans = btrfs_start_transaction(root, 0);
2516 if (IS_ERR(trans)) {
2517 err = PTR_ERR(trans);
2518 goto out_release;
2520 trans->block_rsv = &block_rsv;
2521 trans->bytes_reserved = block_rsv.size;
2523 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
2525 ret = btrfs_unlink_subvol(trans, root, dir,
2526 dest->root_key.objectid,
2527 dentry->d_name.name,
2528 dentry->d_name.len);
2529 if (ret) {
2530 err = ret;
2531 btrfs_abort_transaction(trans, ret);
2532 goto out_end_trans;
2535 btrfs_record_root_in_trans(trans, dest);
2537 memset(&dest->root_item.drop_progress, 0,
2538 sizeof(dest->root_item.drop_progress));
2539 dest->root_item.drop_level = 0;
2540 btrfs_set_root_refs(&dest->root_item, 0);
2542 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
2543 ret = btrfs_insert_orphan_item(trans,
2544 fs_info->tree_root,
2545 dest->root_key.objectid);
2546 if (ret) {
2547 btrfs_abort_transaction(trans, ret);
2548 err = ret;
2549 goto out_end_trans;
2553 ret = btrfs_uuid_tree_rem(trans, fs_info, dest->root_item.uuid,
2554 BTRFS_UUID_KEY_SUBVOL,
2555 dest->root_key.objectid);
2556 if (ret && ret != -ENOENT) {
2557 btrfs_abort_transaction(trans, ret);
2558 err = ret;
2559 goto out_end_trans;
2561 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2562 ret = btrfs_uuid_tree_rem(trans, fs_info,
2563 dest->root_item.received_uuid,
2564 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2565 dest->root_key.objectid);
2566 if (ret && ret != -ENOENT) {
2567 btrfs_abort_transaction(trans, ret);
2568 err = ret;
2569 goto out_end_trans;
2573 out_end_trans:
2574 trans->block_rsv = NULL;
2575 trans->bytes_reserved = 0;
2576 ret = btrfs_end_transaction(trans);
2577 if (ret && !err)
2578 err = ret;
2579 inode->i_flags |= S_DEAD;
2580 out_release:
2581 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
2582 out_up_write:
2583 up_write(&fs_info->subvol_sem);
2584 if (err) {
2585 spin_lock(&dest->root_item_lock);
2586 root_flags = btrfs_root_flags(&dest->root_item);
2587 btrfs_set_root_flags(&dest->root_item,
2588 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2589 spin_unlock(&dest->root_item_lock);
2591 out_unlock_inode:
2592 inode_unlock(inode);
2593 if (!err) {
2594 d_invalidate(dentry);
2595 btrfs_invalidate_inodes(dest);
2596 d_delete(dentry);
2597 ASSERT(dest->send_in_progress == 0);
2599 /* the last ref */
2600 if (dest->ino_cache_inode) {
2601 iput(dest->ino_cache_inode);
2602 dest->ino_cache_inode = NULL;
2605 out_dput:
2606 dput(dentry);
2607 out_unlock_dir:
2608 inode_unlock(dir);
2609 out_drop_write:
2610 mnt_drop_write_file(file);
2611 out:
2612 kfree(vol_args);
2613 return err;
2616 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2618 struct inode *inode = file_inode(file);
2619 struct btrfs_root *root = BTRFS_I(inode)->root;
2620 struct btrfs_ioctl_defrag_range_args *range;
2621 int ret;
2623 ret = mnt_want_write_file(file);
2624 if (ret)
2625 return ret;
2627 if (btrfs_root_readonly(root)) {
2628 ret = -EROFS;
2629 goto out;
2632 switch (inode->i_mode & S_IFMT) {
2633 case S_IFDIR:
2634 if (!capable(CAP_SYS_ADMIN)) {
2635 ret = -EPERM;
2636 goto out;
2638 ret = btrfs_defrag_root(root);
2639 break;
2640 case S_IFREG:
2641 if (!(file->f_mode & FMODE_WRITE)) {
2642 ret = -EINVAL;
2643 goto out;
2646 range = kzalloc(sizeof(*range), GFP_KERNEL);
2647 if (!range) {
2648 ret = -ENOMEM;
2649 goto out;
2652 if (argp) {
2653 if (copy_from_user(range, argp,
2654 sizeof(*range))) {
2655 ret = -EFAULT;
2656 kfree(range);
2657 goto out;
2659 /* compression requires us to start the IO */
2660 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2661 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2662 range->extent_thresh = (u32)-1;
2664 } else {
2665 /* the rest are all set to zero by kzalloc */
2666 range->len = (u64)-1;
2668 ret = btrfs_defrag_file(file_inode(file), file,
2669 range, 0, 0);
2670 if (ret > 0)
2671 ret = 0;
2672 kfree(range);
2673 break;
2674 default:
2675 ret = -EINVAL;
2677 out:
2678 mnt_drop_write_file(file);
2679 return ret;
2682 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2684 struct btrfs_ioctl_vol_args *vol_args;
2685 int ret;
2687 if (!capable(CAP_SYS_ADMIN))
2688 return -EPERM;
2690 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2691 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2693 mutex_lock(&fs_info->volume_mutex);
2694 vol_args = memdup_user(arg, sizeof(*vol_args));
2695 if (IS_ERR(vol_args)) {
2696 ret = PTR_ERR(vol_args);
2697 goto out;
2700 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2701 ret = btrfs_init_new_device(fs_info, vol_args->name);
2703 if (!ret)
2704 btrfs_info(fs_info, "disk added %s", vol_args->name);
2706 kfree(vol_args);
2707 out:
2708 mutex_unlock(&fs_info->volume_mutex);
2709 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2710 return ret;
2713 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2715 struct inode *inode = file_inode(file);
2716 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2717 struct btrfs_ioctl_vol_args_v2 *vol_args;
2718 int ret;
2720 if (!capable(CAP_SYS_ADMIN))
2721 return -EPERM;
2723 ret = mnt_want_write_file(file);
2724 if (ret)
2725 return ret;
2727 vol_args = memdup_user(arg, sizeof(*vol_args));
2728 if (IS_ERR(vol_args)) {
2729 ret = PTR_ERR(vol_args);
2730 goto err_drop;
2733 /* Check for compatibility reject unknown flags */
2734 if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
2735 ret = -EOPNOTSUPP;
2736 goto out;
2739 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2740 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2741 goto out;
2744 mutex_lock(&fs_info->volume_mutex);
2745 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
2746 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
2747 } else {
2748 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
2749 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2751 mutex_unlock(&fs_info->volume_mutex);
2752 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2754 if (!ret) {
2755 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
2756 btrfs_info(fs_info, "device deleted: id %llu",
2757 vol_args->devid);
2758 else
2759 btrfs_info(fs_info, "device deleted: %s",
2760 vol_args->name);
2762 out:
2763 kfree(vol_args);
2764 err_drop:
2765 mnt_drop_write_file(file);
2766 return ret;
2769 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2771 struct inode *inode = file_inode(file);
2772 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2773 struct btrfs_ioctl_vol_args *vol_args;
2774 int ret;
2776 if (!capable(CAP_SYS_ADMIN))
2777 return -EPERM;
2779 ret = mnt_want_write_file(file);
2780 if (ret)
2781 return ret;
2783 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2784 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2785 goto out_drop_write;
2788 vol_args = memdup_user(arg, sizeof(*vol_args));
2789 if (IS_ERR(vol_args)) {
2790 ret = PTR_ERR(vol_args);
2791 goto out;
2794 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2795 mutex_lock(&fs_info->volume_mutex);
2796 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2797 mutex_unlock(&fs_info->volume_mutex);
2799 if (!ret)
2800 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2801 kfree(vol_args);
2802 out:
2803 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2804 out_drop_write:
2805 mnt_drop_write_file(file);
2807 return ret;
2810 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
2811 void __user *arg)
2813 struct btrfs_ioctl_fs_info_args *fi_args;
2814 struct btrfs_device *device;
2815 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2816 int ret = 0;
2818 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2819 if (!fi_args)
2820 return -ENOMEM;
2822 mutex_lock(&fs_devices->device_list_mutex);
2823 fi_args->num_devices = fs_devices->num_devices;
2824 memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2826 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2827 if (device->devid > fi_args->max_id)
2828 fi_args->max_id = device->devid;
2830 mutex_unlock(&fs_devices->device_list_mutex);
2832 fi_args->nodesize = fs_info->nodesize;
2833 fi_args->sectorsize = fs_info->sectorsize;
2834 fi_args->clone_alignment = fs_info->sectorsize;
2836 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2837 ret = -EFAULT;
2839 kfree(fi_args);
2840 return ret;
2843 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
2844 void __user *arg)
2846 struct btrfs_ioctl_dev_info_args *di_args;
2847 struct btrfs_device *dev;
2848 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2849 int ret = 0;
2850 char *s_uuid = NULL;
2852 di_args = memdup_user(arg, sizeof(*di_args));
2853 if (IS_ERR(di_args))
2854 return PTR_ERR(di_args);
2856 if (!btrfs_is_empty_uuid(di_args->uuid))
2857 s_uuid = di_args->uuid;
2859 mutex_lock(&fs_devices->device_list_mutex);
2860 dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2862 if (!dev) {
2863 ret = -ENODEV;
2864 goto out;
2867 di_args->devid = dev->devid;
2868 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
2869 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2870 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2871 if (dev->name) {
2872 struct rcu_string *name;
2874 rcu_read_lock();
2875 name = rcu_dereference(dev->name);
2876 strncpy(di_args->path, name->str, sizeof(di_args->path));
2877 rcu_read_unlock();
2878 di_args->path[sizeof(di_args->path) - 1] = 0;
2879 } else {
2880 di_args->path[0] = '\0';
2883 out:
2884 mutex_unlock(&fs_devices->device_list_mutex);
2885 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2886 ret = -EFAULT;
2888 kfree(di_args);
2889 return ret;
2892 static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2894 struct page *page;
2896 page = grab_cache_page(inode->i_mapping, index);
2897 if (!page)
2898 return ERR_PTR(-ENOMEM);
2900 if (!PageUptodate(page)) {
2901 int ret;
2903 ret = btrfs_readpage(NULL, page);
2904 if (ret)
2905 return ERR_PTR(ret);
2906 lock_page(page);
2907 if (!PageUptodate(page)) {
2908 unlock_page(page);
2909 put_page(page);
2910 return ERR_PTR(-EIO);
2912 if (page->mapping != inode->i_mapping) {
2913 unlock_page(page);
2914 put_page(page);
2915 return ERR_PTR(-EAGAIN);
2919 return page;
2922 static int gather_extent_pages(struct inode *inode, struct page **pages,
2923 int num_pages, u64 off)
2925 int i;
2926 pgoff_t index = off >> PAGE_SHIFT;
2928 for (i = 0; i < num_pages; i++) {
2929 again:
2930 pages[i] = extent_same_get_page(inode, index + i);
2931 if (IS_ERR(pages[i])) {
2932 int err = PTR_ERR(pages[i]);
2934 if (err == -EAGAIN)
2935 goto again;
2936 pages[i] = NULL;
2937 return err;
2940 return 0;
2943 static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2944 bool retry_range_locking)
2947 * Do any pending delalloc/csum calculations on inode, one way or
2948 * another, and lock file content.
2949 * The locking order is:
2951 * 1) pages
2952 * 2) range in the inode's io tree
2954 while (1) {
2955 struct btrfs_ordered_extent *ordered;
2956 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2957 ordered = btrfs_lookup_first_ordered_extent(inode,
2958 off + len - 1);
2959 if ((!ordered ||
2960 ordered->file_offset + ordered->len <= off ||
2961 ordered->file_offset >= off + len) &&
2962 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2963 off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2964 if (ordered)
2965 btrfs_put_ordered_extent(ordered);
2966 break;
2968 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2969 if (ordered)
2970 btrfs_put_ordered_extent(ordered);
2971 if (!retry_range_locking)
2972 return -EAGAIN;
2973 btrfs_wait_ordered_range(inode, off, len);
2975 return 0;
2978 static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2980 inode_unlock(inode1);
2981 inode_unlock(inode2);
2984 static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2986 if (inode1 < inode2)
2987 swap(inode1, inode2);
2989 inode_lock_nested(inode1, I_MUTEX_PARENT);
2990 inode_lock_nested(inode2, I_MUTEX_CHILD);
2993 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2994 struct inode *inode2, u64 loff2, u64 len)
2996 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2997 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3000 static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3001 struct inode *inode2, u64 loff2, u64 len,
3002 bool retry_range_locking)
3004 int ret;
3006 if (inode1 < inode2) {
3007 swap(inode1, inode2);
3008 swap(loff1, loff2);
3010 ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
3011 if (ret)
3012 return ret;
3013 ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
3014 if (ret)
3015 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
3016 loff1 + len - 1);
3017 return ret;
3020 struct cmp_pages {
3021 int num_pages;
3022 struct page **src_pages;
3023 struct page **dst_pages;
3026 static void btrfs_cmp_data_free(struct cmp_pages *cmp)
3028 int i;
3029 struct page *pg;
3031 for (i = 0; i < cmp->num_pages; i++) {
3032 pg = cmp->src_pages[i];
3033 if (pg) {
3034 unlock_page(pg);
3035 put_page(pg);
3037 pg = cmp->dst_pages[i];
3038 if (pg) {
3039 unlock_page(pg);
3040 put_page(pg);
3043 kfree(cmp->src_pages);
3044 kfree(cmp->dst_pages);
3047 static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
3048 struct inode *dst, u64 dst_loff,
3049 u64 len, struct cmp_pages *cmp)
3051 int ret;
3052 int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
3053 struct page **src_pgarr, **dst_pgarr;
3056 * We must gather up all the pages before we initiate our
3057 * extent locking. We use an array for the page pointers. Size
3058 * of the array is bounded by len, which is in turn bounded by
3059 * BTRFS_MAX_DEDUPE_LEN.
3061 src_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
3062 dst_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
3063 if (!src_pgarr || !dst_pgarr) {
3064 kfree(src_pgarr);
3065 kfree(dst_pgarr);
3066 return -ENOMEM;
3068 cmp->num_pages = num_pages;
3069 cmp->src_pages = src_pgarr;
3070 cmp->dst_pages = dst_pgarr;
3073 * If deduping ranges in the same inode, locking rules make it mandatory
3074 * to always lock pages in ascending order to avoid deadlocks with
3075 * concurrent tasks (such as starting writeback/delalloc).
3077 if (src == dst && dst_loff < loff) {
3078 swap(src_pgarr, dst_pgarr);
3079 swap(loff, dst_loff);
3082 ret = gather_extent_pages(src, src_pgarr, cmp->num_pages, loff);
3083 if (ret)
3084 goto out;
3086 ret = gather_extent_pages(dst, dst_pgarr, cmp->num_pages, dst_loff);
3088 out:
3089 if (ret)
3090 btrfs_cmp_data_free(cmp);
3091 return ret;
3094 static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
3096 int ret = 0;
3097 int i;
3098 struct page *src_page, *dst_page;
3099 unsigned int cmp_len = PAGE_SIZE;
3100 void *addr, *dst_addr;
3102 i = 0;
3103 while (len) {
3104 if (len < PAGE_SIZE)
3105 cmp_len = len;
3107 BUG_ON(i >= cmp->num_pages);
3109 src_page = cmp->src_pages[i];
3110 dst_page = cmp->dst_pages[i];
3111 ASSERT(PageLocked(src_page));
3112 ASSERT(PageLocked(dst_page));
3114 addr = kmap_atomic(src_page);
3115 dst_addr = kmap_atomic(dst_page);
3117 flush_dcache_page(src_page);
3118 flush_dcache_page(dst_page);
3120 if (memcmp(addr, dst_addr, cmp_len))
3121 ret = -EBADE;
3123 kunmap_atomic(addr);
3124 kunmap_atomic(dst_addr);
3126 if (ret)
3127 break;
3129 len -= cmp_len;
3130 i++;
3133 return ret;
3136 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3137 u64 olen)
3139 u64 len = *plen;
3140 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3142 if (off + olen > inode->i_size || off + olen < off)
3143 return -EINVAL;
3145 /* if we extend to eof, continue to block boundary */
3146 if (off + len == inode->i_size)
3147 *plen = len = ALIGN(inode->i_size, bs) - off;
3149 /* Check that we are block aligned - btrfs_clone() requires this */
3150 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3151 return -EINVAL;
3153 return 0;
3156 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3157 struct inode *dst, u64 dst_loff)
3159 int ret;
3160 u64 len = olen;
3161 struct cmp_pages cmp;
3162 bool same_inode = (src == dst);
3163 u64 same_lock_start = 0;
3164 u64 same_lock_len = 0;
3166 if (len == 0)
3167 return 0;
3169 if (same_inode)
3170 inode_lock(src);
3171 else
3172 btrfs_double_inode_lock(src, dst);
3174 ret = extent_same_check_offsets(src, loff, &len, olen);
3175 if (ret)
3176 goto out_unlock;
3178 ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3179 if (ret)
3180 goto out_unlock;
3182 if (same_inode) {
3184 * Single inode case wants the same checks, except we
3185 * don't want our length pushed out past i_size as
3186 * comparing that data range makes no sense.
3188 * extent_same_check_offsets() will do this for an
3189 * unaligned length at i_size, so catch it here and
3190 * reject the request.
3192 * This effectively means we require aligned extents
3193 * for the single-inode case, whereas the other cases
3194 * allow an unaligned length so long as it ends at
3195 * i_size.
3197 if (len != olen) {
3198 ret = -EINVAL;
3199 goto out_unlock;
3202 /* Check for overlapping ranges */
3203 if (dst_loff + len > loff && dst_loff < loff + len) {
3204 ret = -EINVAL;
3205 goto out_unlock;
3208 same_lock_start = min_t(u64, loff, dst_loff);
3209 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
3210 } else {
3212 * If the source and destination inodes are different, the
3213 * source's range end offset matches the source's i_size, that
3214 * i_size is not a multiple of the sector size, and the
3215 * destination range does not go past the destination's i_size,
3216 * we must round down the length to the nearest sector size
3217 * multiple. If we don't do this adjustment we end replacing
3218 * with zeroes the bytes in the range that starts at the
3219 * deduplication range's end offset and ends at the next sector
3220 * size multiple.
3222 if (loff + olen == i_size_read(src) &&
3223 dst_loff + len < i_size_read(dst)) {
3224 const u64 sz = BTRFS_I(src)->root->fs_info->sectorsize;
3226 len = round_down(i_size_read(src), sz) - loff;
3227 if (len == 0)
3228 return 0;
3229 olen = len;
3233 /* don't make the dst file partly checksummed */
3234 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3235 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3236 ret = -EINVAL;
3237 goto out_unlock;
3240 again:
3241 ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3242 if (ret)
3243 goto out_unlock;
3245 if (same_inode)
3246 ret = lock_extent_range(src, same_lock_start, same_lock_len,
3247 false);
3248 else
3249 ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3250 false);
3252 * If one of the inodes has dirty pages in the respective range or
3253 * ordered extents, we need to flush dellaloc and wait for all ordered
3254 * extents in the range. We must unlock the pages and the ranges in the
3255 * io trees to avoid deadlocks when flushing delalloc (requires locking
3256 * pages) and when waiting for ordered extents to complete (they require
3257 * range locking).
3259 if (ret == -EAGAIN) {
3261 * Ranges in the io trees already unlocked. Now unlock all
3262 * pages before waiting for all IO to complete.
3264 btrfs_cmp_data_free(&cmp);
3265 if (same_inode) {
3266 btrfs_wait_ordered_range(src, same_lock_start,
3267 same_lock_len);
3268 } else {
3269 btrfs_wait_ordered_range(src, loff, len);
3270 btrfs_wait_ordered_range(dst, dst_loff, len);
3272 goto again;
3274 ASSERT(ret == 0);
3275 if (WARN_ON(ret)) {
3276 /* ranges in the io trees already unlocked */
3277 btrfs_cmp_data_free(&cmp);
3278 return ret;
3281 /* pass original length for comparison so we stay within i_size */
3282 ret = btrfs_cmp_data(olen, &cmp);
3283 if (ret == 0)
3284 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3286 if (same_inode)
3287 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3288 same_lock_start + same_lock_len - 1);
3289 else
3290 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3292 btrfs_cmp_data_free(&cmp);
3293 out_unlock:
3294 if (same_inode)
3295 inode_unlock(src);
3296 else
3297 btrfs_double_inode_unlock(src, dst);
3299 return ret;
3302 #define BTRFS_MAX_DEDUPE_LEN SZ_16M
3304 ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
3305 struct file *dst_file, u64 dst_loff)
3307 struct inode *src = file_inode(src_file);
3308 struct inode *dst = file_inode(dst_file);
3309 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3310 ssize_t res;
3312 if (olen > BTRFS_MAX_DEDUPE_LEN)
3313 olen = BTRFS_MAX_DEDUPE_LEN;
3315 if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3317 * Btrfs does not support blocksize < page_size. As a
3318 * result, btrfs_cmp_data() won't correctly handle
3319 * this situation without an update.
3321 return -EINVAL;
3324 res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
3325 if (res)
3326 return res;
3327 return olen;
3330 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3331 struct inode *inode,
3332 u64 endoff,
3333 const u64 destoff,
3334 const u64 olen,
3335 int no_time_update)
3337 struct btrfs_root *root = BTRFS_I(inode)->root;
3338 int ret;
3340 inode_inc_iversion(inode);
3341 if (!no_time_update)
3342 inode->i_mtime = inode->i_ctime = current_time(inode);
3344 * We round up to the block size at eof when determining which
3345 * extents to clone above, but shouldn't round up the file size.
3347 if (endoff > destoff + olen)
3348 endoff = destoff + olen;
3349 if (endoff > inode->i_size)
3350 btrfs_i_size_write(BTRFS_I(inode), endoff);
3352 ret = btrfs_update_inode(trans, root, inode);
3353 if (ret) {
3354 btrfs_abort_transaction(trans, ret);
3355 btrfs_end_transaction(trans);
3356 goto out;
3358 ret = btrfs_end_transaction(trans);
3359 out:
3360 return ret;
3363 static void clone_update_extent_map(struct btrfs_inode *inode,
3364 const struct btrfs_trans_handle *trans,
3365 const struct btrfs_path *path,
3366 const u64 hole_offset,
3367 const u64 hole_len)
3369 struct extent_map_tree *em_tree = &inode->extent_tree;
3370 struct extent_map *em;
3371 int ret;
3373 em = alloc_extent_map();
3374 if (!em) {
3375 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3376 return;
3379 if (path) {
3380 struct btrfs_file_extent_item *fi;
3382 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3383 struct btrfs_file_extent_item);
3384 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
3385 em->generation = -1;
3386 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3387 BTRFS_FILE_EXTENT_INLINE)
3388 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3389 &inode->runtime_flags);
3390 } else {
3391 em->start = hole_offset;
3392 em->len = hole_len;
3393 em->ram_bytes = em->len;
3394 em->orig_start = hole_offset;
3395 em->block_start = EXTENT_MAP_HOLE;
3396 em->block_len = 0;
3397 em->orig_block_len = 0;
3398 em->compress_type = BTRFS_COMPRESS_NONE;
3399 em->generation = trans->transid;
3402 while (1) {
3403 write_lock(&em_tree->lock);
3404 ret = add_extent_mapping(em_tree, em, 1);
3405 write_unlock(&em_tree->lock);
3406 if (ret != -EEXIST) {
3407 free_extent_map(em);
3408 break;
3410 btrfs_drop_extent_cache(inode, em->start,
3411 em->start + em->len - 1, 0);
3414 if (ret)
3415 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3419 * Make sure we do not end up inserting an inline extent into a file that has
3420 * already other (non-inline) extents. If a file has an inline extent it can
3421 * not have any other extents and the (single) inline extent must start at the
3422 * file offset 0. Failing to respect these rules will lead to file corruption,
3423 * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3425 * We can have extents that have been already written to disk or we can have
3426 * dirty ranges still in delalloc, in which case the extent maps and items are
3427 * created only when we run delalloc, and the delalloc ranges might fall outside
3428 * the range we are currently locking in the inode's io tree. So we check the
3429 * inode's i_size because of that (i_size updates are done while holding the
3430 * i_mutex, which we are holding here).
3431 * We also check to see if the inode has a size not greater than "datal" but has
3432 * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3433 * protected against such concurrent fallocate calls by the i_mutex).
3435 * If the file has no extents but a size greater than datal, do not allow the
3436 * copy because we would need turn the inline extent into a non-inline one (even
3437 * with NO_HOLES enabled). If we find our destination inode only has one inline
3438 * extent, just overwrite it with the source inline extent if its size is less
3439 * than the source extent's size, or we could copy the source inline extent's
3440 * data into the destination inode's inline extent if the later is greater then
3441 * the former.
3443 static int clone_copy_inline_extent(struct inode *dst,
3444 struct btrfs_trans_handle *trans,
3445 struct btrfs_path *path,
3446 struct btrfs_key *new_key,
3447 const u64 drop_start,
3448 const u64 datal,
3449 const u64 skip,
3450 const u64 size,
3451 char *inline_data)
3453 struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
3454 struct btrfs_root *root = BTRFS_I(dst)->root;
3455 const u64 aligned_end = ALIGN(new_key->offset + datal,
3456 fs_info->sectorsize);
3457 int ret;
3458 struct btrfs_key key;
3460 if (new_key->offset > 0)
3461 return -EOPNOTSUPP;
3463 key.objectid = btrfs_ino(BTRFS_I(dst));
3464 key.type = BTRFS_EXTENT_DATA_KEY;
3465 key.offset = 0;
3466 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3467 if (ret < 0) {
3468 return ret;
3469 } else if (ret > 0) {
3470 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3471 ret = btrfs_next_leaf(root, path);
3472 if (ret < 0)
3473 return ret;
3474 else if (ret > 0)
3475 goto copy_inline_extent;
3477 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3478 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3479 key.type == BTRFS_EXTENT_DATA_KEY) {
3480 ASSERT(key.offset > 0);
3481 return -EOPNOTSUPP;
3483 } else if (i_size_read(dst) <= datal) {
3484 struct btrfs_file_extent_item *ei;
3485 u64 ext_len;
3488 * If the file size is <= datal, make sure there are no other
3489 * extents following (can happen do to an fallocate call with
3490 * the flag FALLOC_FL_KEEP_SIZE).
3492 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3493 struct btrfs_file_extent_item);
3495 * If it's an inline extent, it can not have other extents
3496 * following it.
3498 if (btrfs_file_extent_type(path->nodes[0], ei) ==
3499 BTRFS_FILE_EXTENT_INLINE)
3500 goto copy_inline_extent;
3502 ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3503 if (ext_len > aligned_end)
3504 return -EOPNOTSUPP;
3506 ret = btrfs_next_item(root, path);
3507 if (ret < 0) {
3508 return ret;
3509 } else if (ret == 0) {
3510 btrfs_item_key_to_cpu(path->nodes[0], &key,
3511 path->slots[0]);
3512 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3513 key.type == BTRFS_EXTENT_DATA_KEY)
3514 return -EOPNOTSUPP;
3518 copy_inline_extent:
3520 * We have no extent items, or we have an extent at offset 0 which may
3521 * or may not be inlined. All these cases are dealt the same way.
3523 if (i_size_read(dst) > datal) {
3525 * If the destination inode has an inline extent...
3526 * This would require copying the data from the source inline
3527 * extent into the beginning of the destination's inline extent.
3528 * But this is really complex, both extents can be compressed
3529 * or just one of them, which would require decompressing and
3530 * re-compressing data (which could increase the new compressed
3531 * size, not allowing the compressed data to fit anymore in an
3532 * inline extent).
3533 * So just don't support this case for now (it should be rare,
3534 * we are not really saving space when cloning inline extents).
3536 return -EOPNOTSUPP;
3539 btrfs_release_path(path);
3540 ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3541 if (ret)
3542 return ret;
3543 ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3544 if (ret)
3545 return ret;
3547 if (skip) {
3548 const u32 start = btrfs_file_extent_calc_inline_size(0);
3550 memmove(inline_data + start, inline_data + start + skip, datal);
3553 write_extent_buffer(path->nodes[0], inline_data,
3554 btrfs_item_ptr_offset(path->nodes[0],
3555 path->slots[0]),
3556 size);
3557 inode_add_bytes(dst, datal);
3559 return 0;
3563 * btrfs_clone() - clone a range from inode file to another
3565 * @src: Inode to clone from
3566 * @inode: Inode to clone to
3567 * @off: Offset within source to start clone from
3568 * @olen: Original length, passed by user, of range to clone
3569 * @olen_aligned: Block-aligned value of olen
3570 * @destoff: Offset within @inode to start clone
3571 * @no_time_update: Whether to update mtime/ctime on the target inode
3573 static int btrfs_clone(struct inode *src, struct inode *inode,
3574 const u64 off, const u64 olen, const u64 olen_aligned,
3575 const u64 destoff, int no_time_update)
3577 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3578 struct btrfs_root *root = BTRFS_I(inode)->root;
3579 struct btrfs_path *path = NULL;
3580 struct extent_buffer *leaf;
3581 struct btrfs_trans_handle *trans;
3582 char *buf = NULL;
3583 struct btrfs_key key;
3584 u32 nritems;
3585 int slot;
3586 int ret;
3587 const u64 len = olen_aligned;
3588 u64 last_dest_end = destoff;
3590 ret = -ENOMEM;
3591 buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3592 if (!buf)
3593 return ret;
3595 path = btrfs_alloc_path();
3596 if (!path) {
3597 kvfree(buf);
3598 return ret;
3601 path->reada = READA_FORWARD;
3602 /* clone data */
3603 key.objectid = btrfs_ino(BTRFS_I(src));
3604 key.type = BTRFS_EXTENT_DATA_KEY;
3605 key.offset = off;
3607 while (1) {
3608 u64 next_key_min_offset = key.offset + 1;
3611 * note the key will change type as we walk through the
3612 * tree.
3614 path->leave_spinning = 1;
3615 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3616 0, 0);
3617 if (ret < 0)
3618 goto out;
3620 * First search, if no extent item that starts at offset off was
3621 * found but the previous item is an extent item, it's possible
3622 * it might overlap our target range, therefore process it.
3624 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3625 btrfs_item_key_to_cpu(path->nodes[0], &key,
3626 path->slots[0] - 1);
3627 if (key.type == BTRFS_EXTENT_DATA_KEY)
3628 path->slots[0]--;
3631 nritems = btrfs_header_nritems(path->nodes[0]);
3632 process_slot:
3633 if (path->slots[0] >= nritems) {
3634 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3635 if (ret < 0)
3636 goto out;
3637 if (ret > 0)
3638 break;
3639 nritems = btrfs_header_nritems(path->nodes[0]);
3641 leaf = path->nodes[0];
3642 slot = path->slots[0];
3644 btrfs_item_key_to_cpu(leaf, &key, slot);
3645 if (key.type > BTRFS_EXTENT_DATA_KEY ||
3646 key.objectid != btrfs_ino(BTRFS_I(src)))
3647 break;
3649 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3650 struct btrfs_file_extent_item *extent;
3651 int type;
3652 u32 size;
3653 struct btrfs_key new_key;
3654 u64 disko = 0, diskl = 0;
3655 u64 datao = 0, datal = 0;
3656 u8 comp;
3657 u64 drop_start;
3659 extent = btrfs_item_ptr(leaf, slot,
3660 struct btrfs_file_extent_item);
3661 comp = btrfs_file_extent_compression(leaf, extent);
3662 type = btrfs_file_extent_type(leaf, extent);
3663 if (type == BTRFS_FILE_EXTENT_REG ||
3664 type == BTRFS_FILE_EXTENT_PREALLOC) {
3665 disko = btrfs_file_extent_disk_bytenr(leaf,
3666 extent);
3667 diskl = btrfs_file_extent_disk_num_bytes(leaf,
3668 extent);
3669 datao = btrfs_file_extent_offset(leaf, extent);
3670 datal = btrfs_file_extent_num_bytes(leaf,
3671 extent);
3672 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3673 /* take upper bound, may be compressed */
3674 datal = btrfs_file_extent_ram_bytes(leaf,
3675 extent);
3679 * The first search might have left us at an extent
3680 * item that ends before our target range's start, can
3681 * happen if we have holes and NO_HOLES feature enabled.
3683 if (key.offset + datal <= off) {
3684 path->slots[0]++;
3685 goto process_slot;
3686 } else if (key.offset >= off + len) {
3687 break;
3689 next_key_min_offset = key.offset + datal;
3690 size = btrfs_item_size_nr(leaf, slot);
3691 read_extent_buffer(leaf, buf,
3692 btrfs_item_ptr_offset(leaf, slot),
3693 size);
3695 btrfs_release_path(path);
3696 path->leave_spinning = 0;
3698 memcpy(&new_key, &key, sizeof(new_key));
3699 new_key.objectid = btrfs_ino(BTRFS_I(inode));
3700 if (off <= key.offset)
3701 new_key.offset = key.offset + destoff - off;
3702 else
3703 new_key.offset = destoff;
3706 * Deal with a hole that doesn't have an extent item
3707 * that represents it (NO_HOLES feature enabled).
3708 * This hole is either in the middle of the cloning
3709 * range or at the beginning (fully overlaps it or
3710 * partially overlaps it).
3712 if (new_key.offset != last_dest_end)
3713 drop_start = last_dest_end;
3714 else
3715 drop_start = new_key.offset;
3718 * 1 - adjusting old extent (we may have to split it)
3719 * 1 - add new extent
3720 * 1 - inode update
3722 trans = btrfs_start_transaction(root, 3);
3723 if (IS_ERR(trans)) {
3724 ret = PTR_ERR(trans);
3725 goto out;
3728 if (type == BTRFS_FILE_EXTENT_REG ||
3729 type == BTRFS_FILE_EXTENT_PREALLOC) {
3731 * a | --- range to clone ---| b
3732 * | ------------- extent ------------- |
3735 /* subtract range b */
3736 if (key.offset + datal > off + len)
3737 datal = off + len - key.offset;
3739 /* subtract range a */
3740 if (off > key.offset) {
3741 datao += off - key.offset;
3742 datal -= off - key.offset;
3745 ret = btrfs_drop_extents(trans, root, inode,
3746 drop_start,
3747 new_key.offset + datal,
3749 if (ret) {
3750 if (ret != -EOPNOTSUPP)
3751 btrfs_abort_transaction(trans,
3752 ret);
3753 btrfs_end_transaction(trans);
3754 goto out;
3757 ret = btrfs_insert_empty_item(trans, root, path,
3758 &new_key, size);
3759 if (ret) {
3760 btrfs_abort_transaction(trans, ret);
3761 btrfs_end_transaction(trans);
3762 goto out;
3765 leaf = path->nodes[0];
3766 slot = path->slots[0];
3767 write_extent_buffer(leaf, buf,
3768 btrfs_item_ptr_offset(leaf, slot),
3769 size);
3771 extent = btrfs_item_ptr(leaf, slot,
3772 struct btrfs_file_extent_item);
3774 /* disko == 0 means it's a hole */
3775 if (!disko)
3776 datao = 0;
3778 btrfs_set_file_extent_offset(leaf, extent,
3779 datao);
3780 btrfs_set_file_extent_num_bytes(leaf, extent,
3781 datal);
3783 if (disko) {
3784 inode_add_bytes(inode, datal);
3785 ret = btrfs_inc_extent_ref(trans,
3786 fs_info,
3787 disko, diskl, 0,
3788 root->root_key.objectid,
3789 btrfs_ino(BTRFS_I(inode)),
3790 new_key.offset - datao);
3791 if (ret) {
3792 btrfs_abort_transaction(trans,
3793 ret);
3794 btrfs_end_transaction(trans);
3795 goto out;
3799 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3800 u64 skip = 0;
3801 u64 trim = 0;
3803 if (off > key.offset) {
3804 skip = off - key.offset;
3805 new_key.offset += skip;
3808 if (key.offset + datal > off + len)
3809 trim = key.offset + datal - (off + len);
3811 if (comp && (skip || trim)) {
3812 ret = -EINVAL;
3813 btrfs_end_transaction(trans);
3814 goto out;
3816 size -= skip + trim;
3817 datal -= skip + trim;
3819 ret = clone_copy_inline_extent(inode,
3820 trans, path,
3821 &new_key,
3822 drop_start,
3823 datal,
3824 skip, size, buf);
3825 if (ret) {
3826 if (ret != -EOPNOTSUPP)
3827 btrfs_abort_transaction(trans,
3828 ret);
3829 btrfs_end_transaction(trans);
3830 goto out;
3832 leaf = path->nodes[0];
3833 slot = path->slots[0];
3836 /* If we have an implicit hole (NO_HOLES feature). */
3837 if (drop_start < new_key.offset)
3838 clone_update_extent_map(BTRFS_I(inode), trans,
3839 NULL, drop_start,
3840 new_key.offset - drop_start);
3842 clone_update_extent_map(BTRFS_I(inode), trans,
3843 path, 0, 0);
3845 btrfs_mark_buffer_dirty(leaf);
3846 btrfs_release_path(path);
3848 last_dest_end = ALIGN(new_key.offset + datal,
3849 fs_info->sectorsize);
3850 ret = clone_finish_inode_update(trans, inode,
3851 last_dest_end,
3852 destoff, olen,
3853 no_time_update);
3854 if (ret)
3855 goto out;
3856 if (new_key.offset + datal >= destoff + len)
3857 break;
3859 btrfs_release_path(path);
3860 key.offset = next_key_min_offset;
3862 if (fatal_signal_pending(current)) {
3863 ret = -EINTR;
3864 goto out;
3867 cond_resched();
3869 ret = 0;
3871 if (last_dest_end < destoff + len) {
3873 * We have an implicit hole (NO_HOLES feature is enabled) that
3874 * fully or partially overlaps our cloning range at its end.
3876 btrfs_release_path(path);
3879 * 1 - remove extent(s)
3880 * 1 - inode update
3882 trans = btrfs_start_transaction(root, 2);
3883 if (IS_ERR(trans)) {
3884 ret = PTR_ERR(trans);
3885 goto out;
3887 ret = btrfs_drop_extents(trans, root, inode,
3888 last_dest_end, destoff + len, 1);
3889 if (ret) {
3890 if (ret != -EOPNOTSUPP)
3891 btrfs_abort_transaction(trans, ret);
3892 btrfs_end_transaction(trans);
3893 goto out;
3895 clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3896 last_dest_end,
3897 destoff + len - last_dest_end);
3898 ret = clone_finish_inode_update(trans, inode, destoff + len,
3899 destoff, olen, no_time_update);
3902 out:
3903 btrfs_free_path(path);
3904 kvfree(buf);
3905 return ret;
3908 static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
3909 u64 off, u64 olen, u64 destoff)
3911 struct inode *inode = file_inode(file);
3912 struct inode *src = file_inode(file_src);
3913 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3914 struct btrfs_root *root = BTRFS_I(inode)->root;
3915 int ret;
3916 u64 len = olen;
3917 u64 bs = fs_info->sb->s_blocksize;
3918 int same_inode = src == inode;
3921 * TODO:
3922 * - split compressed inline extents. annoying: we need to
3923 * decompress into destination's address_space (the file offset
3924 * may change, so source mapping won't do), then recompress (or
3925 * otherwise reinsert) a subrange.
3927 * - split destination inode's inline extents. The inline extents can
3928 * be either compressed or non-compressed.
3931 if (btrfs_root_readonly(root))
3932 return -EROFS;
3934 if (file_src->f_path.mnt != file->f_path.mnt ||
3935 src->i_sb != inode->i_sb)
3936 return -EXDEV;
3938 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3939 return -EISDIR;
3941 if (!same_inode) {
3942 btrfs_double_inode_lock(src, inode);
3943 } else {
3944 inode_lock(src);
3947 /* don't make the dst file partly checksummed */
3948 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3949 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
3950 ret = -EINVAL;
3951 goto out_unlock;
3954 /* determine range to clone */
3955 ret = -EINVAL;
3956 if (off + len > src->i_size || off + len < off)
3957 goto out_unlock;
3958 if (len == 0)
3959 olen = len = src->i_size - off;
3961 * If we extend to eof, continue to block boundary if and only if the
3962 * destination end offset matches the destination file's size, otherwise
3963 * we would be corrupting data by placing the eof block into the middle
3964 * of a file.
3966 if (off + len == src->i_size) {
3967 if (!IS_ALIGNED(len, bs) && destoff + len < inode->i_size)
3968 goto out_unlock;
3969 len = ALIGN(src->i_size, bs) - off;
3972 if (len == 0) {
3973 ret = 0;
3974 goto out_unlock;
3977 /* verify the end result is block aligned */
3978 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3979 !IS_ALIGNED(destoff, bs))
3980 goto out_unlock;
3982 /* verify if ranges are overlapped within the same file */
3983 if (same_inode) {
3984 if (destoff + len > off && destoff < off + len)
3985 goto out_unlock;
3988 if (destoff > inode->i_size) {
3989 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3990 if (ret)
3991 goto out_unlock;
3995 * Lock the target range too. Right after we replace the file extent
3996 * items in the fs tree (which now point to the cloned data), we might
3997 * have a worker replace them with extent items relative to a write
3998 * operation that was issued before this clone operation (i.e. confront
3999 * with inode.c:btrfs_finish_ordered_io).
4001 if (same_inode) {
4002 u64 lock_start = min_t(u64, off, destoff);
4003 u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
4005 ret = lock_extent_range(src, lock_start, lock_len, true);
4006 } else {
4007 ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
4008 true);
4010 ASSERT(ret == 0);
4011 if (WARN_ON(ret)) {
4012 /* ranges in the io trees already unlocked */
4013 goto out_unlock;
4016 ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
4018 if (same_inode) {
4019 u64 lock_start = min_t(u64, off, destoff);
4020 u64 lock_end = max_t(u64, off, destoff) + len - 1;
4022 unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
4023 } else {
4024 btrfs_double_extent_unlock(src, off, inode, destoff, len);
4027 * Truncate page cache pages so that future reads will see the cloned
4028 * data immediately and not the previous data.
4030 truncate_inode_pages_range(&inode->i_data,
4031 round_down(destoff, PAGE_SIZE),
4032 round_up(destoff + len, PAGE_SIZE) - 1);
4033 out_unlock:
4034 if (!same_inode)
4035 btrfs_double_inode_unlock(src, inode);
4036 else
4037 inode_unlock(src);
4038 return ret;
4041 int btrfs_clone_file_range(struct file *src_file, loff_t off,
4042 struct file *dst_file, loff_t destoff, u64 len)
4044 return btrfs_clone_files(dst_file, src_file, off, len, destoff);
4048 * there are many ways the trans_start and trans_end ioctls can lead
4049 * to deadlocks. They should only be used by applications that
4050 * basically own the machine, and have a very in depth understanding
4051 * of all the possible deadlocks and enospc problems.
4053 static long btrfs_ioctl_trans_start(struct file *file)
4055 struct inode *inode = file_inode(file);
4056 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4057 struct btrfs_root *root = BTRFS_I(inode)->root;
4058 struct btrfs_trans_handle *trans;
4059 struct btrfs_file_private *private;
4060 int ret;
4061 static bool warned = false;
4063 ret = -EPERM;
4064 if (!capable(CAP_SYS_ADMIN))
4065 goto out;
4067 if (!warned) {
4068 btrfs_warn(fs_info,
4069 "Userspace transaction mechanism is considered "
4070 "deprecated and slated to be removed in 4.17. "
4071 "If you have a valid use case please "
4072 "speak up on the mailing list");
4073 WARN_ON(1);
4074 warned = true;
4077 ret = -EINPROGRESS;
4078 private = file->private_data;
4079 if (private && private->trans)
4080 goto out;
4081 if (!private) {
4082 private = kzalloc(sizeof(struct btrfs_file_private),
4083 GFP_KERNEL);
4084 if (!private)
4085 return -ENOMEM;
4086 file->private_data = private;
4089 ret = -EROFS;
4090 if (btrfs_root_readonly(root))
4091 goto out;
4093 ret = mnt_want_write_file(file);
4094 if (ret)
4095 goto out;
4097 atomic_inc(&fs_info->open_ioctl_trans);
4099 ret = -ENOMEM;
4100 trans = btrfs_start_ioctl_transaction(root);
4101 if (IS_ERR(trans))
4102 goto out_drop;
4104 private->trans = trans;
4105 return 0;
4107 out_drop:
4108 atomic_dec(&fs_info->open_ioctl_trans);
4109 mnt_drop_write_file(file);
4110 out:
4111 return ret;
4114 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
4116 struct inode *inode = file_inode(file);
4117 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4118 struct btrfs_root *root = BTRFS_I(inode)->root;
4119 struct btrfs_root *new_root;
4120 struct btrfs_dir_item *di;
4121 struct btrfs_trans_handle *trans;
4122 struct btrfs_path *path;
4123 struct btrfs_key location;
4124 struct btrfs_disk_key disk_key;
4125 u64 objectid = 0;
4126 u64 dir_id;
4127 int ret;
4129 if (!capable(CAP_SYS_ADMIN))
4130 return -EPERM;
4132 ret = mnt_want_write_file(file);
4133 if (ret)
4134 return ret;
4136 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
4137 ret = -EFAULT;
4138 goto out;
4141 if (!objectid)
4142 objectid = BTRFS_FS_TREE_OBJECTID;
4144 location.objectid = objectid;
4145 location.type = BTRFS_ROOT_ITEM_KEY;
4146 location.offset = (u64)-1;
4148 new_root = btrfs_read_fs_root_no_name(fs_info, &location);
4149 if (IS_ERR(new_root)) {
4150 ret = PTR_ERR(new_root);
4151 goto out;
4153 if (!is_fstree(new_root->objectid)) {
4154 ret = -ENOENT;
4155 goto out;
4158 path = btrfs_alloc_path();
4159 if (!path) {
4160 ret = -ENOMEM;
4161 goto out;
4163 path->leave_spinning = 1;
4165 trans = btrfs_start_transaction(root, 1);
4166 if (IS_ERR(trans)) {
4167 btrfs_free_path(path);
4168 ret = PTR_ERR(trans);
4169 goto out;
4172 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4173 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
4174 dir_id, "default", 7, 1);
4175 if (IS_ERR_OR_NULL(di)) {
4176 btrfs_free_path(path);
4177 btrfs_end_transaction(trans);
4178 btrfs_err(fs_info,
4179 "Umm, you don't have the default diritem, this isn't going to work");
4180 ret = -ENOENT;
4181 goto out;
4184 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
4185 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
4186 btrfs_mark_buffer_dirty(path->nodes[0]);
4187 btrfs_free_path(path);
4189 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
4190 btrfs_end_transaction(trans);
4191 out:
4192 mnt_drop_write_file(file);
4193 return ret;
4196 void btrfs_get_block_group_info(struct list_head *groups_list,
4197 struct btrfs_ioctl_space_info *space)
4199 struct btrfs_block_group_cache *block_group;
4201 space->total_bytes = 0;
4202 space->used_bytes = 0;
4203 space->flags = 0;
4204 list_for_each_entry(block_group, groups_list, list) {
4205 space->flags = block_group->flags;
4206 space->total_bytes += block_group->key.offset;
4207 space->used_bytes +=
4208 btrfs_block_group_used(&block_group->item);
4212 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
4213 void __user *arg)
4215 struct btrfs_ioctl_space_args space_args;
4216 struct btrfs_ioctl_space_info space;
4217 struct btrfs_ioctl_space_info *dest;
4218 struct btrfs_ioctl_space_info *dest_orig;
4219 struct btrfs_ioctl_space_info __user *user_dest;
4220 struct btrfs_space_info *info;
4221 u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
4222 BTRFS_BLOCK_GROUP_SYSTEM,
4223 BTRFS_BLOCK_GROUP_METADATA,
4224 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
4225 int num_types = 4;
4226 int alloc_size;
4227 int ret = 0;
4228 u64 slot_count = 0;
4229 int i, c;
4231 if (copy_from_user(&space_args,
4232 (struct btrfs_ioctl_space_args __user *)arg,
4233 sizeof(space_args)))
4234 return -EFAULT;
4236 for (i = 0; i < num_types; i++) {
4237 struct btrfs_space_info *tmp;
4239 info = NULL;
4240 rcu_read_lock();
4241 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4242 list) {
4243 if (tmp->flags == types[i]) {
4244 info = tmp;
4245 break;
4248 rcu_read_unlock();
4250 if (!info)
4251 continue;
4253 down_read(&info->groups_sem);
4254 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4255 if (!list_empty(&info->block_groups[c]))
4256 slot_count++;
4258 up_read(&info->groups_sem);
4262 * Global block reserve, exported as a space_info
4264 slot_count++;
4266 /* space_slots == 0 means they are asking for a count */
4267 if (space_args.space_slots == 0) {
4268 space_args.total_spaces = slot_count;
4269 goto out;
4272 slot_count = min_t(u64, space_args.space_slots, slot_count);
4274 alloc_size = sizeof(*dest) * slot_count;
4276 /* we generally have at most 6 or so space infos, one for each raid
4277 * level. So, a whole page should be more than enough for everyone
4279 if (alloc_size > PAGE_SIZE)
4280 return -ENOMEM;
4282 space_args.total_spaces = 0;
4283 dest = kmalloc(alloc_size, GFP_KERNEL);
4284 if (!dest)
4285 return -ENOMEM;
4286 dest_orig = dest;
4288 /* now we have a buffer to copy into */
4289 for (i = 0; i < num_types; i++) {
4290 struct btrfs_space_info *tmp;
4292 if (!slot_count)
4293 break;
4295 info = NULL;
4296 rcu_read_lock();
4297 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4298 list) {
4299 if (tmp->flags == types[i]) {
4300 info = tmp;
4301 break;
4304 rcu_read_unlock();
4306 if (!info)
4307 continue;
4308 down_read(&info->groups_sem);
4309 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4310 if (!list_empty(&info->block_groups[c])) {
4311 btrfs_get_block_group_info(
4312 &info->block_groups[c], &space);
4313 memcpy(dest, &space, sizeof(space));
4314 dest++;
4315 space_args.total_spaces++;
4316 slot_count--;
4318 if (!slot_count)
4319 break;
4321 up_read(&info->groups_sem);
4325 * Add global block reserve
4327 if (slot_count) {
4328 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4330 spin_lock(&block_rsv->lock);
4331 space.total_bytes = block_rsv->size;
4332 space.used_bytes = block_rsv->size - block_rsv->reserved;
4333 spin_unlock(&block_rsv->lock);
4334 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4335 memcpy(dest, &space, sizeof(space));
4336 space_args.total_spaces++;
4339 user_dest = (struct btrfs_ioctl_space_info __user *)
4340 (arg + sizeof(struct btrfs_ioctl_space_args));
4342 if (copy_to_user(user_dest, dest_orig, alloc_size))
4343 ret = -EFAULT;
4345 kfree(dest_orig);
4346 out:
4347 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
4348 ret = -EFAULT;
4350 return ret;
4354 * there are many ways the trans_start and trans_end ioctls can lead
4355 * to deadlocks. They should only be used by applications that
4356 * basically own the machine, and have a very in depth understanding
4357 * of all the possible deadlocks and enospc problems.
4359 long btrfs_ioctl_trans_end(struct file *file)
4361 struct inode *inode = file_inode(file);
4362 struct btrfs_root *root = BTRFS_I(inode)->root;
4363 struct btrfs_file_private *private = file->private_data;
4365 if (!private || !private->trans)
4366 return -EINVAL;
4368 btrfs_end_transaction(private->trans);
4369 private->trans = NULL;
4371 atomic_dec(&root->fs_info->open_ioctl_trans);
4373 mnt_drop_write_file(file);
4374 return 0;
4377 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4378 void __user *argp)
4380 struct btrfs_trans_handle *trans;
4381 u64 transid;
4382 int ret;
4384 trans = btrfs_attach_transaction_barrier(root);
4385 if (IS_ERR(trans)) {
4386 if (PTR_ERR(trans) != -ENOENT)
4387 return PTR_ERR(trans);
4389 /* No running transaction, don't bother */
4390 transid = root->fs_info->last_trans_committed;
4391 goto out;
4393 transid = trans->transid;
4394 ret = btrfs_commit_transaction_async(trans, 0);
4395 if (ret) {
4396 btrfs_end_transaction(trans);
4397 return ret;
4399 out:
4400 if (argp)
4401 if (copy_to_user(argp, &transid, sizeof(transid)))
4402 return -EFAULT;
4403 return 0;
4406 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
4407 void __user *argp)
4409 u64 transid;
4411 if (argp) {
4412 if (copy_from_user(&transid, argp, sizeof(transid)))
4413 return -EFAULT;
4414 } else {
4415 transid = 0; /* current trans */
4417 return btrfs_wait_for_commit(fs_info, transid);
4420 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4422 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4423 struct btrfs_ioctl_scrub_args *sa;
4424 int ret;
4426 if (!capable(CAP_SYS_ADMIN))
4427 return -EPERM;
4429 sa = memdup_user(arg, sizeof(*sa));
4430 if (IS_ERR(sa))
4431 return PTR_ERR(sa);
4433 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4434 ret = mnt_want_write_file(file);
4435 if (ret)
4436 goto out;
4439 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
4440 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4443 if (copy_to_user(arg, sa, sizeof(*sa)))
4444 ret = -EFAULT;
4446 if (!(sa->flags & BTRFS_SCRUB_READONLY))
4447 mnt_drop_write_file(file);
4448 out:
4449 kfree(sa);
4450 return ret;
4453 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4455 if (!capable(CAP_SYS_ADMIN))
4456 return -EPERM;
4458 return btrfs_scrub_cancel(fs_info);
4461 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4462 void __user *arg)
4464 struct btrfs_ioctl_scrub_args *sa;
4465 int ret;
4467 if (!capable(CAP_SYS_ADMIN))
4468 return -EPERM;
4470 sa = memdup_user(arg, sizeof(*sa));
4471 if (IS_ERR(sa))
4472 return PTR_ERR(sa);
4474 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4476 if (copy_to_user(arg, sa, sizeof(*sa)))
4477 ret = -EFAULT;
4479 kfree(sa);
4480 return ret;
4483 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4484 void __user *arg)
4486 struct btrfs_ioctl_get_dev_stats *sa;
4487 int ret;
4489 sa = memdup_user(arg, sizeof(*sa));
4490 if (IS_ERR(sa))
4491 return PTR_ERR(sa);
4493 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4494 kfree(sa);
4495 return -EPERM;
4498 ret = btrfs_get_dev_stats(fs_info, sa);
4500 if (copy_to_user(arg, sa, sizeof(*sa)))
4501 ret = -EFAULT;
4503 kfree(sa);
4504 return ret;
4507 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4508 void __user *arg)
4510 struct btrfs_ioctl_dev_replace_args *p;
4511 int ret;
4513 if (!capable(CAP_SYS_ADMIN))
4514 return -EPERM;
4516 p = memdup_user(arg, sizeof(*p));
4517 if (IS_ERR(p))
4518 return PTR_ERR(p);
4520 switch (p->cmd) {
4521 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4522 if (sb_rdonly(fs_info->sb)) {
4523 ret = -EROFS;
4524 goto out;
4526 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4527 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4528 } else {
4529 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4530 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4532 break;
4533 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4534 btrfs_dev_replace_status(fs_info, p);
4535 ret = 0;
4536 break;
4537 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4538 ret = btrfs_dev_replace_cancel(fs_info, p);
4539 break;
4540 default:
4541 ret = -EINVAL;
4542 break;
4545 if (copy_to_user(arg, p, sizeof(*p)))
4546 ret = -EFAULT;
4547 out:
4548 kfree(p);
4549 return ret;
4552 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4554 int ret = 0;
4555 int i;
4556 u64 rel_ptr;
4557 int size;
4558 struct btrfs_ioctl_ino_path_args *ipa = NULL;
4559 struct inode_fs_paths *ipath = NULL;
4560 struct btrfs_path *path;
4562 if (!capable(CAP_DAC_READ_SEARCH))
4563 return -EPERM;
4565 path = btrfs_alloc_path();
4566 if (!path) {
4567 ret = -ENOMEM;
4568 goto out;
4571 ipa = memdup_user(arg, sizeof(*ipa));
4572 if (IS_ERR(ipa)) {
4573 ret = PTR_ERR(ipa);
4574 ipa = NULL;
4575 goto out;
4578 size = min_t(u32, ipa->size, 4096);
4579 ipath = init_ipath(size, root, path);
4580 if (IS_ERR(ipath)) {
4581 ret = PTR_ERR(ipath);
4582 ipath = NULL;
4583 goto out;
4586 ret = paths_from_inode(ipa->inum, ipath);
4587 if (ret < 0)
4588 goto out;
4590 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4591 rel_ptr = ipath->fspath->val[i] -
4592 (u64)(unsigned long)ipath->fspath->val;
4593 ipath->fspath->val[i] = rel_ptr;
4596 ret = copy_to_user((void *)(unsigned long)ipa->fspath,
4597 (void *)(unsigned long)ipath->fspath, size);
4598 if (ret) {
4599 ret = -EFAULT;
4600 goto out;
4603 out:
4604 btrfs_free_path(path);
4605 free_ipath(ipath);
4606 kfree(ipa);
4608 return ret;
4611 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4613 struct btrfs_data_container *inodes = ctx;
4614 const size_t c = 3 * sizeof(u64);
4616 if (inodes->bytes_left >= c) {
4617 inodes->bytes_left -= c;
4618 inodes->val[inodes->elem_cnt] = inum;
4619 inodes->val[inodes->elem_cnt + 1] = offset;
4620 inodes->val[inodes->elem_cnt + 2] = root;
4621 inodes->elem_cnt += 3;
4622 } else {
4623 inodes->bytes_missing += c - inodes->bytes_left;
4624 inodes->bytes_left = 0;
4625 inodes->elem_missed += 3;
4628 return 0;
4631 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4632 void __user *arg)
4634 int ret = 0;
4635 int size;
4636 struct btrfs_ioctl_logical_ino_args *loi;
4637 struct btrfs_data_container *inodes = NULL;
4638 struct btrfs_path *path = NULL;
4640 if (!capable(CAP_SYS_ADMIN))
4641 return -EPERM;
4643 loi = memdup_user(arg, sizeof(*loi));
4644 if (IS_ERR(loi))
4645 return PTR_ERR(loi);
4647 path = btrfs_alloc_path();
4648 if (!path) {
4649 ret = -ENOMEM;
4650 goto out;
4653 size = min_t(u32, loi->size, SZ_64K);
4654 inodes = init_data_container(size);
4655 if (IS_ERR(inodes)) {
4656 ret = PTR_ERR(inodes);
4657 inodes = NULL;
4658 goto out;
4661 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4662 build_ino_list, inodes);
4663 if (ret == -EINVAL)
4664 ret = -ENOENT;
4665 if (ret < 0)
4666 goto out;
4668 ret = copy_to_user((void *)(unsigned long)loi->inodes,
4669 (void *)(unsigned long)inodes, size);
4670 if (ret)
4671 ret = -EFAULT;
4673 out:
4674 btrfs_free_path(path);
4675 kvfree(inodes);
4676 kfree(loi);
4678 return ret;
4681 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4682 struct btrfs_ioctl_balance_args *bargs)
4684 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4686 bargs->flags = bctl->flags;
4688 if (atomic_read(&fs_info->balance_running))
4689 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4690 if (atomic_read(&fs_info->balance_pause_req))
4691 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4692 if (atomic_read(&fs_info->balance_cancel_req))
4693 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4695 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4696 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4697 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4699 if (lock) {
4700 spin_lock(&fs_info->balance_lock);
4701 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4702 spin_unlock(&fs_info->balance_lock);
4703 } else {
4704 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4708 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4710 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4711 struct btrfs_fs_info *fs_info = root->fs_info;
4712 struct btrfs_ioctl_balance_args *bargs;
4713 struct btrfs_balance_control *bctl;
4714 bool need_unlock; /* for mut. excl. ops lock */
4715 int ret;
4717 if (!capable(CAP_SYS_ADMIN))
4718 return -EPERM;
4720 ret = mnt_want_write_file(file);
4721 if (ret)
4722 return ret;
4724 again:
4725 if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4726 mutex_lock(&fs_info->volume_mutex);
4727 mutex_lock(&fs_info->balance_mutex);
4728 need_unlock = true;
4729 goto locked;
4733 * mut. excl. ops lock is locked. Three possibilities:
4734 * (1) some other op is running
4735 * (2) balance is running
4736 * (3) balance is paused -- special case (think resume)
4738 mutex_lock(&fs_info->balance_mutex);
4739 if (fs_info->balance_ctl) {
4740 /* this is either (2) or (3) */
4741 if (!atomic_read(&fs_info->balance_running)) {
4742 mutex_unlock(&fs_info->balance_mutex);
4743 if (!mutex_trylock(&fs_info->volume_mutex))
4744 goto again;
4745 mutex_lock(&fs_info->balance_mutex);
4747 if (fs_info->balance_ctl &&
4748 !atomic_read(&fs_info->balance_running)) {
4749 /* this is (3) */
4750 need_unlock = false;
4751 goto locked;
4754 mutex_unlock(&fs_info->balance_mutex);
4755 mutex_unlock(&fs_info->volume_mutex);
4756 goto again;
4757 } else {
4758 /* this is (2) */
4759 mutex_unlock(&fs_info->balance_mutex);
4760 ret = -EINPROGRESS;
4761 goto out;
4763 } else {
4764 /* this is (1) */
4765 mutex_unlock(&fs_info->balance_mutex);
4766 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4767 goto out;
4770 locked:
4771 BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4773 if (arg) {
4774 bargs = memdup_user(arg, sizeof(*bargs));
4775 if (IS_ERR(bargs)) {
4776 ret = PTR_ERR(bargs);
4777 goto out_unlock;
4780 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4781 if (!fs_info->balance_ctl) {
4782 ret = -ENOTCONN;
4783 goto out_bargs;
4786 bctl = fs_info->balance_ctl;
4787 spin_lock(&fs_info->balance_lock);
4788 bctl->flags |= BTRFS_BALANCE_RESUME;
4789 spin_unlock(&fs_info->balance_lock);
4791 goto do_balance;
4793 } else {
4794 bargs = NULL;
4797 if (fs_info->balance_ctl) {
4798 ret = -EINPROGRESS;
4799 goto out_bargs;
4802 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4803 if (!bctl) {
4804 ret = -ENOMEM;
4805 goto out_bargs;
4808 bctl->fs_info = fs_info;
4809 if (arg) {
4810 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4811 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4812 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4814 bctl->flags = bargs->flags;
4815 } else {
4816 /* balance everything - no filters */
4817 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4820 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4821 ret = -EINVAL;
4822 goto out_bctl;
4825 do_balance:
4827 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP
4828 * goes to to btrfs_balance. bctl is freed in __cancel_balance,
4829 * or, if restriper was paused all the way until unmount, in
4830 * free_fs_info. The flag is cleared in __cancel_balance.
4832 need_unlock = false;
4834 ret = btrfs_balance(bctl, bargs);
4835 bctl = NULL;
4837 if (arg) {
4838 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4839 ret = -EFAULT;
4842 out_bctl:
4843 kfree(bctl);
4844 out_bargs:
4845 kfree(bargs);
4846 out_unlock:
4847 mutex_unlock(&fs_info->balance_mutex);
4848 mutex_unlock(&fs_info->volume_mutex);
4849 if (need_unlock)
4850 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4851 out:
4852 mnt_drop_write_file(file);
4853 return ret;
4856 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4858 if (!capable(CAP_SYS_ADMIN))
4859 return -EPERM;
4861 switch (cmd) {
4862 case BTRFS_BALANCE_CTL_PAUSE:
4863 return btrfs_pause_balance(fs_info);
4864 case BTRFS_BALANCE_CTL_CANCEL:
4865 return btrfs_cancel_balance(fs_info);
4868 return -EINVAL;
4871 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4872 void __user *arg)
4874 struct btrfs_ioctl_balance_args *bargs;
4875 int ret = 0;
4877 if (!capable(CAP_SYS_ADMIN))
4878 return -EPERM;
4880 mutex_lock(&fs_info->balance_mutex);
4881 if (!fs_info->balance_ctl) {
4882 ret = -ENOTCONN;
4883 goto out;
4886 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4887 if (!bargs) {
4888 ret = -ENOMEM;
4889 goto out;
4892 update_ioctl_balance_args(fs_info, 1, bargs);
4894 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4895 ret = -EFAULT;
4897 kfree(bargs);
4898 out:
4899 mutex_unlock(&fs_info->balance_mutex);
4900 return ret;
4903 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4905 struct inode *inode = file_inode(file);
4906 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4907 struct btrfs_ioctl_quota_ctl_args *sa;
4908 struct btrfs_trans_handle *trans = NULL;
4909 int ret;
4910 int err;
4912 if (!capable(CAP_SYS_ADMIN))
4913 return -EPERM;
4915 ret = mnt_want_write_file(file);
4916 if (ret)
4917 return ret;
4919 sa = memdup_user(arg, sizeof(*sa));
4920 if (IS_ERR(sa)) {
4921 ret = PTR_ERR(sa);
4922 goto drop_write;
4925 down_write(&fs_info->subvol_sem);
4926 trans = btrfs_start_transaction(fs_info->tree_root, 2);
4927 if (IS_ERR(trans)) {
4928 ret = PTR_ERR(trans);
4929 goto out;
4932 switch (sa->cmd) {
4933 case BTRFS_QUOTA_CTL_ENABLE:
4934 ret = btrfs_quota_enable(trans, fs_info);
4935 break;
4936 case BTRFS_QUOTA_CTL_DISABLE:
4937 ret = btrfs_quota_disable(trans, fs_info);
4938 break;
4939 default:
4940 ret = -EINVAL;
4941 break;
4944 err = btrfs_commit_transaction(trans);
4945 if (err && !ret)
4946 ret = err;
4947 out:
4948 kfree(sa);
4949 up_write(&fs_info->subvol_sem);
4950 drop_write:
4951 mnt_drop_write_file(file);
4952 return ret;
4955 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4957 struct inode *inode = file_inode(file);
4958 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4959 struct btrfs_root *root = BTRFS_I(inode)->root;
4960 struct btrfs_ioctl_qgroup_assign_args *sa;
4961 struct btrfs_trans_handle *trans;
4962 int ret;
4963 int err;
4965 if (!capable(CAP_SYS_ADMIN))
4966 return -EPERM;
4968 ret = mnt_want_write_file(file);
4969 if (ret)
4970 return ret;
4972 sa = memdup_user(arg, sizeof(*sa));
4973 if (IS_ERR(sa)) {
4974 ret = PTR_ERR(sa);
4975 goto drop_write;
4978 trans = btrfs_join_transaction(root);
4979 if (IS_ERR(trans)) {
4980 ret = PTR_ERR(trans);
4981 goto out;
4984 if (sa->assign) {
4985 ret = btrfs_add_qgroup_relation(trans, fs_info,
4986 sa->src, sa->dst);
4987 } else {
4988 ret = btrfs_del_qgroup_relation(trans, fs_info,
4989 sa->src, sa->dst);
4992 /* update qgroup status and info */
4993 err = btrfs_run_qgroups(trans, fs_info);
4994 if (err < 0)
4995 btrfs_handle_fs_error(fs_info, err,
4996 "failed to update qgroup status and info");
4997 err = btrfs_end_transaction(trans);
4998 if (err && !ret)
4999 ret = err;
5001 out:
5002 kfree(sa);
5003 drop_write:
5004 mnt_drop_write_file(file);
5005 return ret;
5008 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
5010 struct inode *inode = file_inode(file);
5011 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5012 struct btrfs_root *root = BTRFS_I(inode)->root;
5013 struct btrfs_ioctl_qgroup_create_args *sa;
5014 struct btrfs_trans_handle *trans;
5015 int ret;
5016 int err;
5018 if (!capable(CAP_SYS_ADMIN))
5019 return -EPERM;
5021 ret = mnt_want_write_file(file);
5022 if (ret)
5023 return ret;
5025 sa = memdup_user(arg, sizeof(*sa));
5026 if (IS_ERR(sa)) {
5027 ret = PTR_ERR(sa);
5028 goto drop_write;
5031 if (!sa->qgroupid) {
5032 ret = -EINVAL;
5033 goto out;
5036 trans = btrfs_join_transaction(root);
5037 if (IS_ERR(trans)) {
5038 ret = PTR_ERR(trans);
5039 goto out;
5042 if (sa->create) {
5043 ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
5044 } else {
5045 ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
5048 err = btrfs_end_transaction(trans);
5049 if (err && !ret)
5050 ret = err;
5052 out:
5053 kfree(sa);
5054 drop_write:
5055 mnt_drop_write_file(file);
5056 return ret;
5059 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
5061 struct inode *inode = file_inode(file);
5062 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5063 struct btrfs_root *root = BTRFS_I(inode)->root;
5064 struct btrfs_ioctl_qgroup_limit_args *sa;
5065 struct btrfs_trans_handle *trans;
5066 int ret;
5067 int err;
5068 u64 qgroupid;
5070 if (!capable(CAP_SYS_ADMIN))
5071 return -EPERM;
5073 ret = mnt_want_write_file(file);
5074 if (ret)
5075 return ret;
5077 sa = memdup_user(arg, sizeof(*sa));
5078 if (IS_ERR(sa)) {
5079 ret = PTR_ERR(sa);
5080 goto drop_write;
5083 trans = btrfs_join_transaction(root);
5084 if (IS_ERR(trans)) {
5085 ret = PTR_ERR(trans);
5086 goto out;
5089 qgroupid = sa->qgroupid;
5090 if (!qgroupid) {
5091 /* take the current subvol as qgroup */
5092 qgroupid = root->root_key.objectid;
5095 ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
5097 err = btrfs_end_transaction(trans);
5098 if (err && !ret)
5099 ret = err;
5101 out:
5102 kfree(sa);
5103 drop_write:
5104 mnt_drop_write_file(file);
5105 return ret;
5108 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
5110 struct inode *inode = file_inode(file);
5111 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5112 struct btrfs_ioctl_quota_rescan_args *qsa;
5113 int ret;
5115 if (!capable(CAP_SYS_ADMIN))
5116 return -EPERM;
5118 ret = mnt_want_write_file(file);
5119 if (ret)
5120 return ret;
5122 qsa = memdup_user(arg, sizeof(*qsa));
5123 if (IS_ERR(qsa)) {
5124 ret = PTR_ERR(qsa);
5125 goto drop_write;
5128 if (qsa->flags) {
5129 ret = -EINVAL;
5130 goto out;
5133 ret = btrfs_qgroup_rescan(fs_info);
5135 out:
5136 kfree(qsa);
5137 drop_write:
5138 mnt_drop_write_file(file);
5139 return ret;
5142 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
5144 struct inode *inode = file_inode(file);
5145 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5146 struct btrfs_ioctl_quota_rescan_args *qsa;
5147 int ret = 0;
5149 if (!capable(CAP_SYS_ADMIN))
5150 return -EPERM;
5152 qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
5153 if (!qsa)
5154 return -ENOMEM;
5156 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
5157 qsa->flags = 1;
5158 qsa->progress = fs_info->qgroup_rescan_progress.objectid;
5161 if (copy_to_user(arg, qsa, sizeof(*qsa)))
5162 ret = -EFAULT;
5164 kfree(qsa);
5165 return ret;
5168 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
5170 struct inode *inode = file_inode(file);
5171 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5173 if (!capable(CAP_SYS_ADMIN))
5174 return -EPERM;
5176 return btrfs_qgroup_wait_for_completion(fs_info, true);
5179 static long _btrfs_ioctl_set_received_subvol(struct file *file,
5180 struct btrfs_ioctl_received_subvol_args *sa)
5182 struct inode *inode = file_inode(file);
5183 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5184 struct btrfs_root *root = BTRFS_I(inode)->root;
5185 struct btrfs_root_item *root_item = &root->root_item;
5186 struct btrfs_trans_handle *trans;
5187 struct timespec ct = current_time(inode);
5188 int ret = 0;
5189 int received_uuid_changed;
5191 if (!inode_owner_or_capable(inode))
5192 return -EPERM;
5194 ret = mnt_want_write_file(file);
5195 if (ret < 0)
5196 return ret;
5198 down_write(&fs_info->subvol_sem);
5200 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
5201 ret = -EINVAL;
5202 goto out;
5205 if (btrfs_root_readonly(root)) {
5206 ret = -EROFS;
5207 goto out;
5211 * 1 - root item
5212 * 2 - uuid items (received uuid + subvol uuid)
5214 trans = btrfs_start_transaction(root, 3);
5215 if (IS_ERR(trans)) {
5216 ret = PTR_ERR(trans);
5217 trans = NULL;
5218 goto out;
5221 sa->rtransid = trans->transid;
5222 sa->rtime.sec = ct.tv_sec;
5223 sa->rtime.nsec = ct.tv_nsec;
5225 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5226 BTRFS_UUID_SIZE);
5227 if (received_uuid_changed &&
5228 !btrfs_is_empty_uuid(root_item->received_uuid))
5229 btrfs_uuid_tree_rem(trans, fs_info, root_item->received_uuid,
5230 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5231 root->root_key.objectid);
5232 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5233 btrfs_set_root_stransid(root_item, sa->stransid);
5234 btrfs_set_root_rtransid(root_item, sa->rtransid);
5235 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5236 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5237 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5238 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
5240 ret = btrfs_update_root(trans, fs_info->tree_root,
5241 &root->root_key, &root->root_item);
5242 if (ret < 0) {
5243 btrfs_end_transaction(trans);
5244 goto out;
5246 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5247 ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
5248 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5249 root->root_key.objectid);
5250 if (ret < 0 && ret != -EEXIST) {
5251 btrfs_abort_transaction(trans, ret);
5252 goto out;
5255 ret = btrfs_commit_transaction(trans);
5256 if (ret < 0) {
5257 btrfs_abort_transaction(trans, ret);
5258 goto out;
5261 out:
5262 up_write(&fs_info->subvol_sem);
5263 mnt_drop_write_file(file);
5264 return ret;
5267 #ifdef CONFIG_64BIT
5268 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5269 void __user *arg)
5271 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5272 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5273 int ret = 0;
5275 args32 = memdup_user(arg, sizeof(*args32));
5276 if (IS_ERR(args32))
5277 return PTR_ERR(args32);
5279 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
5280 if (!args64) {
5281 ret = -ENOMEM;
5282 goto out;
5285 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5286 args64->stransid = args32->stransid;
5287 args64->rtransid = args32->rtransid;
5288 args64->stime.sec = args32->stime.sec;
5289 args64->stime.nsec = args32->stime.nsec;
5290 args64->rtime.sec = args32->rtime.sec;
5291 args64->rtime.nsec = args32->rtime.nsec;
5292 args64->flags = args32->flags;
5294 ret = _btrfs_ioctl_set_received_subvol(file, args64);
5295 if (ret)
5296 goto out;
5298 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5299 args32->stransid = args64->stransid;
5300 args32->rtransid = args64->rtransid;
5301 args32->stime.sec = args64->stime.sec;
5302 args32->stime.nsec = args64->stime.nsec;
5303 args32->rtime.sec = args64->rtime.sec;
5304 args32->rtime.nsec = args64->rtime.nsec;
5305 args32->flags = args64->flags;
5307 ret = copy_to_user(arg, args32, sizeof(*args32));
5308 if (ret)
5309 ret = -EFAULT;
5311 out:
5312 kfree(args32);
5313 kfree(args64);
5314 return ret;
5316 #endif
5318 static long btrfs_ioctl_set_received_subvol(struct file *file,
5319 void __user *arg)
5321 struct btrfs_ioctl_received_subvol_args *sa = NULL;
5322 int ret = 0;
5324 sa = memdup_user(arg, sizeof(*sa));
5325 if (IS_ERR(sa))
5326 return PTR_ERR(sa);
5328 ret = _btrfs_ioctl_set_received_subvol(file, sa);
5330 if (ret)
5331 goto out;
5333 ret = copy_to_user(arg, sa, sizeof(*sa));
5334 if (ret)
5335 ret = -EFAULT;
5337 out:
5338 kfree(sa);
5339 return ret;
5342 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5344 struct inode *inode = file_inode(file);
5345 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5346 size_t len;
5347 int ret;
5348 char label[BTRFS_LABEL_SIZE];
5350 spin_lock(&fs_info->super_lock);
5351 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5352 spin_unlock(&fs_info->super_lock);
5354 len = strnlen(label, BTRFS_LABEL_SIZE);
5356 if (len == BTRFS_LABEL_SIZE) {
5357 btrfs_warn(fs_info,
5358 "label is too long, return the first %zu bytes",
5359 --len);
5362 ret = copy_to_user(arg, label, len);
5364 return ret ? -EFAULT : 0;
5367 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5369 struct inode *inode = file_inode(file);
5370 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5371 struct btrfs_root *root = BTRFS_I(inode)->root;
5372 struct btrfs_super_block *super_block = fs_info->super_copy;
5373 struct btrfs_trans_handle *trans;
5374 char label[BTRFS_LABEL_SIZE];
5375 int ret;
5377 if (!capable(CAP_SYS_ADMIN))
5378 return -EPERM;
5380 if (copy_from_user(label, arg, sizeof(label)))
5381 return -EFAULT;
5383 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5384 btrfs_err(fs_info,
5385 "unable to set label with more than %d bytes",
5386 BTRFS_LABEL_SIZE - 1);
5387 return -EINVAL;
5390 ret = mnt_want_write_file(file);
5391 if (ret)
5392 return ret;
5394 trans = btrfs_start_transaction(root, 0);
5395 if (IS_ERR(trans)) {
5396 ret = PTR_ERR(trans);
5397 goto out_unlock;
5400 spin_lock(&fs_info->super_lock);
5401 strcpy(super_block->label, label);
5402 spin_unlock(&fs_info->super_lock);
5403 ret = btrfs_commit_transaction(trans);
5405 out_unlock:
5406 mnt_drop_write_file(file);
5407 return ret;
5410 #define INIT_FEATURE_FLAGS(suffix) \
5411 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5412 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5413 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5415 int btrfs_ioctl_get_supported_features(void __user *arg)
5417 static const struct btrfs_ioctl_feature_flags features[3] = {
5418 INIT_FEATURE_FLAGS(SUPP),
5419 INIT_FEATURE_FLAGS(SAFE_SET),
5420 INIT_FEATURE_FLAGS(SAFE_CLEAR)
5423 if (copy_to_user(arg, &features, sizeof(features)))
5424 return -EFAULT;
5426 return 0;
5429 static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
5431 struct inode *inode = file_inode(file);
5432 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5433 struct btrfs_super_block *super_block = fs_info->super_copy;
5434 struct btrfs_ioctl_feature_flags features;
5436 features.compat_flags = btrfs_super_compat_flags(super_block);
5437 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5438 features.incompat_flags = btrfs_super_incompat_flags(super_block);
5440 if (copy_to_user(arg, &features, sizeof(features)))
5441 return -EFAULT;
5443 return 0;
5446 static int check_feature_bits(struct btrfs_fs_info *fs_info,
5447 enum btrfs_feature_set set,
5448 u64 change_mask, u64 flags, u64 supported_flags,
5449 u64 safe_set, u64 safe_clear)
5451 const char *type = btrfs_feature_set_names[set];
5452 char *names;
5453 u64 disallowed, unsupported;
5454 u64 set_mask = flags & change_mask;
5455 u64 clear_mask = ~flags & change_mask;
5457 unsupported = set_mask & ~supported_flags;
5458 if (unsupported) {
5459 names = btrfs_printable_features(set, unsupported);
5460 if (names) {
5461 btrfs_warn(fs_info,
5462 "this kernel does not support the %s feature bit%s",
5463 names, strchr(names, ',') ? "s" : "");
5464 kfree(names);
5465 } else
5466 btrfs_warn(fs_info,
5467 "this kernel does not support %s bits 0x%llx",
5468 type, unsupported);
5469 return -EOPNOTSUPP;
5472 disallowed = set_mask & ~safe_set;
5473 if (disallowed) {
5474 names = btrfs_printable_features(set, disallowed);
5475 if (names) {
5476 btrfs_warn(fs_info,
5477 "can't set the %s feature bit%s while mounted",
5478 names, strchr(names, ',') ? "s" : "");
5479 kfree(names);
5480 } else
5481 btrfs_warn(fs_info,
5482 "can't set %s bits 0x%llx while mounted",
5483 type, disallowed);
5484 return -EPERM;
5487 disallowed = clear_mask & ~safe_clear;
5488 if (disallowed) {
5489 names = btrfs_printable_features(set, disallowed);
5490 if (names) {
5491 btrfs_warn(fs_info,
5492 "can't clear the %s feature bit%s while mounted",
5493 names, strchr(names, ',') ? "s" : "");
5494 kfree(names);
5495 } else
5496 btrfs_warn(fs_info,
5497 "can't clear %s bits 0x%llx while mounted",
5498 type, disallowed);
5499 return -EPERM;
5502 return 0;
5505 #define check_feature(fs_info, change_mask, flags, mask_base) \
5506 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
5507 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
5508 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
5509 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5511 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5513 struct inode *inode = file_inode(file);
5514 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5515 struct btrfs_root *root = BTRFS_I(inode)->root;
5516 struct btrfs_super_block *super_block = fs_info->super_copy;
5517 struct btrfs_ioctl_feature_flags flags[2];
5518 struct btrfs_trans_handle *trans;
5519 u64 newflags;
5520 int ret;
5522 if (!capable(CAP_SYS_ADMIN))
5523 return -EPERM;
5525 if (copy_from_user(flags, arg, sizeof(flags)))
5526 return -EFAULT;
5528 /* Nothing to do */
5529 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5530 !flags[0].incompat_flags)
5531 return 0;
5533 ret = check_feature(fs_info, flags[0].compat_flags,
5534 flags[1].compat_flags, COMPAT);
5535 if (ret)
5536 return ret;
5538 ret = check_feature(fs_info, flags[0].compat_ro_flags,
5539 flags[1].compat_ro_flags, COMPAT_RO);
5540 if (ret)
5541 return ret;
5543 ret = check_feature(fs_info, flags[0].incompat_flags,
5544 flags[1].incompat_flags, INCOMPAT);
5545 if (ret)
5546 return ret;
5548 ret = mnt_want_write_file(file);
5549 if (ret)
5550 return ret;
5552 trans = btrfs_start_transaction(root, 0);
5553 if (IS_ERR(trans)) {
5554 ret = PTR_ERR(trans);
5555 goto out_drop_write;
5558 spin_lock(&fs_info->super_lock);
5559 newflags = btrfs_super_compat_flags(super_block);
5560 newflags |= flags[0].compat_flags & flags[1].compat_flags;
5561 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5562 btrfs_set_super_compat_flags(super_block, newflags);
5564 newflags = btrfs_super_compat_ro_flags(super_block);
5565 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5566 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5567 btrfs_set_super_compat_ro_flags(super_block, newflags);
5569 newflags = btrfs_super_incompat_flags(super_block);
5570 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5571 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5572 btrfs_set_super_incompat_flags(super_block, newflags);
5573 spin_unlock(&fs_info->super_lock);
5575 ret = btrfs_commit_transaction(trans);
5576 out_drop_write:
5577 mnt_drop_write_file(file);
5579 return ret;
5582 long btrfs_ioctl(struct file *file, unsigned int
5583 cmd, unsigned long arg)
5585 struct inode *inode = file_inode(file);
5586 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5587 struct btrfs_root *root = BTRFS_I(inode)->root;
5588 void __user *argp = (void __user *)arg;
5590 switch (cmd) {
5591 case FS_IOC_GETFLAGS:
5592 return btrfs_ioctl_getflags(file, argp);
5593 case FS_IOC_SETFLAGS:
5594 return btrfs_ioctl_setflags(file, argp);
5595 case FS_IOC_GETVERSION:
5596 return btrfs_ioctl_getversion(file, argp);
5597 case FITRIM:
5598 return btrfs_ioctl_fitrim(file, argp);
5599 case BTRFS_IOC_SNAP_CREATE:
5600 return btrfs_ioctl_snap_create(file, argp, 0);
5601 case BTRFS_IOC_SNAP_CREATE_V2:
5602 return btrfs_ioctl_snap_create_v2(file, argp, 0);
5603 case BTRFS_IOC_SUBVOL_CREATE:
5604 return btrfs_ioctl_snap_create(file, argp, 1);
5605 case BTRFS_IOC_SUBVOL_CREATE_V2:
5606 return btrfs_ioctl_snap_create_v2(file, argp, 1);
5607 case BTRFS_IOC_SNAP_DESTROY:
5608 return btrfs_ioctl_snap_destroy(file, argp);
5609 case BTRFS_IOC_SUBVOL_GETFLAGS:
5610 return btrfs_ioctl_subvol_getflags(file, argp);
5611 case BTRFS_IOC_SUBVOL_SETFLAGS:
5612 return btrfs_ioctl_subvol_setflags(file, argp);
5613 case BTRFS_IOC_DEFAULT_SUBVOL:
5614 return btrfs_ioctl_default_subvol(file, argp);
5615 case BTRFS_IOC_DEFRAG:
5616 return btrfs_ioctl_defrag(file, NULL);
5617 case BTRFS_IOC_DEFRAG_RANGE:
5618 return btrfs_ioctl_defrag(file, argp);
5619 case BTRFS_IOC_RESIZE:
5620 return btrfs_ioctl_resize(file, argp);
5621 case BTRFS_IOC_ADD_DEV:
5622 return btrfs_ioctl_add_dev(fs_info, argp);
5623 case BTRFS_IOC_RM_DEV:
5624 return btrfs_ioctl_rm_dev(file, argp);
5625 case BTRFS_IOC_RM_DEV_V2:
5626 return btrfs_ioctl_rm_dev_v2(file, argp);
5627 case BTRFS_IOC_FS_INFO:
5628 return btrfs_ioctl_fs_info(fs_info, argp);
5629 case BTRFS_IOC_DEV_INFO:
5630 return btrfs_ioctl_dev_info(fs_info, argp);
5631 case BTRFS_IOC_BALANCE:
5632 return btrfs_ioctl_balance(file, NULL);
5633 case BTRFS_IOC_TRANS_START:
5634 return btrfs_ioctl_trans_start(file);
5635 case BTRFS_IOC_TRANS_END:
5636 return btrfs_ioctl_trans_end(file);
5637 case BTRFS_IOC_TREE_SEARCH:
5638 return btrfs_ioctl_tree_search(file, argp);
5639 case BTRFS_IOC_TREE_SEARCH_V2:
5640 return btrfs_ioctl_tree_search_v2(file, argp);
5641 case BTRFS_IOC_INO_LOOKUP:
5642 return btrfs_ioctl_ino_lookup(file, argp);
5643 case BTRFS_IOC_INO_PATHS:
5644 return btrfs_ioctl_ino_to_path(root, argp);
5645 case BTRFS_IOC_LOGICAL_INO:
5646 return btrfs_ioctl_logical_to_ino(fs_info, argp);
5647 case BTRFS_IOC_SPACE_INFO:
5648 return btrfs_ioctl_space_info(fs_info, argp);
5649 case BTRFS_IOC_SYNC: {
5650 int ret;
5652 ret = btrfs_start_delalloc_roots(fs_info, 0, -1);
5653 if (ret)
5654 return ret;
5655 ret = btrfs_sync_fs(inode->i_sb, 1);
5657 * The transaction thread may want to do more work,
5658 * namely it pokes the cleaner kthread that will start
5659 * processing uncleaned subvols.
5661 wake_up_process(fs_info->transaction_kthread);
5662 return ret;
5664 case BTRFS_IOC_START_SYNC:
5665 return btrfs_ioctl_start_sync(root, argp);
5666 case BTRFS_IOC_WAIT_SYNC:
5667 return btrfs_ioctl_wait_sync(fs_info, argp);
5668 case BTRFS_IOC_SCRUB:
5669 return btrfs_ioctl_scrub(file, argp);
5670 case BTRFS_IOC_SCRUB_CANCEL:
5671 return btrfs_ioctl_scrub_cancel(fs_info);
5672 case BTRFS_IOC_SCRUB_PROGRESS:
5673 return btrfs_ioctl_scrub_progress(fs_info, argp);
5674 case BTRFS_IOC_BALANCE_V2:
5675 return btrfs_ioctl_balance(file, argp);
5676 case BTRFS_IOC_BALANCE_CTL:
5677 return btrfs_ioctl_balance_ctl(fs_info, arg);
5678 case BTRFS_IOC_BALANCE_PROGRESS:
5679 return btrfs_ioctl_balance_progress(fs_info, argp);
5680 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5681 return btrfs_ioctl_set_received_subvol(file, argp);
5682 #ifdef CONFIG_64BIT
5683 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5684 return btrfs_ioctl_set_received_subvol_32(file, argp);
5685 #endif
5686 case BTRFS_IOC_SEND:
5687 return btrfs_ioctl_send(file, argp);
5688 case BTRFS_IOC_GET_DEV_STATS:
5689 return btrfs_ioctl_get_dev_stats(fs_info, argp);
5690 case BTRFS_IOC_QUOTA_CTL:
5691 return btrfs_ioctl_quota_ctl(file, argp);
5692 case BTRFS_IOC_QGROUP_ASSIGN:
5693 return btrfs_ioctl_qgroup_assign(file, argp);
5694 case BTRFS_IOC_QGROUP_CREATE:
5695 return btrfs_ioctl_qgroup_create(file, argp);
5696 case BTRFS_IOC_QGROUP_LIMIT:
5697 return btrfs_ioctl_qgroup_limit(file, argp);
5698 case BTRFS_IOC_QUOTA_RESCAN:
5699 return btrfs_ioctl_quota_rescan(file, argp);
5700 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5701 return btrfs_ioctl_quota_rescan_status(file, argp);
5702 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5703 return btrfs_ioctl_quota_rescan_wait(file, argp);
5704 case BTRFS_IOC_DEV_REPLACE:
5705 return btrfs_ioctl_dev_replace(fs_info, argp);
5706 case BTRFS_IOC_GET_FSLABEL:
5707 return btrfs_ioctl_get_fslabel(file, argp);
5708 case BTRFS_IOC_SET_FSLABEL:
5709 return btrfs_ioctl_set_fslabel(file, argp);
5710 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5711 return btrfs_ioctl_get_supported_features(argp);
5712 case BTRFS_IOC_GET_FEATURES:
5713 return btrfs_ioctl_get_features(file, argp);
5714 case BTRFS_IOC_SET_FEATURES:
5715 return btrfs_ioctl_set_features(file, argp);
5718 return -ENOTTY;
5721 #ifdef CONFIG_COMPAT
5722 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5725 * These all access 32-bit values anyway so no further
5726 * handling is necessary.
5728 switch (cmd) {
5729 case FS_IOC32_GETFLAGS:
5730 cmd = FS_IOC_GETFLAGS;
5731 break;
5732 case FS_IOC32_SETFLAGS:
5733 cmd = FS_IOC_SETFLAGS;
5734 break;
5735 case FS_IOC32_GETVERSION:
5736 cmd = FS_IOC_GETVERSION;
5737 break;
5740 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
5742 #endif