btrfs: Add "barrier" option to support "-o remount,barrier"
[platform/adaptation/renesas_rcar/renesas_kernel.git] / fs / btrfs / ioctl.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
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.
7  *
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.
12  *
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.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/fsnotify.h>
25 #include <linux/pagemap.h>
26 #include <linux/highmem.h>
27 #include <linux/time.h>
28 #include <linux/init.h>
29 #include <linux/string.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mount.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/swap.h>
35 #include <linux/writeback.h>
36 #include <linux/statfs.h>
37 #include <linux/compat.h>
38 #include <linux/bit_spinlock.h>
39 #include <linux/security.h>
40 #include <linux/xattr.h>
41 #include <linux/vmalloc.h>
42 #include <linux/slab.h>
43 #include <linux/blkdev.h>
44 #include <linux/uuid.h>
45 #include <linux/btrfs.h>
46 #include <linux/uaccess.h>
47 #include "ctree.h"
48 #include "disk-io.h"
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "volumes.h"
53 #include "locking.h"
54 #include "inode-map.h"
55 #include "backref.h"
56 #include "rcu-string.h"
57 #include "send.h"
58 #include "dev-replace.h"
59 #include "sysfs.h"
60
61 static int btrfs_clone(struct inode *src, struct inode *inode,
62                        u64 off, u64 olen, u64 olen_aligned, u64 destoff);
63
64 /* Mask out flags that are inappropriate for the given type of inode. */
65 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
66 {
67         if (S_ISDIR(mode))
68                 return flags;
69         else if (S_ISREG(mode))
70                 return flags & ~FS_DIRSYNC_FL;
71         else
72                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
73 }
74
75 /*
76  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
77  */
78 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
79 {
80         unsigned int iflags = 0;
81
82         if (flags & BTRFS_INODE_SYNC)
83                 iflags |= FS_SYNC_FL;
84         if (flags & BTRFS_INODE_IMMUTABLE)
85                 iflags |= FS_IMMUTABLE_FL;
86         if (flags & BTRFS_INODE_APPEND)
87                 iflags |= FS_APPEND_FL;
88         if (flags & BTRFS_INODE_NODUMP)
89                 iflags |= FS_NODUMP_FL;
90         if (flags & BTRFS_INODE_NOATIME)
91                 iflags |= FS_NOATIME_FL;
92         if (flags & BTRFS_INODE_DIRSYNC)
93                 iflags |= FS_DIRSYNC_FL;
94         if (flags & BTRFS_INODE_NODATACOW)
95                 iflags |= FS_NOCOW_FL;
96
97         if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
98                 iflags |= FS_COMPR_FL;
99         else if (flags & BTRFS_INODE_NOCOMPRESS)
100                 iflags |= FS_NOCOMP_FL;
101
102         return iflags;
103 }
104
105 /*
106  * Update inode->i_flags based on the btrfs internal flags.
107  */
108 void btrfs_update_iflags(struct inode *inode)
109 {
110         struct btrfs_inode *ip = BTRFS_I(inode);
111
112         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
113
114         if (ip->flags & BTRFS_INODE_SYNC)
115                 inode->i_flags |= S_SYNC;
116         if (ip->flags & BTRFS_INODE_IMMUTABLE)
117                 inode->i_flags |= S_IMMUTABLE;
118         if (ip->flags & BTRFS_INODE_APPEND)
119                 inode->i_flags |= S_APPEND;
120         if (ip->flags & BTRFS_INODE_NOATIME)
121                 inode->i_flags |= S_NOATIME;
122         if (ip->flags & BTRFS_INODE_DIRSYNC)
123                 inode->i_flags |= S_DIRSYNC;
124 }
125
126 /*
127  * Inherit flags from the parent inode.
128  *
129  * Currently only the compression flags and the cow flags are inherited.
130  */
131 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
132 {
133         unsigned int flags;
134
135         if (!dir)
136                 return;
137
138         flags = BTRFS_I(dir)->flags;
139
140         if (flags & BTRFS_INODE_NOCOMPRESS) {
141                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
142                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
143         } else if (flags & BTRFS_INODE_COMPRESS) {
144                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
145                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
146         }
147
148         if (flags & BTRFS_INODE_NODATACOW) {
149                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
150                 if (S_ISREG(inode->i_mode))
151                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
152         }
153
154         btrfs_update_iflags(inode);
155 }
156
157 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
158 {
159         struct btrfs_inode *ip = BTRFS_I(file_inode(file));
160         unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
161
162         if (copy_to_user(arg, &flags, sizeof(flags)))
163                 return -EFAULT;
164         return 0;
165 }
166
167 static int check_flags(unsigned int flags)
168 {
169         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
170                       FS_NOATIME_FL | FS_NODUMP_FL | \
171                       FS_SYNC_FL | FS_DIRSYNC_FL | \
172                       FS_NOCOMP_FL | FS_COMPR_FL |
173                       FS_NOCOW_FL))
174                 return -EOPNOTSUPP;
175
176         if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
177                 return -EINVAL;
178
179         return 0;
180 }
181
182 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
183 {
184         struct inode *inode = file_inode(file);
185         struct btrfs_inode *ip = BTRFS_I(inode);
186         struct btrfs_root *root = ip->root;
187         struct btrfs_trans_handle *trans;
188         unsigned int flags, oldflags;
189         int ret;
190         u64 ip_oldflags;
191         unsigned int i_oldflags;
192         umode_t mode;
193
194         if (btrfs_root_readonly(root))
195                 return -EROFS;
196
197         if (copy_from_user(&flags, arg, sizeof(flags)))
198                 return -EFAULT;
199
200         ret = check_flags(flags);
201         if (ret)
202                 return ret;
203
204         if (!inode_owner_or_capable(inode))
205                 return -EACCES;
206
207         ret = mnt_want_write_file(file);
208         if (ret)
209                 return ret;
210
211         mutex_lock(&inode->i_mutex);
212
213         ip_oldflags = ip->flags;
214         i_oldflags = inode->i_flags;
215         mode = inode->i_mode;
216
217         flags = btrfs_mask_flags(inode->i_mode, flags);
218         oldflags = btrfs_flags_to_ioctl(ip->flags);
219         if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
220                 if (!capable(CAP_LINUX_IMMUTABLE)) {
221                         ret = -EPERM;
222                         goto out_unlock;
223                 }
224         }
225
226         if (flags & FS_SYNC_FL)
227                 ip->flags |= BTRFS_INODE_SYNC;
228         else
229                 ip->flags &= ~BTRFS_INODE_SYNC;
230         if (flags & FS_IMMUTABLE_FL)
231                 ip->flags |= BTRFS_INODE_IMMUTABLE;
232         else
233                 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
234         if (flags & FS_APPEND_FL)
235                 ip->flags |= BTRFS_INODE_APPEND;
236         else
237                 ip->flags &= ~BTRFS_INODE_APPEND;
238         if (flags & FS_NODUMP_FL)
239                 ip->flags |= BTRFS_INODE_NODUMP;
240         else
241                 ip->flags &= ~BTRFS_INODE_NODUMP;
242         if (flags & FS_NOATIME_FL)
243                 ip->flags |= BTRFS_INODE_NOATIME;
244         else
245                 ip->flags &= ~BTRFS_INODE_NOATIME;
246         if (flags & FS_DIRSYNC_FL)
247                 ip->flags |= BTRFS_INODE_DIRSYNC;
248         else
249                 ip->flags &= ~BTRFS_INODE_DIRSYNC;
250         if (flags & FS_NOCOW_FL) {
251                 if (S_ISREG(mode)) {
252                         /*
253                          * It's safe to turn csums off here, no extents exist.
254                          * Otherwise we want the flag to reflect the real COW
255                          * status of the file and will not set it.
256                          */
257                         if (inode->i_size == 0)
258                                 ip->flags |= BTRFS_INODE_NODATACOW
259                                            | BTRFS_INODE_NODATASUM;
260                 } else {
261                         ip->flags |= BTRFS_INODE_NODATACOW;
262                 }
263         } else {
264                 /*
265                  * Revert back under same assuptions as above
266                  */
267                 if (S_ISREG(mode)) {
268                         if (inode->i_size == 0)
269                                 ip->flags &= ~(BTRFS_INODE_NODATACOW
270                                              | BTRFS_INODE_NODATASUM);
271                 } else {
272                         ip->flags &= ~BTRFS_INODE_NODATACOW;
273                 }
274         }
275
276         /*
277          * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
278          * flag may be changed automatically if compression code won't make
279          * things smaller.
280          */
281         if (flags & FS_NOCOMP_FL) {
282                 ip->flags &= ~BTRFS_INODE_COMPRESS;
283                 ip->flags |= BTRFS_INODE_NOCOMPRESS;
284         } else if (flags & FS_COMPR_FL) {
285                 ip->flags |= BTRFS_INODE_COMPRESS;
286                 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
287         } else {
288                 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
289         }
290
291         trans = btrfs_start_transaction(root, 1);
292         if (IS_ERR(trans)) {
293                 ret = PTR_ERR(trans);
294                 goto out_drop;
295         }
296
297         btrfs_update_iflags(inode);
298         inode_inc_iversion(inode);
299         inode->i_ctime = CURRENT_TIME;
300         ret = btrfs_update_inode(trans, root, inode);
301
302         btrfs_end_transaction(trans, root);
303  out_drop:
304         if (ret) {
305                 ip->flags = ip_oldflags;
306                 inode->i_flags = i_oldflags;
307         }
308
309  out_unlock:
310         mutex_unlock(&inode->i_mutex);
311         mnt_drop_write_file(file);
312         return ret;
313 }
314
315 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
316 {
317         struct inode *inode = file_inode(file);
318
319         return put_user(inode->i_generation, arg);
320 }
321
322 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
323 {
324         struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
325         struct btrfs_device *device;
326         struct request_queue *q;
327         struct fstrim_range range;
328         u64 minlen = ULLONG_MAX;
329         u64 num_devices = 0;
330         u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
331         int ret;
332
333         if (!capable(CAP_SYS_ADMIN))
334                 return -EPERM;
335
336         rcu_read_lock();
337         list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
338                                 dev_list) {
339                 if (!device->bdev)
340                         continue;
341                 q = bdev_get_queue(device->bdev);
342                 if (blk_queue_discard(q)) {
343                         num_devices++;
344                         minlen = min((u64)q->limits.discard_granularity,
345                                      minlen);
346                 }
347         }
348         rcu_read_unlock();
349
350         if (!num_devices)
351                 return -EOPNOTSUPP;
352         if (copy_from_user(&range, arg, sizeof(range)))
353                 return -EFAULT;
354         if (range.start > total_bytes ||
355             range.len < fs_info->sb->s_blocksize)
356                 return -EINVAL;
357
358         range.len = min(range.len, total_bytes - range.start);
359         range.minlen = max(range.minlen, minlen);
360         ret = btrfs_trim_fs(fs_info->tree_root, &range);
361         if (ret < 0)
362                 return ret;
363
364         if (copy_to_user(arg, &range, sizeof(range)))
365                 return -EFAULT;
366
367         return 0;
368 }
369
370 int btrfs_is_empty_uuid(u8 *uuid)
371 {
372         int i;
373
374         for (i = 0; i < BTRFS_UUID_SIZE; i++) {
375                 if (uuid[i])
376                         return 0;
377         }
378         return 1;
379 }
380
381 static noinline int create_subvol(struct inode *dir,
382                                   struct dentry *dentry,
383                                   char *name, int namelen,
384                                   u64 *async_transid,
385                                   struct btrfs_qgroup_inherit *inherit)
386 {
387         struct btrfs_trans_handle *trans;
388         struct btrfs_key key;
389         struct btrfs_root_item root_item;
390         struct btrfs_inode_item *inode_item;
391         struct extent_buffer *leaf;
392         struct btrfs_root *root = BTRFS_I(dir)->root;
393         struct btrfs_root *new_root;
394         struct btrfs_block_rsv block_rsv;
395         struct timespec cur_time = CURRENT_TIME;
396         struct inode *inode;
397         int ret;
398         int err;
399         u64 objectid;
400         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
401         u64 index = 0;
402         u64 qgroup_reserved;
403         uuid_le new_uuid;
404
405         ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
406         if (ret)
407                 return ret;
408
409         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
410         /*
411          * The same as the snapshot creation, please see the comment
412          * of create_snapshot().
413          */
414         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
415                                                8, &qgroup_reserved, false);
416         if (ret)
417                 return ret;
418
419         trans = btrfs_start_transaction(root, 0);
420         if (IS_ERR(trans)) {
421                 ret = PTR_ERR(trans);
422                 goto out;
423         }
424         trans->block_rsv = &block_rsv;
425         trans->bytes_reserved = block_rsv.size;
426
427         ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
428         if (ret)
429                 goto fail;
430
431         leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
432                                       0, objectid, NULL, 0, 0, 0);
433         if (IS_ERR(leaf)) {
434                 ret = PTR_ERR(leaf);
435                 goto fail;
436         }
437
438         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
439         btrfs_set_header_bytenr(leaf, leaf->start);
440         btrfs_set_header_generation(leaf, trans->transid);
441         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
442         btrfs_set_header_owner(leaf, objectid);
443
444         write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
445                             BTRFS_FSID_SIZE);
446         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
447                             btrfs_header_chunk_tree_uuid(leaf),
448                             BTRFS_UUID_SIZE);
449         btrfs_mark_buffer_dirty(leaf);
450
451         memset(&root_item, 0, sizeof(root_item));
452
453         inode_item = &root_item.inode;
454         btrfs_set_stack_inode_generation(inode_item, 1);
455         btrfs_set_stack_inode_size(inode_item, 3);
456         btrfs_set_stack_inode_nlink(inode_item, 1);
457         btrfs_set_stack_inode_nbytes(inode_item, root->leafsize);
458         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
459
460         btrfs_set_root_flags(&root_item, 0);
461         btrfs_set_root_limit(&root_item, 0);
462         btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
463
464         btrfs_set_root_bytenr(&root_item, leaf->start);
465         btrfs_set_root_generation(&root_item, trans->transid);
466         btrfs_set_root_level(&root_item, 0);
467         btrfs_set_root_refs(&root_item, 1);
468         btrfs_set_root_used(&root_item, leaf->len);
469         btrfs_set_root_last_snapshot(&root_item, 0);
470
471         btrfs_set_root_generation_v2(&root_item,
472                         btrfs_root_generation(&root_item));
473         uuid_le_gen(&new_uuid);
474         memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
475         btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
476         btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
477         root_item.ctime = root_item.otime;
478         btrfs_set_root_ctransid(&root_item, trans->transid);
479         btrfs_set_root_otransid(&root_item, trans->transid);
480
481         btrfs_tree_unlock(leaf);
482         free_extent_buffer(leaf);
483         leaf = NULL;
484
485         btrfs_set_root_dirid(&root_item, new_dirid);
486
487         key.objectid = objectid;
488         key.offset = 0;
489         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
490         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
491                                 &root_item);
492         if (ret)
493                 goto fail;
494
495         key.offset = (u64)-1;
496         new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
497         if (IS_ERR(new_root)) {
498                 btrfs_abort_transaction(trans, root, PTR_ERR(new_root));
499                 ret = PTR_ERR(new_root);
500                 goto fail;
501         }
502
503         btrfs_record_root_in_trans(trans, new_root);
504
505         ret = btrfs_create_subvol_root(trans, new_root, new_dirid);
506         if (ret) {
507                 /* We potentially lose an unused inode item here */
508                 btrfs_abort_transaction(trans, root, ret);
509                 goto fail;
510         }
511
512         /*
513          * insert the directory item
514          */
515         ret = btrfs_set_inode_index(dir, &index);
516         if (ret) {
517                 btrfs_abort_transaction(trans, root, ret);
518                 goto fail;
519         }
520
521         ret = btrfs_insert_dir_item(trans, root,
522                                     name, namelen, dir, &key,
523                                     BTRFS_FT_DIR, index);
524         if (ret) {
525                 btrfs_abort_transaction(trans, root, ret);
526                 goto fail;
527         }
528
529         btrfs_i_size_write(dir, dir->i_size + namelen * 2);
530         ret = btrfs_update_inode(trans, root, dir);
531         BUG_ON(ret);
532
533         ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
534                                  objectid, root->root_key.objectid,
535                                  btrfs_ino(dir), index, name, namelen);
536         BUG_ON(ret);
537
538         ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
539                                   root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
540                                   objectid);
541         if (ret)
542                 btrfs_abort_transaction(trans, root, ret);
543
544 fail:
545         trans->block_rsv = NULL;
546         trans->bytes_reserved = 0;
547         if (async_transid) {
548                 *async_transid = trans->transid;
549                 err = btrfs_commit_transaction_async(trans, root, 1);
550                 if (err)
551                         err = btrfs_commit_transaction(trans, root);
552         } else {
553                 err = btrfs_commit_transaction(trans, root);
554         }
555         if (err && !ret)
556                 ret = err;
557
558         if (!ret) {
559                 inode = btrfs_lookup_dentry(dir, dentry);
560                 if (IS_ERR(inode)) {
561                         ret = PTR_ERR(inode);
562                         goto out;
563                 }
564                 d_instantiate(dentry, inode);
565         }
566 out:
567         btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
568         return ret;
569 }
570
571 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
572                            struct dentry *dentry, char *name, int namelen,
573                            u64 *async_transid, bool readonly,
574                            struct btrfs_qgroup_inherit *inherit)
575 {
576         struct inode *inode;
577         struct btrfs_pending_snapshot *pending_snapshot;
578         struct btrfs_trans_handle *trans;
579         int ret;
580
581         if (!root->ref_cows)
582                 return -EINVAL;
583
584         ret = btrfs_start_delalloc_inodes(root, 0);
585         if (ret)
586                 return ret;
587
588         btrfs_wait_ordered_extents(root, -1);
589
590         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
591         if (!pending_snapshot)
592                 return -ENOMEM;
593
594         btrfs_init_block_rsv(&pending_snapshot->block_rsv,
595                              BTRFS_BLOCK_RSV_TEMP);
596         /*
597          * 1 - parent dir inode
598          * 2 - dir entries
599          * 1 - root item
600          * 2 - root ref/backref
601          * 1 - root of snapshot
602          * 1 - UUID item
603          */
604         ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
605                                         &pending_snapshot->block_rsv, 8,
606                                         &pending_snapshot->qgroup_reserved,
607                                         false);
608         if (ret)
609                 goto out;
610
611         pending_snapshot->dentry = dentry;
612         pending_snapshot->root = root;
613         pending_snapshot->readonly = readonly;
614         pending_snapshot->dir = dir;
615         pending_snapshot->inherit = inherit;
616
617         trans = btrfs_start_transaction(root, 0);
618         if (IS_ERR(trans)) {
619                 ret = PTR_ERR(trans);
620                 goto fail;
621         }
622
623         spin_lock(&root->fs_info->trans_lock);
624         list_add(&pending_snapshot->list,
625                  &trans->transaction->pending_snapshots);
626         spin_unlock(&root->fs_info->trans_lock);
627         if (async_transid) {
628                 *async_transid = trans->transid;
629                 ret = btrfs_commit_transaction_async(trans,
630                                      root->fs_info->extent_root, 1);
631                 if (ret)
632                         ret = btrfs_commit_transaction(trans, root);
633         } else {
634                 ret = btrfs_commit_transaction(trans,
635                                                root->fs_info->extent_root);
636         }
637         if (ret)
638                 goto fail;
639
640         ret = pending_snapshot->error;
641         if (ret)
642                 goto fail;
643
644         ret = btrfs_orphan_cleanup(pending_snapshot->snap);
645         if (ret)
646                 goto fail;
647
648         inode = btrfs_lookup_dentry(dentry->d_parent->d_inode, dentry);
649         if (IS_ERR(inode)) {
650                 ret = PTR_ERR(inode);
651                 goto fail;
652         }
653
654         d_instantiate(dentry, inode);
655         ret = 0;
656 fail:
657         btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
658                                          &pending_snapshot->block_rsv,
659                                          pending_snapshot->qgroup_reserved);
660 out:
661         kfree(pending_snapshot);
662         return ret;
663 }
664
665 /*  copy of check_sticky in fs/namei.c()
666 * It's inline, so penalty for filesystems that don't use sticky bit is
667 * minimal.
668 */
669 static inline int btrfs_check_sticky(struct inode *dir, struct inode *inode)
670 {
671         kuid_t fsuid = current_fsuid();
672
673         if (!(dir->i_mode & S_ISVTX))
674                 return 0;
675         if (uid_eq(inode->i_uid, fsuid))
676                 return 0;
677         if (uid_eq(dir->i_uid, fsuid))
678                 return 0;
679         return !capable(CAP_FOWNER);
680 }
681
682 /*  copy of may_delete in fs/namei.c()
683  *      Check whether we can remove a link victim from directory dir, check
684  *  whether the type of victim is right.
685  *  1. We can't do it if dir is read-only (done in permission())
686  *  2. We should have write and exec permissions on dir
687  *  3. We can't remove anything from append-only dir
688  *  4. We can't do anything with immutable dir (done in permission())
689  *  5. If the sticky bit on dir is set we should either
690  *      a. be owner of dir, or
691  *      b. be owner of victim, or
692  *      c. have CAP_FOWNER capability
693  *  6. If the victim is append-only or immutable we can't do antyhing with
694  *     links pointing to it.
695  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
696  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
697  *  9. We can't remove a root or mountpoint.
698  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
699  *     nfs_async_unlink().
700  */
701
702 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
703 {
704         int error;
705
706         if (!victim->d_inode)
707                 return -ENOENT;
708
709         BUG_ON(victim->d_parent->d_inode != dir);
710         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
711
712         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
713         if (error)
714                 return error;
715         if (IS_APPEND(dir))
716                 return -EPERM;
717         if (btrfs_check_sticky(dir, victim->d_inode)||
718                 IS_APPEND(victim->d_inode)||
719             IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
720                 return -EPERM;
721         if (isdir) {
722                 if (!S_ISDIR(victim->d_inode->i_mode))
723                         return -ENOTDIR;
724                 if (IS_ROOT(victim))
725                         return -EBUSY;
726         } else if (S_ISDIR(victim->d_inode->i_mode))
727                 return -EISDIR;
728         if (IS_DEADDIR(dir))
729                 return -ENOENT;
730         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
731                 return -EBUSY;
732         return 0;
733 }
734
735 /* copy of may_create in fs/namei.c() */
736 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
737 {
738         if (child->d_inode)
739                 return -EEXIST;
740         if (IS_DEADDIR(dir))
741                 return -ENOENT;
742         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
743 }
744
745 /*
746  * Create a new subvolume below @parent.  This is largely modeled after
747  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
748  * inside this filesystem so it's quite a bit simpler.
749  */
750 static noinline int btrfs_mksubvol(struct path *parent,
751                                    char *name, int namelen,
752                                    struct btrfs_root *snap_src,
753                                    u64 *async_transid, bool readonly,
754                                    struct btrfs_qgroup_inherit *inherit)
755 {
756         struct inode *dir  = parent->dentry->d_inode;
757         struct dentry *dentry;
758         int error;
759
760         error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
761         if (error == -EINTR)
762                 return error;
763
764         dentry = lookup_one_len(name, parent->dentry, namelen);
765         error = PTR_ERR(dentry);
766         if (IS_ERR(dentry))
767                 goto out_unlock;
768
769         error = -EEXIST;
770         if (dentry->d_inode)
771                 goto out_dput;
772
773         error = btrfs_may_create(dir, dentry);
774         if (error)
775                 goto out_dput;
776
777         /*
778          * even if this name doesn't exist, we may get hash collisions.
779          * check for them now when we can safely fail
780          */
781         error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
782                                                dir->i_ino, name,
783                                                namelen);
784         if (error)
785                 goto out_dput;
786
787         down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
788
789         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
790                 goto out_up_read;
791
792         if (snap_src) {
793                 error = create_snapshot(snap_src, dir, dentry, name, namelen,
794                                         async_transid, readonly, inherit);
795         } else {
796                 error = create_subvol(dir, dentry, name, namelen,
797                                       async_transid, inherit);
798         }
799         if (!error)
800                 fsnotify_mkdir(dir, dentry);
801 out_up_read:
802         up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
803 out_dput:
804         dput(dentry);
805 out_unlock:
806         mutex_unlock(&dir->i_mutex);
807         return error;
808 }
809
810 /*
811  * When we're defragging a range, we don't want to kick it off again
812  * if it is really just waiting for delalloc to send it down.
813  * If we find a nice big extent or delalloc range for the bytes in the
814  * file you want to defrag, we return 0 to let you know to skip this
815  * part of the file
816  */
817 static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh)
818 {
819         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
820         struct extent_map *em = NULL;
821         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
822         u64 end;
823
824         read_lock(&em_tree->lock);
825         em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
826         read_unlock(&em_tree->lock);
827
828         if (em) {
829                 end = extent_map_end(em);
830                 free_extent_map(em);
831                 if (end - offset > thresh)
832                         return 0;
833         }
834         /* if we already have a nice delalloc here, just stop */
835         thresh /= 2;
836         end = count_range_bits(io_tree, &offset, offset + thresh,
837                                thresh, EXTENT_DELALLOC, 1);
838         if (end >= thresh)
839                 return 0;
840         return 1;
841 }
842
843 /*
844  * helper function to walk through a file and find extents
845  * newer than a specific transid, and smaller than thresh.
846  *
847  * This is used by the defragging code to find new and small
848  * extents
849  */
850 static int find_new_extents(struct btrfs_root *root,
851                             struct inode *inode, u64 newer_than,
852                             u64 *off, int thresh)
853 {
854         struct btrfs_path *path;
855         struct btrfs_key min_key;
856         struct extent_buffer *leaf;
857         struct btrfs_file_extent_item *extent;
858         int type;
859         int ret;
860         u64 ino = btrfs_ino(inode);
861
862         path = btrfs_alloc_path();
863         if (!path)
864                 return -ENOMEM;
865
866         min_key.objectid = ino;
867         min_key.type = BTRFS_EXTENT_DATA_KEY;
868         min_key.offset = *off;
869
870         path->keep_locks = 1;
871
872         while (1) {
873                 ret = btrfs_search_forward(root, &min_key, path, newer_than);
874                 if (ret != 0)
875                         goto none;
876                 if (min_key.objectid != ino)
877                         goto none;
878                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
879                         goto none;
880
881                 leaf = path->nodes[0];
882                 extent = btrfs_item_ptr(leaf, path->slots[0],
883                                         struct btrfs_file_extent_item);
884
885                 type = btrfs_file_extent_type(leaf, extent);
886                 if (type == BTRFS_FILE_EXTENT_REG &&
887                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
888                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
889                         *off = min_key.offset;
890                         btrfs_free_path(path);
891                         return 0;
892                 }
893
894                 if (min_key.offset == (u64)-1)
895                         goto none;
896
897                 min_key.offset++;
898                 btrfs_release_path(path);
899         }
900 none:
901         btrfs_free_path(path);
902         return -ENOENT;
903 }
904
905 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
906 {
907         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
908         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
909         struct extent_map *em;
910         u64 len = PAGE_CACHE_SIZE;
911
912         /*
913          * hopefully we have this extent in the tree already, try without
914          * the full extent lock
915          */
916         read_lock(&em_tree->lock);
917         em = lookup_extent_mapping(em_tree, start, len);
918         read_unlock(&em_tree->lock);
919
920         if (!em) {
921                 /* get the big lock and read metadata off disk */
922                 lock_extent(io_tree, start, start + len - 1);
923                 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
924                 unlock_extent(io_tree, start, start + len - 1);
925
926                 if (IS_ERR(em))
927                         return NULL;
928         }
929
930         return em;
931 }
932
933 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
934 {
935         struct extent_map *next;
936         bool ret = true;
937
938         /* this is the last extent */
939         if (em->start + em->len >= i_size_read(inode))
940                 return false;
941
942         next = defrag_lookup_extent(inode, em->start + em->len);
943         if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
944                 ret = false;
945
946         free_extent_map(next);
947         return ret;
948 }
949
950 static int should_defrag_range(struct inode *inode, u64 start, int thresh,
951                                u64 *last_len, u64 *skip, u64 *defrag_end,
952                                int compress)
953 {
954         struct extent_map *em;
955         int ret = 1;
956         bool next_mergeable = true;
957
958         /*
959          * make sure that once we start defragging an extent, we keep on
960          * defragging it
961          */
962         if (start < *defrag_end)
963                 return 1;
964
965         *skip = 0;
966
967         em = defrag_lookup_extent(inode, start);
968         if (!em)
969                 return 0;
970
971         /* this will cover holes, and inline extents */
972         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
973                 ret = 0;
974                 goto out;
975         }
976
977         next_mergeable = defrag_check_next_extent(inode, em);
978
979         /*
980          * we hit a real extent, if it is big or the next extent is not a
981          * real extent, don't bother defragging it
982          */
983         if (!compress && (*last_len == 0 || *last_len >= thresh) &&
984             (em->len >= thresh || !next_mergeable))
985                 ret = 0;
986 out:
987         /*
988          * last_len ends up being a counter of how many bytes we've defragged.
989          * every time we choose not to defrag an extent, we reset *last_len
990          * so that the next tiny extent will force a defrag.
991          *
992          * The end result of this is that tiny extents before a single big
993          * extent will force at least part of that big extent to be defragged.
994          */
995         if (ret) {
996                 *defrag_end = extent_map_end(em);
997         } else {
998                 *last_len = 0;
999                 *skip = extent_map_end(em);
1000                 *defrag_end = 0;
1001         }
1002
1003         free_extent_map(em);
1004         return ret;
1005 }
1006
1007 /*
1008  * it doesn't do much good to defrag one or two pages
1009  * at a time.  This pulls in a nice chunk of pages
1010  * to COW and defrag.
1011  *
1012  * It also makes sure the delalloc code has enough
1013  * dirty data to avoid making new small extents as part
1014  * of the defrag
1015  *
1016  * It's a good idea to start RA on this range
1017  * before calling this.
1018  */
1019 static int cluster_pages_for_defrag(struct inode *inode,
1020                                     struct page **pages,
1021                                     unsigned long start_index,
1022                                     int num_pages)
1023 {
1024         unsigned long file_end;
1025         u64 isize = i_size_read(inode);
1026         u64 page_start;
1027         u64 page_end;
1028         u64 page_cnt;
1029         int ret;
1030         int i;
1031         int i_done;
1032         struct btrfs_ordered_extent *ordered;
1033         struct extent_state *cached_state = NULL;
1034         struct extent_io_tree *tree;
1035         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1036
1037         file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1038         if (!isize || start_index > file_end)
1039                 return 0;
1040
1041         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1042
1043         ret = btrfs_delalloc_reserve_space(inode,
1044                                            page_cnt << PAGE_CACHE_SHIFT);
1045         if (ret)
1046                 return ret;
1047         i_done = 0;
1048         tree = &BTRFS_I(inode)->io_tree;
1049
1050         /* step one, lock all the pages */
1051         for (i = 0; i < page_cnt; i++) {
1052                 struct page *page;
1053 again:
1054                 page = find_or_create_page(inode->i_mapping,
1055                                            start_index + i, mask);
1056                 if (!page)
1057                         break;
1058
1059                 page_start = page_offset(page);
1060                 page_end = page_start + PAGE_CACHE_SIZE - 1;
1061                 while (1) {
1062                         lock_extent(tree, page_start, page_end);
1063                         ordered = btrfs_lookup_ordered_extent(inode,
1064                                                               page_start);
1065                         unlock_extent(tree, page_start, page_end);
1066                         if (!ordered)
1067                                 break;
1068
1069                         unlock_page(page);
1070                         btrfs_start_ordered_extent(inode, ordered, 1);
1071                         btrfs_put_ordered_extent(ordered);
1072                         lock_page(page);
1073                         /*
1074                          * we unlocked the page above, so we need check if
1075                          * it was released or not.
1076                          */
1077                         if (page->mapping != inode->i_mapping) {
1078                                 unlock_page(page);
1079                                 page_cache_release(page);
1080                                 goto again;
1081                         }
1082                 }
1083
1084                 if (!PageUptodate(page)) {
1085                         btrfs_readpage(NULL, page);
1086                         lock_page(page);
1087                         if (!PageUptodate(page)) {
1088                                 unlock_page(page);
1089                                 page_cache_release(page);
1090                                 ret = -EIO;
1091                                 break;
1092                         }
1093                 }
1094
1095                 if (page->mapping != inode->i_mapping) {
1096                         unlock_page(page);
1097                         page_cache_release(page);
1098                         goto again;
1099                 }
1100
1101                 pages[i] = page;
1102                 i_done++;
1103         }
1104         if (!i_done || ret)
1105                 goto out;
1106
1107         if (!(inode->i_sb->s_flags & MS_ACTIVE))
1108                 goto out;
1109
1110         /*
1111          * so now we have a nice long stream of locked
1112          * and up to date pages, lets wait on them
1113          */
1114         for (i = 0; i < i_done; i++)
1115                 wait_on_page_writeback(pages[i]);
1116
1117         page_start = page_offset(pages[0]);
1118         page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1119
1120         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1121                          page_start, page_end - 1, 0, &cached_state);
1122         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1123                           page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1124                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1125                           &cached_state, GFP_NOFS);
1126
1127         if (i_done != page_cnt) {
1128                 spin_lock(&BTRFS_I(inode)->lock);
1129                 BTRFS_I(inode)->outstanding_extents++;
1130                 spin_unlock(&BTRFS_I(inode)->lock);
1131                 btrfs_delalloc_release_space(inode,
1132                                      (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1133         }
1134
1135
1136         set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1137                           &cached_state, GFP_NOFS);
1138
1139         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1140                              page_start, page_end - 1, &cached_state,
1141                              GFP_NOFS);
1142
1143         for (i = 0; i < i_done; i++) {
1144                 clear_page_dirty_for_io(pages[i]);
1145                 ClearPageChecked(pages[i]);
1146                 set_page_extent_mapped(pages[i]);
1147                 set_page_dirty(pages[i]);
1148                 unlock_page(pages[i]);
1149                 page_cache_release(pages[i]);
1150         }
1151         return i_done;
1152 out:
1153         for (i = 0; i < i_done; i++) {
1154                 unlock_page(pages[i]);
1155                 page_cache_release(pages[i]);
1156         }
1157         btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1158         return ret;
1159
1160 }
1161
1162 int btrfs_defrag_file(struct inode *inode, struct file *file,
1163                       struct btrfs_ioctl_defrag_range_args *range,
1164                       u64 newer_than, unsigned long max_to_defrag)
1165 {
1166         struct btrfs_root *root = BTRFS_I(inode)->root;
1167         struct file_ra_state *ra = NULL;
1168         unsigned long last_index;
1169         u64 isize = i_size_read(inode);
1170         u64 last_len = 0;
1171         u64 skip = 0;
1172         u64 defrag_end = 0;
1173         u64 newer_off = range->start;
1174         unsigned long i;
1175         unsigned long ra_index = 0;
1176         int ret;
1177         int defrag_count = 0;
1178         int compress_type = BTRFS_COMPRESS_ZLIB;
1179         int extent_thresh = range->extent_thresh;
1180         int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1181         int cluster = max_cluster;
1182         u64 new_align = ~((u64)128 * 1024 - 1);
1183         struct page **pages = NULL;
1184
1185         if (isize == 0)
1186                 return 0;
1187
1188         if (range->start >= isize)
1189                 return -EINVAL;
1190
1191         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1192                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1193                         return -EINVAL;
1194                 if (range->compress_type)
1195                         compress_type = range->compress_type;
1196         }
1197
1198         if (extent_thresh == 0)
1199                 extent_thresh = 256 * 1024;
1200
1201         /*
1202          * if we were not given a file, allocate a readahead
1203          * context
1204          */
1205         if (!file) {
1206                 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1207                 if (!ra)
1208                         return -ENOMEM;
1209                 file_ra_state_init(ra, inode->i_mapping);
1210         } else {
1211                 ra = &file->f_ra;
1212         }
1213
1214         pages = kmalloc_array(max_cluster, sizeof(struct page *),
1215                         GFP_NOFS);
1216         if (!pages) {
1217                 ret = -ENOMEM;
1218                 goto out_ra;
1219         }
1220
1221         /* find the last page to defrag */
1222         if (range->start + range->len > range->start) {
1223                 last_index = min_t(u64, isize - 1,
1224                          range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1225         } else {
1226                 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1227         }
1228
1229         if (newer_than) {
1230                 ret = find_new_extents(root, inode, newer_than,
1231                                        &newer_off, 64 * 1024);
1232                 if (!ret) {
1233                         range->start = newer_off;
1234                         /*
1235                          * we always align our defrag to help keep
1236                          * the extents in the file evenly spaced
1237                          */
1238                         i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1239                 } else
1240                         goto out_ra;
1241         } else {
1242                 i = range->start >> PAGE_CACHE_SHIFT;
1243         }
1244         if (!max_to_defrag)
1245                 max_to_defrag = last_index + 1;
1246
1247         /*
1248          * make writeback starts from i, so the defrag range can be
1249          * written sequentially.
1250          */
1251         if (i < inode->i_mapping->writeback_index)
1252                 inode->i_mapping->writeback_index = i;
1253
1254         while (i <= last_index && defrag_count < max_to_defrag &&
1255                (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
1256                 PAGE_CACHE_SHIFT)) {
1257                 /*
1258                  * make sure we stop running if someone unmounts
1259                  * the FS
1260                  */
1261                 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1262                         break;
1263
1264                 if (btrfs_defrag_cancelled(root->fs_info)) {
1265                         printk(KERN_DEBUG "BTRFS: defrag_file cancelled\n");
1266                         ret = -EAGAIN;
1267                         break;
1268                 }
1269
1270                 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1271                                          extent_thresh, &last_len, &skip,
1272                                          &defrag_end, range->flags &
1273                                          BTRFS_DEFRAG_RANGE_COMPRESS)) {
1274                         unsigned long next;
1275                         /*
1276                          * the should_defrag function tells us how much to skip
1277                          * bump our counter by the suggested amount
1278                          */
1279                         next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1280                         i = max(i + 1, next);
1281                         continue;
1282                 }
1283
1284                 if (!newer_than) {
1285                         cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1286                                    PAGE_CACHE_SHIFT) - i;
1287                         cluster = min(cluster, max_cluster);
1288                 } else {
1289                         cluster = max_cluster;
1290                 }
1291
1292                 if (i + cluster > ra_index) {
1293                         ra_index = max(i, ra_index);
1294                         btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1295                                        cluster);
1296                         ra_index += max_cluster;
1297                 }
1298
1299                 mutex_lock(&inode->i_mutex);
1300                 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1301                         BTRFS_I(inode)->force_compress = compress_type;
1302                 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1303                 if (ret < 0) {
1304                         mutex_unlock(&inode->i_mutex);
1305                         goto out_ra;
1306                 }
1307
1308                 defrag_count += ret;
1309                 balance_dirty_pages_ratelimited(inode->i_mapping);
1310                 mutex_unlock(&inode->i_mutex);
1311
1312                 if (newer_than) {
1313                         if (newer_off == (u64)-1)
1314                                 break;
1315
1316                         if (ret > 0)
1317                                 i += ret;
1318
1319                         newer_off = max(newer_off + 1,
1320                                         (u64)i << PAGE_CACHE_SHIFT);
1321
1322                         ret = find_new_extents(root, inode,
1323                                                newer_than, &newer_off,
1324                                                64 * 1024);
1325                         if (!ret) {
1326                                 range->start = newer_off;
1327                                 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1328                         } else {
1329                                 break;
1330                         }
1331                 } else {
1332                         if (ret > 0) {
1333                                 i += ret;
1334                                 last_len += ret << PAGE_CACHE_SHIFT;
1335                         } else {
1336                                 i++;
1337                                 last_len = 0;
1338                         }
1339                 }
1340         }
1341
1342         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
1343                 filemap_flush(inode->i_mapping);
1344
1345         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1346                 /* the filemap_flush will queue IO into the worker threads, but
1347                  * we have to make sure the IO is actually started and that
1348                  * ordered extents get created before we return
1349                  */
1350                 atomic_inc(&root->fs_info->async_submit_draining);
1351                 while (atomic_read(&root->fs_info->nr_async_submits) ||
1352                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1353                         wait_event(root->fs_info->async_submit_wait,
1354                            (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1355                             atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1356                 }
1357                 atomic_dec(&root->fs_info->async_submit_draining);
1358         }
1359
1360         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1361                 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1362         }
1363
1364         ret = defrag_count;
1365
1366 out_ra:
1367         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1368                 mutex_lock(&inode->i_mutex);
1369                 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1370                 mutex_unlock(&inode->i_mutex);
1371         }
1372         if (!file)
1373                 kfree(ra);
1374         kfree(pages);
1375         return ret;
1376 }
1377
1378 static noinline int btrfs_ioctl_resize(struct file *file,
1379                                         void __user *arg)
1380 {
1381         u64 new_size;
1382         u64 old_size;
1383         u64 devid = 1;
1384         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1385         struct btrfs_ioctl_vol_args *vol_args;
1386         struct btrfs_trans_handle *trans;
1387         struct btrfs_device *device = NULL;
1388         char *sizestr;
1389         char *devstr = NULL;
1390         int ret = 0;
1391         int mod = 0;
1392
1393         if (!capable(CAP_SYS_ADMIN))
1394                 return -EPERM;
1395
1396         ret = mnt_want_write_file(file);
1397         if (ret)
1398                 return ret;
1399
1400         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1401                         1)) {
1402                 mnt_drop_write_file(file);
1403                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1404         }
1405
1406         mutex_lock(&root->fs_info->volume_mutex);
1407         vol_args = memdup_user(arg, sizeof(*vol_args));
1408         if (IS_ERR(vol_args)) {
1409                 ret = PTR_ERR(vol_args);
1410                 goto out;
1411         }
1412
1413         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1414
1415         sizestr = vol_args->name;
1416         devstr = strchr(sizestr, ':');
1417         if (devstr) {
1418                 char *end;
1419                 sizestr = devstr + 1;
1420                 *devstr = '\0';
1421                 devstr = vol_args->name;
1422                 devid = simple_strtoull(devstr, &end, 10);
1423                 if (!devid) {
1424                         ret = -EINVAL;
1425                         goto out_free;
1426                 }
1427                 btrfs_info(root->fs_info, "resizing devid %llu", devid);
1428         }
1429
1430         device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1431         if (!device) {
1432                 btrfs_info(root->fs_info, "resizer unable to find device %llu",
1433                        devid);
1434                 ret = -ENODEV;
1435                 goto out_free;
1436         }
1437
1438         if (!device->writeable) {
1439                 btrfs_info(root->fs_info,
1440                            "resizer unable to apply on readonly device %llu",
1441                        devid);
1442                 ret = -EPERM;
1443                 goto out_free;
1444         }
1445
1446         if (!strcmp(sizestr, "max"))
1447                 new_size = device->bdev->bd_inode->i_size;
1448         else {
1449                 if (sizestr[0] == '-') {
1450                         mod = -1;
1451                         sizestr++;
1452                 } else if (sizestr[0] == '+') {
1453                         mod = 1;
1454                         sizestr++;
1455                 }
1456                 new_size = memparse(sizestr, NULL);
1457                 if (new_size == 0) {
1458                         ret = -EINVAL;
1459                         goto out_free;
1460                 }
1461         }
1462
1463         if (device->is_tgtdev_for_dev_replace) {
1464                 ret = -EPERM;
1465                 goto out_free;
1466         }
1467
1468         old_size = device->total_bytes;
1469
1470         if (mod < 0) {
1471                 if (new_size > old_size) {
1472                         ret = -EINVAL;
1473                         goto out_free;
1474                 }
1475                 new_size = old_size - new_size;
1476         } else if (mod > 0) {
1477                 if (new_size > ULLONG_MAX - old_size) {
1478                         ret = -EINVAL;
1479                         goto out_free;
1480                 }
1481                 new_size = old_size + new_size;
1482         }
1483
1484         if (new_size < 256 * 1024 * 1024) {
1485                 ret = -EINVAL;
1486                 goto out_free;
1487         }
1488         if (new_size > device->bdev->bd_inode->i_size) {
1489                 ret = -EFBIG;
1490                 goto out_free;
1491         }
1492
1493         do_div(new_size, root->sectorsize);
1494         new_size *= root->sectorsize;
1495
1496         printk_in_rcu(KERN_INFO "BTRFS: new size for %s is %llu\n",
1497                       rcu_str_deref(device->name), new_size);
1498
1499         if (new_size > old_size) {
1500                 trans = btrfs_start_transaction(root, 0);
1501                 if (IS_ERR(trans)) {
1502                         ret = PTR_ERR(trans);
1503                         goto out_free;
1504                 }
1505                 ret = btrfs_grow_device(trans, device, new_size);
1506                 btrfs_commit_transaction(trans, root);
1507         } else if (new_size < old_size) {
1508                 ret = btrfs_shrink_device(device, new_size);
1509         } /* equal, nothing need to do */
1510
1511 out_free:
1512         kfree(vol_args);
1513 out:
1514         mutex_unlock(&root->fs_info->volume_mutex);
1515         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1516         mnt_drop_write_file(file);
1517         return ret;
1518 }
1519
1520 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1521                                 char *name, unsigned long fd, int subvol,
1522                                 u64 *transid, bool readonly,
1523                                 struct btrfs_qgroup_inherit *inherit)
1524 {
1525         int namelen;
1526         int ret = 0;
1527
1528         ret = mnt_want_write_file(file);
1529         if (ret)
1530                 goto out;
1531
1532         namelen = strlen(name);
1533         if (strchr(name, '/')) {
1534                 ret = -EINVAL;
1535                 goto out_drop_write;
1536         }
1537
1538         if (name[0] == '.' &&
1539            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1540                 ret = -EEXIST;
1541                 goto out_drop_write;
1542         }
1543
1544         if (subvol) {
1545                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1546                                      NULL, transid, readonly, inherit);
1547         } else {
1548                 struct fd src = fdget(fd);
1549                 struct inode *src_inode;
1550                 if (!src.file) {
1551                         ret = -EINVAL;
1552                         goto out_drop_write;
1553                 }
1554
1555                 src_inode = file_inode(src.file);
1556                 if (src_inode->i_sb != file_inode(file)->i_sb) {
1557                         btrfs_info(BTRFS_I(src_inode)->root->fs_info,
1558                                    "Snapshot src from another FS");
1559                         ret = -EINVAL;
1560                 } else {
1561                         ret = btrfs_mksubvol(&file->f_path, name, namelen,
1562                                              BTRFS_I(src_inode)->root,
1563                                              transid, readonly, inherit);
1564                 }
1565                 fdput(src);
1566         }
1567 out_drop_write:
1568         mnt_drop_write_file(file);
1569 out:
1570         return ret;
1571 }
1572
1573 static noinline int btrfs_ioctl_snap_create(struct file *file,
1574                                             void __user *arg, int subvol)
1575 {
1576         struct btrfs_ioctl_vol_args *vol_args;
1577         int ret;
1578
1579         vol_args = memdup_user(arg, sizeof(*vol_args));
1580         if (IS_ERR(vol_args))
1581                 return PTR_ERR(vol_args);
1582         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1583
1584         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1585                                               vol_args->fd, subvol,
1586                                               NULL, false, NULL);
1587
1588         kfree(vol_args);
1589         return ret;
1590 }
1591
1592 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1593                                                void __user *arg, int subvol)
1594 {
1595         struct btrfs_ioctl_vol_args_v2 *vol_args;
1596         int ret;
1597         u64 transid = 0;
1598         u64 *ptr = NULL;
1599         bool readonly = false;
1600         struct btrfs_qgroup_inherit *inherit = NULL;
1601
1602         vol_args = memdup_user(arg, sizeof(*vol_args));
1603         if (IS_ERR(vol_args))
1604                 return PTR_ERR(vol_args);
1605         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1606
1607         if (vol_args->flags &
1608             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1609               BTRFS_SUBVOL_QGROUP_INHERIT)) {
1610                 ret = -EOPNOTSUPP;
1611                 goto out;
1612         }
1613
1614         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1615                 ptr = &transid;
1616         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1617                 readonly = true;
1618         if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1619                 if (vol_args->size > PAGE_CACHE_SIZE) {
1620                         ret = -EINVAL;
1621                         goto out;
1622                 }
1623                 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1624                 if (IS_ERR(inherit)) {
1625                         ret = PTR_ERR(inherit);
1626                         goto out;
1627                 }
1628         }
1629
1630         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1631                                               vol_args->fd, subvol, ptr,
1632                                               readonly, inherit);
1633
1634         if (ret == 0 && ptr &&
1635             copy_to_user(arg +
1636                          offsetof(struct btrfs_ioctl_vol_args_v2,
1637                                   transid), ptr, sizeof(*ptr)))
1638                 ret = -EFAULT;
1639 out:
1640         kfree(vol_args);
1641         kfree(inherit);
1642         return ret;
1643 }
1644
1645 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1646                                                 void __user *arg)
1647 {
1648         struct inode *inode = file_inode(file);
1649         struct btrfs_root *root = BTRFS_I(inode)->root;
1650         int ret = 0;
1651         u64 flags = 0;
1652
1653         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1654                 return -EINVAL;
1655
1656         down_read(&root->fs_info->subvol_sem);
1657         if (btrfs_root_readonly(root))
1658                 flags |= BTRFS_SUBVOL_RDONLY;
1659         up_read(&root->fs_info->subvol_sem);
1660
1661         if (copy_to_user(arg, &flags, sizeof(flags)))
1662                 ret = -EFAULT;
1663
1664         return ret;
1665 }
1666
1667 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1668                                               void __user *arg)
1669 {
1670         struct inode *inode = file_inode(file);
1671         struct btrfs_root *root = BTRFS_I(inode)->root;
1672         struct btrfs_trans_handle *trans;
1673         u64 root_flags;
1674         u64 flags;
1675         int ret = 0;
1676
1677         ret = mnt_want_write_file(file);
1678         if (ret)
1679                 goto out;
1680
1681         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1682                 ret = -EINVAL;
1683                 goto out_drop_write;
1684         }
1685
1686         if (copy_from_user(&flags, arg, sizeof(flags))) {
1687                 ret = -EFAULT;
1688                 goto out_drop_write;
1689         }
1690
1691         if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1692                 ret = -EINVAL;
1693                 goto out_drop_write;
1694         }
1695
1696         if (flags & ~BTRFS_SUBVOL_RDONLY) {
1697                 ret = -EOPNOTSUPP;
1698                 goto out_drop_write;
1699         }
1700
1701         if (!inode_owner_or_capable(inode)) {
1702                 ret = -EACCES;
1703                 goto out_drop_write;
1704         }
1705
1706         down_write(&root->fs_info->subvol_sem);
1707
1708         /* nothing to do */
1709         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1710                 goto out_drop_sem;
1711
1712         root_flags = btrfs_root_flags(&root->root_item);
1713         if (flags & BTRFS_SUBVOL_RDONLY) {
1714                 btrfs_set_root_flags(&root->root_item,
1715                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1716         } else {
1717                 /*
1718                  * Block RO -> RW transition if this subvolume is involved in
1719                  * send
1720                  */
1721                 spin_lock(&root->root_item_lock);
1722                 if (root->send_in_progress == 0) {
1723                         btrfs_set_root_flags(&root->root_item,
1724                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1725                         spin_unlock(&root->root_item_lock);
1726                 } else {
1727                         spin_unlock(&root->root_item_lock);
1728                         btrfs_warn(root->fs_info,
1729                         "Attempt to set subvolume %llu read-write during send",
1730                                         root->root_key.objectid);
1731                         ret = -EPERM;
1732                         goto out_drop_sem;
1733                 }
1734         }
1735
1736         trans = btrfs_start_transaction(root, 1);
1737         if (IS_ERR(trans)) {
1738                 ret = PTR_ERR(trans);
1739                 goto out_reset;
1740         }
1741
1742         ret = btrfs_update_root(trans, root->fs_info->tree_root,
1743                                 &root->root_key, &root->root_item);
1744
1745         btrfs_commit_transaction(trans, root);
1746 out_reset:
1747         if (ret)
1748                 btrfs_set_root_flags(&root->root_item, root_flags);
1749 out_drop_sem:
1750         up_write(&root->fs_info->subvol_sem);
1751 out_drop_write:
1752         mnt_drop_write_file(file);
1753 out:
1754         return ret;
1755 }
1756
1757 /*
1758  * helper to check if the subvolume references other subvolumes
1759  */
1760 static noinline int may_destroy_subvol(struct btrfs_root *root)
1761 {
1762         struct btrfs_path *path;
1763         struct btrfs_dir_item *di;
1764         struct btrfs_key key;
1765         u64 dir_id;
1766         int ret;
1767
1768         path = btrfs_alloc_path();
1769         if (!path)
1770                 return -ENOMEM;
1771
1772         /* Make sure this root isn't set as the default subvol */
1773         dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1774         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1775                                    dir_id, "default", 7, 0);
1776         if (di && !IS_ERR(di)) {
1777                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1778                 if (key.objectid == root->root_key.objectid) {
1779                         ret = -ENOTEMPTY;
1780                         goto out;
1781                 }
1782                 btrfs_release_path(path);
1783         }
1784
1785         key.objectid = root->root_key.objectid;
1786         key.type = BTRFS_ROOT_REF_KEY;
1787         key.offset = (u64)-1;
1788
1789         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1790                                 &key, path, 0, 0);
1791         if (ret < 0)
1792                 goto out;
1793         BUG_ON(ret == 0);
1794
1795         ret = 0;
1796         if (path->slots[0] > 0) {
1797                 path->slots[0]--;
1798                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1799                 if (key.objectid == root->root_key.objectid &&
1800                     key.type == BTRFS_ROOT_REF_KEY)
1801                         ret = -ENOTEMPTY;
1802         }
1803 out:
1804         btrfs_free_path(path);
1805         return ret;
1806 }
1807
1808 static noinline int key_in_sk(struct btrfs_key *key,
1809                               struct btrfs_ioctl_search_key *sk)
1810 {
1811         struct btrfs_key test;
1812         int ret;
1813
1814         test.objectid = sk->min_objectid;
1815         test.type = sk->min_type;
1816         test.offset = sk->min_offset;
1817
1818         ret = btrfs_comp_cpu_keys(key, &test);
1819         if (ret < 0)
1820                 return 0;
1821
1822         test.objectid = sk->max_objectid;
1823         test.type = sk->max_type;
1824         test.offset = sk->max_offset;
1825
1826         ret = btrfs_comp_cpu_keys(key, &test);
1827         if (ret > 0)
1828                 return 0;
1829         return 1;
1830 }
1831
1832 static noinline int copy_to_sk(struct btrfs_root *root,
1833                                struct btrfs_path *path,
1834                                struct btrfs_key *key,
1835                                struct btrfs_ioctl_search_key *sk,
1836                                char *buf,
1837                                unsigned long *sk_offset,
1838                                int *num_found)
1839 {
1840         u64 found_transid;
1841         struct extent_buffer *leaf;
1842         struct btrfs_ioctl_search_header sh;
1843         unsigned long item_off;
1844         unsigned long item_len;
1845         int nritems;
1846         int i;
1847         int slot;
1848         int ret = 0;
1849
1850         leaf = path->nodes[0];
1851         slot = path->slots[0];
1852         nritems = btrfs_header_nritems(leaf);
1853
1854         if (btrfs_header_generation(leaf) > sk->max_transid) {
1855                 i = nritems;
1856                 goto advance_key;
1857         }
1858         found_transid = btrfs_header_generation(leaf);
1859
1860         for (i = slot; i < nritems; i++) {
1861                 item_off = btrfs_item_ptr_offset(leaf, i);
1862                 item_len = btrfs_item_size_nr(leaf, i);
1863
1864                 btrfs_item_key_to_cpu(leaf, key, i);
1865                 if (!key_in_sk(key, sk))
1866                         continue;
1867
1868                 if (sizeof(sh) + item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
1869                         item_len = 0;
1870
1871                 if (sizeof(sh) + item_len + *sk_offset >
1872                     BTRFS_SEARCH_ARGS_BUFSIZE) {
1873                         ret = 1;
1874                         goto overflow;
1875                 }
1876
1877                 sh.objectid = key->objectid;
1878                 sh.offset = key->offset;
1879                 sh.type = key->type;
1880                 sh.len = item_len;
1881                 sh.transid = found_transid;
1882
1883                 /* copy search result header */
1884                 memcpy(buf + *sk_offset, &sh, sizeof(sh));
1885                 *sk_offset += sizeof(sh);
1886
1887                 if (item_len) {
1888                         char *p = buf + *sk_offset;
1889                         /* copy the item */
1890                         read_extent_buffer(leaf, p,
1891                                            item_off, item_len);
1892                         *sk_offset += item_len;
1893                 }
1894                 (*num_found)++;
1895
1896                 if (*num_found >= sk->nr_items)
1897                         break;
1898         }
1899 advance_key:
1900         ret = 0;
1901         if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1902                 key->offset++;
1903         else if (key->type < (u8)-1 && key->type < sk->max_type) {
1904                 key->offset = 0;
1905                 key->type++;
1906         } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1907                 key->offset = 0;
1908                 key->type = 0;
1909                 key->objectid++;
1910         } else
1911                 ret = 1;
1912 overflow:
1913         return ret;
1914 }
1915
1916 static noinline int search_ioctl(struct inode *inode,
1917                                  struct btrfs_ioctl_search_args *args)
1918 {
1919         struct btrfs_root *root;
1920         struct btrfs_key key;
1921         struct btrfs_path *path;
1922         struct btrfs_ioctl_search_key *sk = &args->key;
1923         struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1924         int ret;
1925         int num_found = 0;
1926         unsigned long sk_offset = 0;
1927
1928         path = btrfs_alloc_path();
1929         if (!path)
1930                 return -ENOMEM;
1931
1932         if (sk->tree_id == 0) {
1933                 /* search the root of the inode that was passed */
1934                 root = BTRFS_I(inode)->root;
1935         } else {
1936                 key.objectid = sk->tree_id;
1937                 key.type = BTRFS_ROOT_ITEM_KEY;
1938                 key.offset = (u64)-1;
1939                 root = btrfs_read_fs_root_no_name(info, &key);
1940                 if (IS_ERR(root)) {
1941                         printk(KERN_ERR "BTRFS: could not find root %llu\n",
1942                                sk->tree_id);
1943                         btrfs_free_path(path);
1944                         return -ENOENT;
1945                 }
1946         }
1947
1948         key.objectid = sk->min_objectid;
1949         key.type = sk->min_type;
1950         key.offset = sk->min_offset;
1951
1952         path->keep_locks = 1;
1953
1954         while (1) {
1955                 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
1956                 if (ret != 0) {
1957                         if (ret > 0)
1958                                 ret = 0;
1959                         goto err;
1960                 }
1961                 ret = copy_to_sk(root, path, &key, sk, args->buf,
1962                                  &sk_offset, &num_found);
1963                 btrfs_release_path(path);
1964                 if (ret || num_found >= sk->nr_items)
1965                         break;
1966
1967         }
1968         ret = 0;
1969 err:
1970         sk->nr_items = num_found;
1971         btrfs_free_path(path);
1972         return ret;
1973 }
1974
1975 static noinline int btrfs_ioctl_tree_search(struct file *file,
1976                                            void __user *argp)
1977 {
1978          struct btrfs_ioctl_search_args *args;
1979          struct inode *inode;
1980          int ret;
1981
1982         if (!capable(CAP_SYS_ADMIN))
1983                 return -EPERM;
1984
1985         args = memdup_user(argp, sizeof(*args));
1986         if (IS_ERR(args))
1987                 return PTR_ERR(args);
1988
1989         inode = file_inode(file);
1990         ret = search_ioctl(inode, args);
1991         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1992                 ret = -EFAULT;
1993         kfree(args);
1994         return ret;
1995 }
1996
1997 /*
1998  * Search INODE_REFs to identify path name of 'dirid' directory
1999  * in a 'tree_id' tree. and sets path name to 'name'.
2000  */
2001 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2002                                 u64 tree_id, u64 dirid, char *name)
2003 {
2004         struct btrfs_root *root;
2005         struct btrfs_key key;
2006         char *ptr;
2007         int ret = -1;
2008         int slot;
2009         int len;
2010         int total_len = 0;
2011         struct btrfs_inode_ref *iref;
2012         struct extent_buffer *l;
2013         struct btrfs_path *path;
2014
2015         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2016                 name[0]='\0';
2017                 return 0;
2018         }
2019
2020         path = btrfs_alloc_path();
2021         if (!path)
2022                 return -ENOMEM;
2023
2024         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
2025
2026         key.objectid = tree_id;
2027         key.type = BTRFS_ROOT_ITEM_KEY;
2028         key.offset = (u64)-1;
2029         root = btrfs_read_fs_root_no_name(info, &key);
2030         if (IS_ERR(root)) {
2031                 printk(KERN_ERR "BTRFS: could not find root %llu\n", tree_id);
2032                 ret = -ENOENT;
2033                 goto out;
2034         }
2035
2036         key.objectid = dirid;
2037         key.type = BTRFS_INODE_REF_KEY;
2038         key.offset = (u64)-1;
2039
2040         while (1) {
2041                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2042                 if (ret < 0)
2043                         goto out;
2044                 else if (ret > 0) {
2045                         ret = btrfs_previous_item(root, path, dirid,
2046                                                   BTRFS_INODE_REF_KEY);
2047                         if (ret < 0)
2048                                 goto out;
2049                         else if (ret > 0) {
2050                                 ret = -ENOENT;
2051                                 goto out;
2052                         }
2053                 }
2054
2055                 l = path->nodes[0];
2056                 slot = path->slots[0];
2057                 btrfs_item_key_to_cpu(l, &key, slot);
2058
2059                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2060                 len = btrfs_inode_ref_name_len(l, iref);
2061                 ptr -= len + 1;
2062                 total_len += len + 1;
2063                 if (ptr < name) {
2064                         ret = -ENAMETOOLONG;
2065                         goto out;
2066                 }
2067
2068                 *(ptr + len) = '/';
2069                 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2070
2071                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2072                         break;
2073
2074                 btrfs_release_path(path);
2075                 key.objectid = key.offset;
2076                 key.offset = (u64)-1;
2077                 dirid = key.objectid;
2078         }
2079         memmove(name, ptr, total_len);
2080         name[total_len] = '\0';
2081         ret = 0;
2082 out:
2083         btrfs_free_path(path);
2084         return ret;
2085 }
2086
2087 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2088                                            void __user *argp)
2089 {
2090          struct btrfs_ioctl_ino_lookup_args *args;
2091          struct inode *inode;
2092          int ret;
2093
2094         if (!capable(CAP_SYS_ADMIN))
2095                 return -EPERM;
2096
2097         args = memdup_user(argp, sizeof(*args));
2098         if (IS_ERR(args))
2099                 return PTR_ERR(args);
2100
2101         inode = file_inode(file);
2102
2103         if (args->treeid == 0)
2104                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2105
2106         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2107                                         args->treeid, args->objectid,
2108                                         args->name);
2109
2110         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2111                 ret = -EFAULT;
2112
2113         kfree(args);
2114         return ret;
2115 }
2116
2117 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2118                                              void __user *arg)
2119 {
2120         struct dentry *parent = file->f_path.dentry;
2121         struct dentry *dentry;
2122         struct inode *dir = parent->d_inode;
2123         struct inode *inode;
2124         struct btrfs_root *root = BTRFS_I(dir)->root;
2125         struct btrfs_root *dest = NULL;
2126         struct btrfs_ioctl_vol_args *vol_args;
2127         struct btrfs_trans_handle *trans;
2128         struct btrfs_block_rsv block_rsv;
2129         u64 qgroup_reserved;
2130         int namelen;
2131         int ret;
2132         int err = 0;
2133
2134         vol_args = memdup_user(arg, sizeof(*vol_args));
2135         if (IS_ERR(vol_args))
2136                 return PTR_ERR(vol_args);
2137
2138         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2139         namelen = strlen(vol_args->name);
2140         if (strchr(vol_args->name, '/') ||
2141             strncmp(vol_args->name, "..", namelen) == 0) {
2142                 err = -EINVAL;
2143                 goto out;
2144         }
2145
2146         err = mnt_want_write_file(file);
2147         if (err)
2148                 goto out;
2149
2150         err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2151         if (err == -EINTR)
2152                 goto out_drop_write;
2153         dentry = lookup_one_len(vol_args->name, parent, namelen);
2154         if (IS_ERR(dentry)) {
2155                 err = PTR_ERR(dentry);
2156                 goto out_unlock_dir;
2157         }
2158
2159         if (!dentry->d_inode) {
2160                 err = -ENOENT;
2161                 goto out_dput;
2162         }
2163
2164         inode = dentry->d_inode;
2165         dest = BTRFS_I(inode)->root;
2166         if (!capable(CAP_SYS_ADMIN)) {
2167                 /*
2168                  * Regular user.  Only allow this with a special mount
2169                  * option, when the user has write+exec access to the
2170                  * subvol root, and when rmdir(2) would have been
2171                  * allowed.
2172                  *
2173                  * Note that this is _not_ check that the subvol is
2174                  * empty or doesn't contain data that we wouldn't
2175                  * otherwise be able to delete.
2176                  *
2177                  * Users who want to delete empty subvols should try
2178                  * rmdir(2).
2179                  */
2180                 err = -EPERM;
2181                 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2182                         goto out_dput;
2183
2184                 /*
2185                  * Do not allow deletion if the parent dir is the same
2186                  * as the dir to be deleted.  That means the ioctl
2187                  * must be called on the dentry referencing the root
2188                  * of the subvol, not a random directory contained
2189                  * within it.
2190                  */
2191                 err = -EINVAL;
2192                 if (root == dest)
2193                         goto out_dput;
2194
2195                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2196                 if (err)
2197                         goto out_dput;
2198         }
2199
2200         /* check if subvolume may be deleted by a user */
2201         err = btrfs_may_delete(dir, dentry, 1);
2202         if (err)
2203                 goto out_dput;
2204
2205         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2206                 err = -EINVAL;
2207                 goto out_dput;
2208         }
2209
2210         mutex_lock(&inode->i_mutex);
2211         err = d_invalidate(dentry);
2212         if (err)
2213                 goto out_unlock;
2214
2215         down_write(&root->fs_info->subvol_sem);
2216
2217         err = may_destroy_subvol(dest);
2218         if (err)
2219                 goto out_up_write;
2220
2221         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2222         /*
2223          * One for dir inode, two for dir entries, two for root
2224          * ref/backref.
2225          */
2226         err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2227                                                5, &qgroup_reserved, true);
2228         if (err)
2229                 goto out_up_write;
2230
2231         trans = btrfs_start_transaction(root, 0);
2232         if (IS_ERR(trans)) {
2233                 err = PTR_ERR(trans);
2234                 goto out_release;
2235         }
2236         trans->block_rsv = &block_rsv;
2237         trans->bytes_reserved = block_rsv.size;
2238
2239         ret = btrfs_unlink_subvol(trans, root, dir,
2240                                 dest->root_key.objectid,
2241                                 dentry->d_name.name,
2242                                 dentry->d_name.len);
2243         if (ret) {
2244                 err = ret;
2245                 btrfs_abort_transaction(trans, root, ret);
2246                 goto out_end_trans;
2247         }
2248
2249         btrfs_record_root_in_trans(trans, dest);
2250
2251         memset(&dest->root_item.drop_progress, 0,
2252                 sizeof(dest->root_item.drop_progress));
2253         dest->root_item.drop_level = 0;
2254         btrfs_set_root_refs(&dest->root_item, 0);
2255
2256         if (!xchg(&dest->orphan_item_inserted, 1)) {
2257                 ret = btrfs_insert_orphan_item(trans,
2258                                         root->fs_info->tree_root,
2259                                         dest->root_key.objectid);
2260                 if (ret) {
2261                         btrfs_abort_transaction(trans, root, ret);
2262                         err = ret;
2263                         goto out_end_trans;
2264                 }
2265         }
2266
2267         ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2268                                   dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2269                                   dest->root_key.objectid);
2270         if (ret && ret != -ENOENT) {
2271                 btrfs_abort_transaction(trans, root, ret);
2272                 err = ret;
2273                 goto out_end_trans;
2274         }
2275         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2276                 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2277                                           dest->root_item.received_uuid,
2278                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2279                                           dest->root_key.objectid);
2280                 if (ret && ret != -ENOENT) {
2281                         btrfs_abort_transaction(trans, root, ret);
2282                         err = ret;
2283                         goto out_end_trans;
2284                 }
2285         }
2286
2287 out_end_trans:
2288         trans->block_rsv = NULL;
2289         trans->bytes_reserved = 0;
2290         ret = btrfs_end_transaction(trans, root);
2291         if (ret && !err)
2292                 err = ret;
2293         inode->i_flags |= S_DEAD;
2294 out_release:
2295         btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2296 out_up_write:
2297         up_write(&root->fs_info->subvol_sem);
2298 out_unlock:
2299         mutex_unlock(&inode->i_mutex);
2300         if (!err) {
2301                 shrink_dcache_sb(root->fs_info->sb);
2302                 btrfs_invalidate_inodes(dest);
2303                 d_delete(dentry);
2304
2305                 /* the last ref */
2306                 if (dest->cache_inode) {
2307                         iput(dest->cache_inode);
2308                         dest->cache_inode = NULL;
2309                 }
2310         }
2311 out_dput:
2312         dput(dentry);
2313 out_unlock_dir:
2314         mutex_unlock(&dir->i_mutex);
2315 out_drop_write:
2316         mnt_drop_write_file(file);
2317 out:
2318         kfree(vol_args);
2319         return err;
2320 }
2321
2322 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2323 {
2324         struct inode *inode = file_inode(file);
2325         struct btrfs_root *root = BTRFS_I(inode)->root;
2326         struct btrfs_ioctl_defrag_range_args *range;
2327         int ret;
2328
2329         ret = mnt_want_write_file(file);
2330         if (ret)
2331                 return ret;
2332
2333         if (btrfs_root_readonly(root)) {
2334                 ret = -EROFS;
2335                 goto out;
2336         }
2337
2338         switch (inode->i_mode & S_IFMT) {
2339         case S_IFDIR:
2340                 if (!capable(CAP_SYS_ADMIN)) {
2341                         ret = -EPERM;
2342                         goto out;
2343                 }
2344                 ret = btrfs_defrag_root(root);
2345                 if (ret)
2346                         goto out;
2347                 ret = btrfs_defrag_root(root->fs_info->extent_root);
2348                 break;
2349         case S_IFREG:
2350                 if (!(file->f_mode & FMODE_WRITE)) {
2351                         ret = -EINVAL;
2352                         goto out;
2353                 }
2354
2355                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2356                 if (!range) {
2357                         ret = -ENOMEM;
2358                         goto out;
2359                 }
2360
2361                 if (argp) {
2362                         if (copy_from_user(range, argp,
2363                                            sizeof(*range))) {
2364                                 ret = -EFAULT;
2365                                 kfree(range);
2366                                 goto out;
2367                         }
2368                         /* compression requires us to start the IO */
2369                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2370                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2371                                 range->extent_thresh = (u32)-1;
2372                         }
2373                 } else {
2374                         /* the rest are all set to zero by kzalloc */
2375                         range->len = (u64)-1;
2376                 }
2377                 ret = btrfs_defrag_file(file_inode(file), file,
2378                                         range, 0, 0);
2379                 if (ret > 0)
2380                         ret = 0;
2381                 kfree(range);
2382                 break;
2383         default:
2384                 ret = -EINVAL;
2385         }
2386 out:
2387         mnt_drop_write_file(file);
2388         return ret;
2389 }
2390
2391 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2392 {
2393         struct btrfs_ioctl_vol_args *vol_args;
2394         int ret;
2395
2396         if (!capable(CAP_SYS_ADMIN))
2397                 return -EPERM;
2398
2399         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2400                         1)) {
2401                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2402         }
2403
2404         mutex_lock(&root->fs_info->volume_mutex);
2405         vol_args = memdup_user(arg, sizeof(*vol_args));
2406         if (IS_ERR(vol_args)) {
2407                 ret = PTR_ERR(vol_args);
2408                 goto out;
2409         }
2410
2411         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2412         ret = btrfs_init_new_device(root, vol_args->name);
2413
2414         kfree(vol_args);
2415 out:
2416         mutex_unlock(&root->fs_info->volume_mutex);
2417         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2418         return ret;
2419 }
2420
2421 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2422 {
2423         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2424         struct btrfs_ioctl_vol_args *vol_args;
2425         int ret;
2426
2427         if (!capable(CAP_SYS_ADMIN))
2428                 return -EPERM;
2429
2430         ret = mnt_want_write_file(file);
2431         if (ret)
2432                 return ret;
2433
2434         vol_args = memdup_user(arg, sizeof(*vol_args));
2435         if (IS_ERR(vol_args)) {
2436                 ret = PTR_ERR(vol_args);
2437                 goto out;
2438         }
2439
2440         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2441
2442         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2443                         1)) {
2444                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2445                 goto out;
2446         }
2447
2448         mutex_lock(&root->fs_info->volume_mutex);
2449         ret = btrfs_rm_device(root, vol_args->name);
2450         mutex_unlock(&root->fs_info->volume_mutex);
2451         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2452
2453 out:
2454         kfree(vol_args);
2455         mnt_drop_write_file(file);
2456         return ret;
2457 }
2458
2459 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2460 {
2461         struct btrfs_ioctl_fs_info_args *fi_args;
2462         struct btrfs_device *device;
2463         struct btrfs_device *next;
2464         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2465         int ret = 0;
2466
2467         if (!capable(CAP_SYS_ADMIN))
2468                 return -EPERM;
2469
2470         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2471         if (!fi_args)
2472                 return -ENOMEM;
2473
2474         mutex_lock(&fs_devices->device_list_mutex);
2475         fi_args->num_devices = fs_devices->num_devices;
2476         memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2477
2478         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2479                 if (device->devid > fi_args->max_id)
2480                         fi_args->max_id = device->devid;
2481         }
2482         mutex_unlock(&fs_devices->device_list_mutex);
2483
2484         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2485                 ret = -EFAULT;
2486
2487         kfree(fi_args);
2488         return ret;
2489 }
2490
2491 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2492 {
2493         struct btrfs_ioctl_dev_info_args *di_args;
2494         struct btrfs_device *dev;
2495         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2496         int ret = 0;
2497         char *s_uuid = NULL;
2498
2499         if (!capable(CAP_SYS_ADMIN))
2500                 return -EPERM;
2501
2502         di_args = memdup_user(arg, sizeof(*di_args));
2503         if (IS_ERR(di_args))
2504                 return PTR_ERR(di_args);
2505
2506         if (!btrfs_is_empty_uuid(di_args->uuid))
2507                 s_uuid = di_args->uuid;
2508
2509         mutex_lock(&fs_devices->device_list_mutex);
2510         dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2511
2512         if (!dev) {
2513                 ret = -ENODEV;
2514                 goto out;
2515         }
2516
2517         di_args->devid = dev->devid;
2518         di_args->bytes_used = dev->bytes_used;
2519         di_args->total_bytes = dev->total_bytes;
2520         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2521         if (dev->name) {
2522                 struct rcu_string *name;
2523
2524                 rcu_read_lock();
2525                 name = rcu_dereference(dev->name);
2526                 strncpy(di_args->path, name->str, sizeof(di_args->path));
2527                 rcu_read_unlock();
2528                 di_args->path[sizeof(di_args->path) - 1] = 0;
2529         } else {
2530                 di_args->path[0] = '\0';
2531         }
2532
2533 out:
2534         mutex_unlock(&fs_devices->device_list_mutex);
2535         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2536                 ret = -EFAULT;
2537
2538         kfree(di_args);
2539         return ret;
2540 }
2541
2542 static struct page *extent_same_get_page(struct inode *inode, u64 off)
2543 {
2544         struct page *page;
2545         pgoff_t index;
2546         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2547
2548         index = off >> PAGE_CACHE_SHIFT;
2549
2550         page = grab_cache_page(inode->i_mapping, index);
2551         if (!page)
2552                 return NULL;
2553
2554         if (!PageUptodate(page)) {
2555                 if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2556                                                  0))
2557                         return NULL;
2558                 lock_page(page);
2559                 if (!PageUptodate(page)) {
2560                         unlock_page(page);
2561                         page_cache_release(page);
2562                         return NULL;
2563                 }
2564         }
2565         unlock_page(page);
2566
2567         return page;
2568 }
2569
2570 static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
2571 {
2572         /* do any pending delalloc/csum calc on src, one way or
2573            another, and lock file content */
2574         while (1) {
2575                 struct btrfs_ordered_extent *ordered;
2576                 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2577                 ordered = btrfs_lookup_first_ordered_extent(inode,
2578                                                             off + len - 1);
2579                 if (!ordered &&
2580                     !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2581                                     off + len - 1, EXTENT_DELALLOC, 0, NULL))
2582                         break;
2583                 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2584                 if (ordered)
2585                         btrfs_put_ordered_extent(ordered);
2586                 btrfs_wait_ordered_range(inode, off, len);
2587         }
2588 }
2589
2590 static void btrfs_double_unlock(struct inode *inode1, u64 loff1,
2591                                 struct inode *inode2, u64 loff2, u64 len)
2592 {
2593         unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2594         unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2595
2596         mutex_unlock(&inode1->i_mutex);
2597         mutex_unlock(&inode2->i_mutex);
2598 }
2599
2600 static void btrfs_double_lock(struct inode *inode1, u64 loff1,
2601                               struct inode *inode2, u64 loff2, u64 len)
2602 {
2603         if (inode1 < inode2) {
2604                 swap(inode1, inode2);
2605                 swap(loff1, loff2);
2606         }
2607
2608         mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2609         lock_extent_range(inode1, loff1, len);
2610         if (inode1 != inode2) {
2611                 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2612                 lock_extent_range(inode2, loff2, len);
2613         }
2614 }
2615
2616 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2617                           u64 dst_loff, u64 len)
2618 {
2619         int ret = 0;
2620         struct page *src_page, *dst_page;
2621         unsigned int cmp_len = PAGE_CACHE_SIZE;
2622         void *addr, *dst_addr;
2623
2624         while (len) {
2625                 if (len < PAGE_CACHE_SIZE)
2626                         cmp_len = len;
2627
2628                 src_page = extent_same_get_page(src, loff);
2629                 if (!src_page)
2630                         return -EINVAL;
2631                 dst_page = extent_same_get_page(dst, dst_loff);
2632                 if (!dst_page) {
2633                         page_cache_release(src_page);
2634                         return -EINVAL;
2635                 }
2636                 addr = kmap_atomic(src_page);
2637                 dst_addr = kmap_atomic(dst_page);
2638
2639                 flush_dcache_page(src_page);
2640                 flush_dcache_page(dst_page);
2641
2642                 if (memcmp(addr, dst_addr, cmp_len))
2643                         ret = BTRFS_SAME_DATA_DIFFERS;
2644
2645                 kunmap_atomic(addr);
2646                 kunmap_atomic(dst_addr);
2647                 page_cache_release(src_page);
2648                 page_cache_release(dst_page);
2649
2650                 if (ret)
2651                         break;
2652
2653                 loff += cmp_len;
2654                 dst_loff += cmp_len;
2655                 len -= cmp_len;
2656         }
2657
2658         return ret;
2659 }
2660
2661 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 len)
2662 {
2663         u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2664
2665         if (off + len > inode->i_size || off + len < off)
2666                 return -EINVAL;
2667         /* Check that we are block aligned - btrfs_clone() requires this */
2668         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2669                 return -EINVAL;
2670
2671         return 0;
2672 }
2673
2674 static int btrfs_extent_same(struct inode *src, u64 loff, u64 len,
2675                              struct inode *dst, u64 dst_loff)
2676 {
2677         int ret;
2678
2679         /*
2680          * btrfs_clone() can't handle extents in the same file
2681          * yet. Once that works, we can drop this check and replace it
2682          * with a check for the same inode, but overlapping extents.
2683          */
2684         if (src == dst)
2685                 return -EINVAL;
2686
2687         btrfs_double_lock(src, loff, dst, dst_loff, len);
2688
2689         ret = extent_same_check_offsets(src, loff, len);
2690         if (ret)
2691                 goto out_unlock;
2692
2693         ret = extent_same_check_offsets(dst, dst_loff, len);
2694         if (ret)
2695                 goto out_unlock;
2696
2697         /* don't make the dst file partly checksummed */
2698         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2699             (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
2700                 ret = -EINVAL;
2701                 goto out_unlock;
2702         }
2703
2704         ret = btrfs_cmp_data(src, loff, dst, dst_loff, len);
2705         if (ret == 0)
2706                 ret = btrfs_clone(src, dst, loff, len, len, dst_loff);
2707
2708 out_unlock:
2709         btrfs_double_unlock(src, loff, dst, dst_loff, len);
2710
2711         return ret;
2712 }
2713
2714 #define BTRFS_MAX_DEDUPE_LEN    (16 * 1024 * 1024)
2715
2716 static long btrfs_ioctl_file_extent_same(struct file *file,
2717                                          void __user *argp)
2718 {
2719         struct btrfs_ioctl_same_args tmp;
2720         struct btrfs_ioctl_same_args *same;
2721         struct btrfs_ioctl_same_extent_info *info;
2722         struct inode *src = file->f_dentry->d_inode;
2723         struct file *dst_file = NULL;
2724         struct inode *dst;
2725         u64 off;
2726         u64 len;
2727         int i;
2728         int ret;
2729         unsigned long size;
2730         u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
2731         bool is_admin = capable(CAP_SYS_ADMIN);
2732
2733         if (!(file->f_mode & FMODE_READ))
2734                 return -EINVAL;
2735
2736         ret = mnt_want_write_file(file);
2737         if (ret)
2738                 return ret;
2739
2740         if (copy_from_user(&tmp,
2741                            (struct btrfs_ioctl_same_args __user *)argp,
2742                            sizeof(tmp))) {
2743                 ret = -EFAULT;
2744                 goto out;
2745         }
2746
2747         size = sizeof(tmp) +
2748                 tmp.dest_count * sizeof(struct btrfs_ioctl_same_extent_info);
2749
2750         same = memdup_user((struct btrfs_ioctl_same_args __user *)argp, size);
2751
2752         if (IS_ERR(same)) {
2753                 ret = PTR_ERR(same);
2754                 goto out;
2755         }
2756
2757         off = same->logical_offset;
2758         len = same->length;
2759
2760         /*
2761          * Limit the total length we will dedupe for each operation.
2762          * This is intended to bound the total time spent in this
2763          * ioctl to something sane.
2764          */
2765         if (len > BTRFS_MAX_DEDUPE_LEN)
2766                 len = BTRFS_MAX_DEDUPE_LEN;
2767
2768         if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
2769                 /*
2770                  * Btrfs does not support blocksize < page_size. As a
2771                  * result, btrfs_cmp_data() won't correctly handle
2772                  * this situation without an update.
2773                  */
2774                 ret = -EINVAL;
2775                 goto out;
2776         }
2777
2778         ret = -EISDIR;
2779         if (S_ISDIR(src->i_mode))
2780                 goto out;
2781
2782         ret = -EACCES;
2783         if (!S_ISREG(src->i_mode))
2784                 goto out;
2785
2786         /* pre-format output fields to sane values */
2787         for (i = 0; i < same->dest_count; i++) {
2788                 same->info[i].bytes_deduped = 0ULL;
2789                 same->info[i].status = 0;
2790         }
2791
2792         ret = 0;
2793         for (i = 0; i < same->dest_count; i++) {
2794                 info = &same->info[i];
2795
2796                 dst_file = fget(info->fd);
2797                 if (!dst_file) {
2798                         info->status = -EBADF;
2799                         goto next;
2800                 }
2801
2802                 if (!(is_admin || (dst_file->f_mode & FMODE_WRITE))) {
2803                         info->status = -EINVAL;
2804                         goto next;
2805                 }
2806
2807                 info->status = -EXDEV;
2808                 if (file->f_path.mnt != dst_file->f_path.mnt)
2809                         goto next;
2810
2811                 dst = dst_file->f_dentry->d_inode;
2812                 if (src->i_sb != dst->i_sb)
2813                         goto next;
2814
2815                 if (S_ISDIR(dst->i_mode)) {
2816                         info->status = -EISDIR;
2817                         goto next;
2818                 }
2819
2820                 if (!S_ISREG(dst->i_mode)) {
2821                         info->status = -EACCES;
2822                         goto next;
2823                 }
2824
2825                 info->status = btrfs_extent_same(src, off, len, dst,
2826                                                 info->logical_offset);
2827                 if (info->status == 0)
2828                         info->bytes_deduped += len;
2829
2830 next:
2831                 if (dst_file)
2832                         fput(dst_file);
2833         }
2834
2835         ret = copy_to_user(argp, same, size);
2836         if (ret)
2837                 ret = -EFAULT;
2838
2839 out:
2840         mnt_drop_write_file(file);
2841         return ret;
2842 }
2843
2844 /**
2845  * btrfs_clone() - clone a range from inode file to another
2846  *
2847  * @src: Inode to clone from
2848  * @inode: Inode to clone to
2849  * @off: Offset within source to start clone from
2850  * @olen: Original length, passed by user, of range to clone
2851  * @olen_aligned: Block-aligned value of olen, extent_same uses
2852  *               identical values here
2853  * @destoff: Offset within @inode to start clone
2854  */
2855 static int btrfs_clone(struct inode *src, struct inode *inode,
2856                        u64 off, u64 olen, u64 olen_aligned, u64 destoff)
2857 {
2858         struct btrfs_root *root = BTRFS_I(inode)->root;
2859         struct btrfs_path *path = NULL;
2860         struct extent_buffer *leaf;
2861         struct btrfs_trans_handle *trans;
2862         char *buf = NULL;
2863         struct btrfs_key key;
2864         u32 nritems;
2865         int slot;
2866         int ret;
2867         u64 len = olen_aligned;
2868
2869         ret = -ENOMEM;
2870         buf = vmalloc(btrfs_level_size(root, 0));
2871         if (!buf)
2872                 return ret;
2873
2874         path = btrfs_alloc_path();
2875         if (!path) {
2876                 vfree(buf);
2877                 return ret;
2878         }
2879
2880         path->reada = 2;
2881         /* clone data */
2882         key.objectid = btrfs_ino(src);
2883         key.type = BTRFS_EXTENT_DATA_KEY;
2884         key.offset = 0;
2885
2886         while (1) {
2887                 /*
2888                  * note the key will change type as we walk through the
2889                  * tree.
2890                  */
2891                 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
2892                                 0, 0);
2893                 if (ret < 0)
2894                         goto out;
2895
2896                 nritems = btrfs_header_nritems(path->nodes[0]);
2897                 if (path->slots[0] >= nritems) {
2898                         ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
2899                         if (ret < 0)
2900                                 goto out;
2901                         if (ret > 0)
2902                                 break;
2903                         nritems = btrfs_header_nritems(path->nodes[0]);
2904                 }
2905                 leaf = path->nodes[0];
2906                 slot = path->slots[0];
2907
2908                 btrfs_item_key_to_cpu(leaf, &key, slot);
2909                 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
2910                     key.objectid != btrfs_ino(src))
2911                         break;
2912
2913                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
2914                         struct btrfs_file_extent_item *extent;
2915                         int type;
2916                         u32 size;
2917                         struct btrfs_key new_key;
2918                         u64 disko = 0, diskl = 0;
2919                         u64 datao = 0, datal = 0;
2920                         u8 comp;
2921                         u64 endoff;
2922
2923                         size = btrfs_item_size_nr(leaf, slot);
2924                         read_extent_buffer(leaf, buf,
2925                                            btrfs_item_ptr_offset(leaf, slot),
2926                                            size);
2927
2928                         extent = btrfs_item_ptr(leaf, slot,
2929                                                 struct btrfs_file_extent_item);
2930                         comp = btrfs_file_extent_compression(leaf, extent);
2931                         type = btrfs_file_extent_type(leaf, extent);
2932                         if (type == BTRFS_FILE_EXTENT_REG ||
2933                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2934                                 disko = btrfs_file_extent_disk_bytenr(leaf,
2935                                                                       extent);
2936                                 diskl = btrfs_file_extent_disk_num_bytes(leaf,
2937                                                                  extent);
2938                                 datao = btrfs_file_extent_offset(leaf, extent);
2939                                 datal = btrfs_file_extent_num_bytes(leaf,
2940                                                                     extent);
2941                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2942                                 /* take upper bound, may be compressed */
2943                                 datal = btrfs_file_extent_ram_bytes(leaf,
2944                                                                     extent);
2945                         }
2946                         btrfs_release_path(path);
2947
2948                         if (key.offset + datal <= off ||
2949                             key.offset >= off + len - 1)
2950                                 goto next;
2951
2952                         memcpy(&new_key, &key, sizeof(new_key));
2953                         new_key.objectid = btrfs_ino(inode);
2954                         if (off <= key.offset)
2955                                 new_key.offset = key.offset + destoff - off;
2956                         else
2957                                 new_key.offset = destoff;
2958
2959                         /*
2960                          * 1 - adjusting old extent (we may have to split it)
2961                          * 1 - add new extent
2962                          * 1 - inode update
2963                          */
2964                         trans = btrfs_start_transaction(root, 3);
2965                         if (IS_ERR(trans)) {
2966                                 ret = PTR_ERR(trans);
2967                                 goto out;
2968                         }
2969
2970                         if (type == BTRFS_FILE_EXTENT_REG ||
2971                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2972                                 /*
2973                                  *    a  | --- range to clone ---|  b
2974                                  * | ------------- extent ------------- |
2975                                  */
2976
2977                                 /* substract range b */
2978                                 if (key.offset + datal > off + len)
2979                                         datal = off + len - key.offset;
2980
2981                                 /* substract range a */
2982                                 if (off > key.offset) {
2983                                         datao += off - key.offset;
2984                                         datal -= off - key.offset;
2985                                 }
2986
2987                                 ret = btrfs_drop_extents(trans, root, inode,
2988                                                          new_key.offset,
2989                                                          new_key.offset + datal,
2990                                                          1);
2991                                 if (ret) {
2992                                         btrfs_abort_transaction(trans, root,
2993                                                                 ret);
2994                                         btrfs_end_transaction(trans, root);
2995                                         goto out;
2996                                 }
2997
2998                                 ret = btrfs_insert_empty_item(trans, root, path,
2999                                                               &new_key, size);
3000                                 if (ret) {
3001                                         btrfs_abort_transaction(trans, root,
3002                                                                 ret);
3003                                         btrfs_end_transaction(trans, root);
3004                                         goto out;
3005                                 }
3006
3007                                 leaf = path->nodes[0];
3008                                 slot = path->slots[0];
3009                                 write_extent_buffer(leaf, buf,
3010                                             btrfs_item_ptr_offset(leaf, slot),
3011                                             size);
3012
3013                                 extent = btrfs_item_ptr(leaf, slot,
3014                                                 struct btrfs_file_extent_item);
3015
3016                                 /* disko == 0 means it's a hole */
3017                                 if (!disko)
3018                                         datao = 0;
3019
3020                                 btrfs_set_file_extent_offset(leaf, extent,
3021                                                              datao);
3022                                 btrfs_set_file_extent_num_bytes(leaf, extent,
3023                                                                 datal);
3024                                 if (disko) {
3025                                         inode_add_bytes(inode, datal);
3026                                         ret = btrfs_inc_extent_ref(trans, root,
3027                                                         disko, diskl, 0,
3028                                                         root->root_key.objectid,
3029                                                         btrfs_ino(inode),
3030                                                         new_key.offset - datao,
3031                                                         0);
3032                                         if (ret) {
3033                                                 btrfs_abort_transaction(trans,
3034                                                                         root,
3035                                                                         ret);
3036                                                 btrfs_end_transaction(trans,
3037                                                                       root);
3038                                                 goto out;
3039
3040                                         }
3041                                 }
3042                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3043                                 u64 skip = 0;
3044                                 u64 trim = 0;
3045                                 if (off > key.offset) {
3046                                         skip = off - key.offset;
3047                                         new_key.offset += skip;
3048                                 }
3049
3050                                 if (key.offset + datal > off + len)
3051                                         trim = key.offset + datal - (off + len);
3052
3053                                 if (comp && (skip || trim)) {
3054                                         ret = -EINVAL;
3055                                         btrfs_end_transaction(trans, root);
3056                                         goto out;
3057                                 }
3058                                 size -= skip + trim;
3059                                 datal -= skip + trim;
3060
3061                                 ret = btrfs_drop_extents(trans, root, inode,
3062                                                          new_key.offset,
3063                                                          new_key.offset + datal,
3064                                                          1);
3065                                 if (ret) {
3066                                         btrfs_abort_transaction(trans, root,
3067                                                                 ret);
3068                                         btrfs_end_transaction(trans, root);
3069                                         goto out;
3070                                 }
3071
3072                                 ret = btrfs_insert_empty_item(trans, root, path,
3073                                                               &new_key, size);
3074                                 if (ret) {
3075                                         btrfs_abort_transaction(trans, root,
3076                                                                 ret);
3077                                         btrfs_end_transaction(trans, root);
3078                                         goto out;
3079                                 }
3080
3081                                 if (skip) {
3082                                         u32 start =
3083                                           btrfs_file_extent_calc_inline_size(0);
3084                                         memmove(buf+start, buf+start+skip,
3085                                                 datal);
3086                                 }
3087
3088                                 leaf = path->nodes[0];
3089                                 slot = path->slots[0];
3090                                 write_extent_buffer(leaf, buf,
3091                                             btrfs_item_ptr_offset(leaf, slot),
3092                                             size);
3093                                 inode_add_bytes(inode, datal);
3094                         }
3095
3096                         btrfs_mark_buffer_dirty(leaf);
3097                         btrfs_release_path(path);
3098
3099                         inode_inc_iversion(inode);
3100                         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3101
3102                         /*
3103                          * we round up to the block size at eof when
3104                          * determining which extents to clone above,
3105                          * but shouldn't round up the file size
3106                          */
3107                         endoff = new_key.offset + datal;
3108                         if (endoff > destoff+olen)
3109                                 endoff = destoff+olen;
3110                         if (endoff > inode->i_size)
3111                                 btrfs_i_size_write(inode, endoff);
3112
3113                         ret = btrfs_update_inode(trans, root, inode);
3114                         if (ret) {
3115                                 btrfs_abort_transaction(trans, root, ret);
3116                                 btrfs_end_transaction(trans, root);
3117                                 goto out;
3118                         }
3119                         ret = btrfs_end_transaction(trans, root);
3120                 }
3121 next:
3122                 btrfs_release_path(path);
3123                 key.offset++;
3124         }
3125         ret = 0;
3126
3127 out:
3128         btrfs_release_path(path);
3129         btrfs_free_path(path);
3130         vfree(buf);
3131         return ret;
3132 }
3133
3134 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
3135                                        u64 off, u64 olen, u64 destoff)
3136 {
3137         struct inode *inode = file_inode(file);
3138         struct btrfs_root *root = BTRFS_I(inode)->root;
3139         struct fd src_file;
3140         struct inode *src;
3141         int ret;
3142         u64 len = olen;
3143         u64 bs = root->fs_info->sb->s_blocksize;
3144         int same_inode = 0;
3145
3146         /*
3147          * TODO:
3148          * - split compressed inline extents.  annoying: we need to
3149          *   decompress into destination's address_space (the file offset
3150          *   may change, so source mapping won't do), then recompress (or
3151          *   otherwise reinsert) a subrange.
3152          * - allow ranges within the same file to be cloned (provided
3153          *   they don't overlap)?
3154          */
3155
3156         /* the destination must be opened for writing */
3157         if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
3158                 return -EINVAL;
3159
3160         if (btrfs_root_readonly(root))
3161                 return -EROFS;
3162
3163         ret = mnt_want_write_file(file);
3164         if (ret)
3165                 return ret;
3166
3167         src_file = fdget(srcfd);
3168         if (!src_file.file) {
3169                 ret = -EBADF;
3170                 goto out_drop_write;
3171         }
3172
3173         ret = -EXDEV;
3174         if (src_file.file->f_path.mnt != file->f_path.mnt)
3175                 goto out_fput;
3176
3177         src = file_inode(src_file.file);
3178
3179         ret = -EINVAL;
3180         if (src == inode)
3181                 same_inode = 1;
3182
3183         /* the src must be open for reading */
3184         if (!(src_file.file->f_mode & FMODE_READ))
3185                 goto out_fput;
3186
3187         /* don't make the dst file partly checksummed */
3188         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3189             (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
3190                 goto out_fput;
3191
3192         ret = -EISDIR;
3193         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3194                 goto out_fput;
3195
3196         ret = -EXDEV;
3197         if (src->i_sb != inode->i_sb)
3198                 goto out_fput;
3199
3200         if (!same_inode) {
3201                 if (inode < src) {
3202                         mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
3203                         mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
3204                 } else {
3205                         mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
3206                         mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
3207                 }
3208         } else {
3209                 mutex_lock(&src->i_mutex);
3210         }
3211
3212         /* determine range to clone */
3213         ret = -EINVAL;
3214         if (off + len > src->i_size || off + len < off)
3215                 goto out_unlock;
3216         if (len == 0)
3217                 olen = len = src->i_size - off;
3218         /* if we extend to eof, continue to block boundary */
3219         if (off + len == src->i_size)
3220                 len = ALIGN(src->i_size, bs) - off;
3221
3222         /* verify the end result is block aligned */
3223         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3224             !IS_ALIGNED(destoff, bs))
3225                 goto out_unlock;
3226
3227         /* verify if ranges are overlapped within the same file */
3228         if (same_inode) {
3229                 if (destoff + len > off && destoff < off + len)
3230                         goto out_unlock;
3231         }
3232
3233         if (destoff > inode->i_size) {
3234                 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3235                 if (ret)
3236                         goto out_unlock;
3237         }
3238
3239         /* truncate page cache pages from target inode range */
3240         truncate_inode_pages_range(&inode->i_data, destoff,
3241                                    PAGE_CACHE_ALIGN(destoff + len) - 1);
3242
3243         lock_extent_range(src, off, len);
3244
3245         ret = btrfs_clone(src, inode, off, olen, len, destoff);
3246
3247         unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
3248 out_unlock:
3249         mutex_unlock(&src->i_mutex);
3250         if (!same_inode)
3251                 mutex_unlock(&inode->i_mutex);
3252 out_fput:
3253         fdput(src_file);
3254 out_drop_write:
3255         mnt_drop_write_file(file);
3256         return ret;
3257 }
3258
3259 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
3260 {
3261         struct btrfs_ioctl_clone_range_args args;
3262
3263         if (copy_from_user(&args, argp, sizeof(args)))
3264                 return -EFAULT;
3265         return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
3266                                  args.src_length, args.dest_offset);
3267 }
3268
3269 /*
3270  * there are many ways the trans_start and trans_end ioctls can lead
3271  * to deadlocks.  They should only be used by applications that
3272  * basically own the machine, and have a very in depth understanding
3273  * of all the possible deadlocks and enospc problems.
3274  */
3275 static long btrfs_ioctl_trans_start(struct file *file)
3276 {
3277         struct inode *inode = file_inode(file);
3278         struct btrfs_root *root = BTRFS_I(inode)->root;
3279         struct btrfs_trans_handle *trans;
3280         int ret;
3281
3282         ret = -EPERM;
3283         if (!capable(CAP_SYS_ADMIN))
3284                 goto out;
3285
3286         ret = -EINPROGRESS;
3287         if (file->private_data)
3288                 goto out;
3289
3290         ret = -EROFS;
3291         if (btrfs_root_readonly(root))
3292                 goto out;
3293
3294         ret = mnt_want_write_file(file);
3295         if (ret)
3296                 goto out;
3297
3298         atomic_inc(&root->fs_info->open_ioctl_trans);
3299
3300         ret = -ENOMEM;
3301         trans = btrfs_start_ioctl_transaction(root);
3302         if (IS_ERR(trans))
3303                 goto out_drop;
3304
3305         file->private_data = trans;
3306         return 0;
3307
3308 out_drop:
3309         atomic_dec(&root->fs_info->open_ioctl_trans);
3310         mnt_drop_write_file(file);
3311 out:
3312         return ret;
3313 }
3314
3315 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3316 {
3317         struct inode *inode = file_inode(file);
3318         struct btrfs_root *root = BTRFS_I(inode)->root;
3319         struct btrfs_root *new_root;
3320         struct btrfs_dir_item *di;
3321         struct btrfs_trans_handle *trans;
3322         struct btrfs_path *path;
3323         struct btrfs_key location;
3324         struct btrfs_disk_key disk_key;
3325         u64 objectid = 0;
3326         u64 dir_id;
3327         int ret;
3328
3329         if (!capable(CAP_SYS_ADMIN))
3330                 return -EPERM;
3331
3332         ret = mnt_want_write_file(file);
3333         if (ret)
3334                 return ret;
3335
3336         if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3337                 ret = -EFAULT;
3338                 goto out;
3339         }
3340
3341         if (!objectid)
3342                 objectid = BTRFS_FS_TREE_OBJECTID;
3343
3344         location.objectid = objectid;
3345         location.type = BTRFS_ROOT_ITEM_KEY;
3346         location.offset = (u64)-1;
3347
3348         new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
3349         if (IS_ERR(new_root)) {
3350                 ret = PTR_ERR(new_root);
3351                 goto out;
3352         }
3353
3354         path = btrfs_alloc_path();
3355         if (!path) {
3356                 ret = -ENOMEM;
3357                 goto out;
3358         }
3359         path->leave_spinning = 1;
3360
3361         trans = btrfs_start_transaction(root, 1);
3362         if (IS_ERR(trans)) {
3363                 btrfs_free_path(path);
3364                 ret = PTR_ERR(trans);
3365                 goto out;
3366         }
3367
3368         dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
3369         di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
3370                                    dir_id, "default", 7, 1);
3371         if (IS_ERR_OR_NULL(di)) {
3372                 btrfs_free_path(path);
3373                 btrfs_end_transaction(trans, root);
3374                 btrfs_err(new_root->fs_info, "Umm, you don't have the default dir"
3375                            "item, this isn't going to work");
3376                 ret = -ENOENT;
3377                 goto out;
3378         }
3379
3380         btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3381         btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3382         btrfs_mark_buffer_dirty(path->nodes[0]);
3383         btrfs_free_path(path);
3384
3385         btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
3386         btrfs_end_transaction(trans, root);
3387 out:
3388         mnt_drop_write_file(file);
3389         return ret;
3390 }
3391
3392 void btrfs_get_block_group_info(struct list_head *groups_list,
3393                                 struct btrfs_ioctl_space_info *space)
3394 {
3395         struct btrfs_block_group_cache *block_group;
3396
3397         space->total_bytes = 0;
3398         space->used_bytes = 0;
3399         space->flags = 0;
3400         list_for_each_entry(block_group, groups_list, list) {
3401                 space->flags = block_group->flags;
3402                 space->total_bytes += block_group->key.offset;
3403                 space->used_bytes +=
3404                         btrfs_block_group_used(&block_group->item);
3405         }
3406 }
3407
3408 static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
3409 {
3410         struct btrfs_ioctl_space_args space_args;
3411         struct btrfs_ioctl_space_info space;
3412         struct btrfs_ioctl_space_info *dest;
3413         struct btrfs_ioctl_space_info *dest_orig;
3414         struct btrfs_ioctl_space_info __user *user_dest;
3415         struct btrfs_space_info *info;
3416         u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
3417                        BTRFS_BLOCK_GROUP_SYSTEM,
3418                        BTRFS_BLOCK_GROUP_METADATA,
3419                        BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
3420         int num_types = 4;
3421         int alloc_size;
3422         int ret = 0;
3423         u64 slot_count = 0;
3424         int i, c;
3425
3426         if (copy_from_user(&space_args,
3427                            (struct btrfs_ioctl_space_args __user *)arg,
3428                            sizeof(space_args)))
3429                 return -EFAULT;
3430
3431         for (i = 0; i < num_types; i++) {
3432                 struct btrfs_space_info *tmp;
3433
3434                 info = NULL;
3435                 rcu_read_lock();
3436                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3437                                         list) {
3438                         if (tmp->flags == types[i]) {
3439                                 info = tmp;
3440                                 break;
3441                         }
3442                 }
3443                 rcu_read_unlock();
3444
3445                 if (!info)
3446                         continue;
3447
3448                 down_read(&info->groups_sem);
3449                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3450                         if (!list_empty(&info->block_groups[c]))
3451                                 slot_count++;
3452                 }
3453                 up_read(&info->groups_sem);
3454         }
3455
3456         /* space_slots == 0 means they are asking for a count */
3457         if (space_args.space_slots == 0) {
3458                 space_args.total_spaces = slot_count;
3459                 goto out;
3460         }
3461
3462         slot_count = min_t(u64, space_args.space_slots, slot_count);
3463
3464         alloc_size = sizeof(*dest) * slot_count;
3465
3466         /* we generally have at most 6 or so space infos, one for each raid
3467          * level.  So, a whole page should be more than enough for everyone
3468          */
3469         if (alloc_size > PAGE_CACHE_SIZE)
3470                 return -ENOMEM;
3471
3472         space_args.total_spaces = 0;
3473         dest = kmalloc(alloc_size, GFP_NOFS);
3474         if (!dest)
3475                 return -ENOMEM;
3476         dest_orig = dest;
3477
3478         /* now we have a buffer to copy into */
3479         for (i = 0; i < num_types; i++) {
3480                 struct btrfs_space_info *tmp;
3481
3482                 if (!slot_count)
3483                         break;
3484
3485                 info = NULL;
3486                 rcu_read_lock();
3487                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3488                                         list) {
3489                         if (tmp->flags == types[i]) {
3490                                 info = tmp;
3491                                 break;
3492                         }
3493                 }
3494                 rcu_read_unlock();
3495
3496                 if (!info)
3497                         continue;
3498                 down_read(&info->groups_sem);
3499                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3500                         if (!list_empty(&info->block_groups[c])) {
3501                                 btrfs_get_block_group_info(
3502                                         &info->block_groups[c], &space);
3503                                 memcpy(dest, &space, sizeof(space));
3504                                 dest++;
3505                                 space_args.total_spaces++;
3506                                 slot_count--;
3507                         }
3508                         if (!slot_count)
3509                                 break;
3510                 }
3511                 up_read(&info->groups_sem);
3512         }
3513
3514         user_dest = (struct btrfs_ioctl_space_info __user *)
3515                 (arg + sizeof(struct btrfs_ioctl_space_args));
3516
3517         if (copy_to_user(user_dest, dest_orig, alloc_size))
3518                 ret = -EFAULT;
3519
3520         kfree(dest_orig);
3521 out:
3522         if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3523                 ret = -EFAULT;
3524
3525         return ret;
3526 }
3527
3528 static long btrfs_ioctl_global_rsv(struct btrfs_root *root, void __user *arg)
3529 {
3530         struct btrfs_block_rsv *block_rsv = &root->fs_info->global_block_rsv;
3531         u64 reserved;
3532
3533         spin_lock(&block_rsv->lock);
3534         reserved = block_rsv->reserved;
3535         spin_unlock(&block_rsv->lock);
3536
3537         if (arg && copy_to_user(arg, &reserved, sizeof(reserved)))
3538                 return -EFAULT;
3539         return 0;
3540 }
3541
3542 /*
3543  * there are many ways the trans_start and trans_end ioctls can lead
3544  * to deadlocks.  They should only be used by applications that
3545  * basically own the machine, and have a very in depth understanding
3546  * of all the possible deadlocks and enospc problems.
3547  */
3548 long btrfs_ioctl_trans_end(struct file *file)
3549 {
3550         struct inode *inode = file_inode(file);
3551         struct btrfs_root *root = BTRFS_I(inode)->root;
3552         struct btrfs_trans_handle *trans;
3553
3554         trans = file->private_data;
3555         if (!trans)
3556                 return -EINVAL;
3557         file->private_data = NULL;
3558
3559         btrfs_end_transaction(trans, root);
3560
3561         atomic_dec(&root->fs_info->open_ioctl_trans);
3562
3563         mnt_drop_write_file(file);
3564         return 0;
3565 }
3566
3567 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3568                                             void __user *argp)
3569 {
3570         struct btrfs_trans_handle *trans;
3571         u64 transid;
3572         int ret;
3573
3574         trans = btrfs_attach_transaction_barrier(root);
3575         if (IS_ERR(trans)) {
3576                 if (PTR_ERR(trans) != -ENOENT)
3577                         return PTR_ERR(trans);
3578
3579                 /* No running transaction, don't bother */
3580                 transid = root->fs_info->last_trans_committed;
3581                 goto out;
3582         }
3583         transid = trans->transid;
3584         ret = btrfs_commit_transaction_async(trans, root, 0);
3585         if (ret) {
3586                 btrfs_end_transaction(trans, root);
3587                 return ret;
3588         }
3589 out:
3590         if (argp)
3591                 if (copy_to_user(argp, &transid, sizeof(transid)))
3592                         return -EFAULT;
3593         return 0;
3594 }
3595
3596 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
3597                                            void __user *argp)
3598 {
3599         u64 transid;
3600
3601         if (argp) {
3602                 if (copy_from_user(&transid, argp, sizeof(transid)))
3603                         return -EFAULT;
3604         } else {
3605                 transid = 0;  /* current trans */
3606         }
3607         return btrfs_wait_for_commit(root, transid);
3608 }
3609
3610 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3611 {
3612         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3613         struct btrfs_ioctl_scrub_args *sa;
3614         int ret;
3615
3616         if (!capable(CAP_SYS_ADMIN))
3617                 return -EPERM;
3618
3619         sa = memdup_user(arg, sizeof(*sa));
3620         if (IS_ERR(sa))
3621                 return PTR_ERR(sa);
3622
3623         if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3624                 ret = mnt_want_write_file(file);
3625                 if (ret)
3626                         goto out;
3627         }
3628
3629         ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
3630                               &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3631                               0);
3632
3633         if (copy_to_user(arg, sa, sizeof(*sa)))
3634                 ret = -EFAULT;
3635
3636         if (!(sa->flags & BTRFS_SCRUB_READONLY))
3637                 mnt_drop_write_file(file);
3638 out:
3639         kfree(sa);
3640         return ret;
3641 }
3642
3643 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
3644 {
3645         if (!capable(CAP_SYS_ADMIN))
3646                 return -EPERM;
3647
3648         return btrfs_scrub_cancel(root->fs_info);
3649 }
3650
3651 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
3652                                        void __user *arg)
3653 {
3654         struct btrfs_ioctl_scrub_args *sa;
3655         int ret;
3656
3657         if (!capable(CAP_SYS_ADMIN))
3658                 return -EPERM;
3659
3660         sa = memdup_user(arg, sizeof(*sa));
3661         if (IS_ERR(sa))
3662                 return PTR_ERR(sa);
3663
3664         ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
3665
3666         if (copy_to_user(arg, sa, sizeof(*sa)))
3667                 ret = -EFAULT;
3668
3669         kfree(sa);
3670         return ret;
3671 }
3672
3673 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
3674                                       void __user *arg)
3675 {
3676         struct btrfs_ioctl_get_dev_stats *sa;
3677         int ret;
3678
3679         sa = memdup_user(arg, sizeof(*sa));
3680         if (IS_ERR(sa))
3681                 return PTR_ERR(sa);
3682
3683         if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3684                 kfree(sa);
3685                 return -EPERM;
3686         }
3687
3688         ret = btrfs_get_dev_stats(root, sa);
3689
3690         if (copy_to_user(arg, sa, sizeof(*sa)))
3691                 ret = -EFAULT;
3692
3693         kfree(sa);
3694         return ret;
3695 }
3696
3697 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
3698 {
3699         struct btrfs_ioctl_dev_replace_args *p;
3700         int ret;
3701
3702         if (!capable(CAP_SYS_ADMIN))
3703                 return -EPERM;
3704
3705         p = memdup_user(arg, sizeof(*p));
3706         if (IS_ERR(p))
3707                 return PTR_ERR(p);
3708
3709         switch (p->cmd) {
3710         case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3711                 if (root->fs_info->sb->s_flags & MS_RDONLY) {
3712                         ret = -EROFS;
3713                         goto out;
3714                 }
3715                 if (atomic_xchg(
3716                         &root->fs_info->mutually_exclusive_operation_running,
3717                         1)) {
3718                         ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3719                 } else {
3720                         ret = btrfs_dev_replace_start(root, p);
3721                         atomic_set(
3722                          &root->fs_info->mutually_exclusive_operation_running,
3723                          0);
3724                 }
3725                 break;
3726         case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3727                 btrfs_dev_replace_status(root->fs_info, p);
3728                 ret = 0;
3729                 break;
3730         case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3731                 ret = btrfs_dev_replace_cancel(root->fs_info, p);
3732                 break;
3733         default:
3734                 ret = -EINVAL;
3735                 break;
3736         }
3737
3738         if (copy_to_user(arg, p, sizeof(*p)))
3739                 ret = -EFAULT;
3740 out:
3741         kfree(p);
3742         return ret;
3743 }
3744
3745 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3746 {
3747         int ret = 0;
3748         int i;
3749         u64 rel_ptr;
3750         int size;
3751         struct btrfs_ioctl_ino_path_args *ipa = NULL;
3752         struct inode_fs_paths *ipath = NULL;
3753         struct btrfs_path *path;
3754
3755         if (!capable(CAP_DAC_READ_SEARCH))
3756                 return -EPERM;
3757
3758         path = btrfs_alloc_path();
3759         if (!path) {
3760                 ret = -ENOMEM;
3761                 goto out;
3762         }
3763
3764         ipa = memdup_user(arg, sizeof(*ipa));
3765         if (IS_ERR(ipa)) {
3766                 ret = PTR_ERR(ipa);
3767                 ipa = NULL;
3768                 goto out;
3769         }
3770
3771         size = min_t(u32, ipa->size, 4096);
3772         ipath = init_ipath(size, root, path);
3773         if (IS_ERR(ipath)) {
3774                 ret = PTR_ERR(ipath);
3775                 ipath = NULL;
3776                 goto out;
3777         }
3778
3779         ret = paths_from_inode(ipa->inum, ipath);
3780         if (ret < 0)
3781                 goto out;
3782
3783         for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3784                 rel_ptr = ipath->fspath->val[i] -
3785                           (u64)(unsigned long)ipath->fspath->val;
3786                 ipath->fspath->val[i] = rel_ptr;
3787         }
3788
3789         ret = copy_to_user((void *)(unsigned long)ipa->fspath,
3790                            (void *)(unsigned long)ipath->fspath, size);
3791         if (ret) {
3792                 ret = -EFAULT;
3793                 goto out;
3794         }
3795
3796 out:
3797         btrfs_free_path(path);
3798         free_ipath(ipath);
3799         kfree(ipa);
3800
3801         return ret;
3802 }
3803
3804 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3805 {
3806         struct btrfs_data_container *inodes = ctx;
3807         const size_t c = 3 * sizeof(u64);
3808
3809         if (inodes->bytes_left >= c) {
3810                 inodes->bytes_left -= c;
3811                 inodes->val[inodes->elem_cnt] = inum;
3812                 inodes->val[inodes->elem_cnt + 1] = offset;
3813                 inodes->val[inodes->elem_cnt + 2] = root;
3814                 inodes->elem_cnt += 3;
3815         } else {
3816                 inodes->bytes_missing += c - inodes->bytes_left;
3817                 inodes->bytes_left = 0;
3818                 inodes->elem_missed += 3;
3819         }
3820
3821         return 0;
3822 }
3823
3824 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
3825                                         void __user *arg)
3826 {
3827         int ret = 0;
3828         int size;
3829         struct btrfs_ioctl_logical_ino_args *loi;
3830         struct btrfs_data_container *inodes = NULL;
3831         struct btrfs_path *path = NULL;
3832
3833         if (!capable(CAP_SYS_ADMIN))
3834                 return -EPERM;
3835
3836         loi = memdup_user(arg, sizeof(*loi));
3837         if (IS_ERR(loi)) {
3838                 ret = PTR_ERR(loi);
3839                 loi = NULL;
3840                 goto out;
3841         }
3842
3843         path = btrfs_alloc_path();
3844         if (!path) {
3845                 ret = -ENOMEM;
3846                 goto out;
3847         }
3848
3849         size = min_t(u32, loi->size, 64 * 1024);
3850         inodes = init_data_container(size);
3851         if (IS_ERR(inodes)) {
3852                 ret = PTR_ERR(inodes);
3853                 inodes = NULL;
3854                 goto out;
3855         }
3856
3857         ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
3858                                           build_ino_list, inodes);
3859         if (ret == -EINVAL)
3860                 ret = -ENOENT;
3861         if (ret < 0)
3862                 goto out;
3863
3864         ret = copy_to_user((void *)(unsigned long)loi->inodes,
3865                            (void *)(unsigned long)inodes, size);
3866         if (ret)
3867                 ret = -EFAULT;
3868
3869 out:
3870         btrfs_free_path(path);
3871         vfree(inodes);
3872         kfree(loi);
3873
3874         return ret;
3875 }
3876
3877 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
3878                                struct btrfs_ioctl_balance_args *bargs)
3879 {
3880         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3881
3882         bargs->flags = bctl->flags;
3883
3884         if (atomic_read(&fs_info->balance_running))
3885                 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3886         if (atomic_read(&fs_info->balance_pause_req))
3887                 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3888         if (atomic_read(&fs_info->balance_cancel_req))
3889                 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3890
3891         memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3892         memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3893         memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3894
3895         if (lock) {
3896                 spin_lock(&fs_info->balance_lock);
3897                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3898                 spin_unlock(&fs_info->balance_lock);
3899         } else {
3900                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3901         }
3902 }
3903
3904 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3905 {
3906         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3907         struct btrfs_fs_info *fs_info = root->fs_info;
3908         struct btrfs_ioctl_balance_args *bargs;
3909         struct btrfs_balance_control *bctl;
3910         bool need_unlock; /* for mut. excl. ops lock */
3911         int ret;
3912
3913         if (!capable(CAP_SYS_ADMIN))
3914                 return -EPERM;
3915
3916         ret = mnt_want_write_file(file);
3917         if (ret)
3918                 return ret;
3919
3920 again:
3921         if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
3922                 mutex_lock(&fs_info->volume_mutex);
3923                 mutex_lock(&fs_info->balance_mutex);
3924                 need_unlock = true;
3925                 goto locked;
3926         }
3927
3928         /*
3929          * mut. excl. ops lock is locked.  Three possibilites:
3930          *   (1) some other op is running
3931          *   (2) balance is running
3932          *   (3) balance is paused -- special case (think resume)
3933          */
3934         mutex_lock(&fs_info->balance_mutex);
3935         if (fs_info->balance_ctl) {
3936                 /* this is either (2) or (3) */
3937                 if (!atomic_read(&fs_info->balance_running)) {
3938                         mutex_unlock(&fs_info->balance_mutex);
3939                         if (!mutex_trylock(&fs_info->volume_mutex))
3940                                 goto again;
3941                         mutex_lock(&fs_info->balance_mutex);
3942
3943                         if (fs_info->balance_ctl &&
3944                             !atomic_read(&fs_info->balance_running)) {
3945                                 /* this is (3) */
3946                                 need_unlock = false;
3947                                 goto locked;
3948                         }
3949
3950                         mutex_unlock(&fs_info->balance_mutex);
3951                         mutex_unlock(&fs_info->volume_mutex);
3952                         goto again;
3953                 } else {
3954                         /* this is (2) */
3955                         mutex_unlock(&fs_info->balance_mutex);
3956                         ret = -EINPROGRESS;
3957                         goto out;
3958                 }
3959         } else {
3960                 /* this is (1) */
3961                 mutex_unlock(&fs_info->balance_mutex);
3962                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3963                 goto out;
3964         }
3965
3966 locked:
3967         BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
3968
3969         if (arg) {
3970                 bargs = memdup_user(arg, sizeof(*bargs));
3971                 if (IS_ERR(bargs)) {
3972                         ret = PTR_ERR(bargs);
3973                         goto out_unlock;
3974                 }
3975
3976                 if (bargs->flags & BTRFS_BALANCE_RESUME) {
3977                         if (!fs_info->balance_ctl) {
3978                                 ret = -ENOTCONN;
3979                                 goto out_bargs;
3980                         }
3981
3982                         bctl = fs_info->balance_ctl;
3983                         spin_lock(&fs_info->balance_lock);
3984                         bctl->flags |= BTRFS_BALANCE_RESUME;
3985                         spin_unlock(&fs_info->balance_lock);
3986
3987                         goto do_balance;
3988                 }
3989         } else {
3990                 bargs = NULL;
3991         }
3992
3993         if (fs_info->balance_ctl) {
3994                 ret = -EINPROGRESS;
3995                 goto out_bargs;
3996         }
3997
3998         bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3999         if (!bctl) {
4000                 ret = -ENOMEM;
4001                 goto out_bargs;
4002         }
4003
4004         bctl->fs_info = fs_info;
4005         if (arg) {
4006                 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4007                 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4008                 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4009
4010                 bctl->flags = bargs->flags;
4011         } else {
4012                 /* balance everything - no filters */
4013                 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4014         }
4015
4016 do_balance:
4017         /*
4018          * Ownership of bctl and mutually_exclusive_operation_running
4019          * goes to to btrfs_balance.  bctl is freed in __cancel_balance,
4020          * or, if restriper was paused all the way until unmount, in
4021          * free_fs_info.  mutually_exclusive_operation_running is
4022          * cleared in __cancel_balance.
4023          */
4024         need_unlock = false;
4025
4026         ret = btrfs_balance(bctl, bargs);
4027
4028         if (arg) {
4029                 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4030                         ret = -EFAULT;
4031         }
4032
4033 out_bargs:
4034         kfree(bargs);
4035 out_unlock:
4036         mutex_unlock(&fs_info->balance_mutex);
4037         mutex_unlock(&fs_info->volume_mutex);
4038         if (need_unlock)
4039                 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4040 out:
4041         mnt_drop_write_file(file);
4042         return ret;
4043 }
4044
4045 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4046 {
4047         if (!capable(CAP_SYS_ADMIN))
4048                 return -EPERM;
4049
4050         switch (cmd) {
4051         case BTRFS_BALANCE_CTL_PAUSE:
4052                 return btrfs_pause_balance(root->fs_info);
4053         case BTRFS_BALANCE_CTL_CANCEL:
4054                 return btrfs_cancel_balance(root->fs_info);
4055         }
4056
4057         return -EINVAL;
4058 }
4059
4060 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
4061                                          void __user *arg)
4062 {
4063         struct btrfs_fs_info *fs_info = root->fs_info;
4064         struct btrfs_ioctl_balance_args *bargs;
4065         int ret = 0;
4066
4067         if (!capable(CAP_SYS_ADMIN))
4068                 return -EPERM;
4069
4070         mutex_lock(&fs_info->balance_mutex);
4071         if (!fs_info->balance_ctl) {
4072                 ret = -ENOTCONN;
4073                 goto out;
4074         }
4075
4076         bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
4077         if (!bargs) {
4078                 ret = -ENOMEM;
4079                 goto out;
4080         }
4081
4082         update_ioctl_balance_args(fs_info, 1, bargs);
4083
4084         if (copy_to_user(arg, bargs, sizeof(*bargs)))
4085                 ret = -EFAULT;
4086
4087         kfree(bargs);
4088 out:
4089         mutex_unlock(&fs_info->balance_mutex);
4090         return ret;
4091 }
4092
4093 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4094 {
4095         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4096         struct btrfs_ioctl_quota_ctl_args *sa;
4097         struct btrfs_trans_handle *trans = NULL;
4098         int ret;
4099         int err;
4100
4101         if (!capable(CAP_SYS_ADMIN))
4102                 return -EPERM;
4103
4104         ret = mnt_want_write_file(file);
4105         if (ret)
4106                 return ret;
4107
4108         sa = memdup_user(arg, sizeof(*sa));
4109         if (IS_ERR(sa)) {
4110                 ret = PTR_ERR(sa);
4111                 goto drop_write;
4112         }
4113
4114         down_write(&root->fs_info->subvol_sem);
4115         trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
4116         if (IS_ERR(trans)) {
4117                 ret = PTR_ERR(trans);
4118                 goto out;
4119         }
4120
4121         switch (sa->cmd) {
4122         case BTRFS_QUOTA_CTL_ENABLE:
4123                 ret = btrfs_quota_enable(trans, root->fs_info);
4124                 break;
4125         case BTRFS_QUOTA_CTL_DISABLE:
4126                 ret = btrfs_quota_disable(trans, root->fs_info);
4127                 break;
4128         default:
4129                 ret = -EINVAL;
4130                 break;
4131         }
4132
4133         err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
4134         if (err && !ret)
4135                 ret = err;
4136 out:
4137         kfree(sa);
4138         up_write(&root->fs_info->subvol_sem);
4139 drop_write:
4140         mnt_drop_write_file(file);
4141         return ret;
4142 }
4143
4144 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4145 {
4146         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4147         struct btrfs_ioctl_qgroup_assign_args *sa;
4148         struct btrfs_trans_handle *trans;
4149         int ret;
4150         int err;
4151
4152         if (!capable(CAP_SYS_ADMIN))
4153                 return -EPERM;
4154
4155         ret = mnt_want_write_file(file);
4156         if (ret)
4157                 return ret;
4158
4159         sa = memdup_user(arg, sizeof(*sa));
4160         if (IS_ERR(sa)) {
4161                 ret = PTR_ERR(sa);
4162                 goto drop_write;
4163         }
4164
4165         trans = btrfs_join_transaction(root);
4166         if (IS_ERR(trans)) {
4167                 ret = PTR_ERR(trans);
4168                 goto out;
4169         }
4170
4171         /* FIXME: check if the IDs really exist */
4172         if (sa->assign) {
4173                 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
4174                                                 sa->src, sa->dst);
4175         } else {
4176                 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
4177                                                 sa->src, sa->dst);
4178         }
4179
4180         err = btrfs_end_transaction(trans, root);
4181         if (err && !ret)
4182                 ret = err;
4183
4184 out:
4185         kfree(sa);
4186 drop_write:
4187         mnt_drop_write_file(file);
4188         return ret;
4189 }
4190
4191 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4192 {
4193         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4194         struct btrfs_ioctl_qgroup_create_args *sa;
4195         struct btrfs_trans_handle *trans;
4196         int ret;
4197         int err;
4198
4199         if (!capable(CAP_SYS_ADMIN))
4200                 return -EPERM;
4201
4202         ret = mnt_want_write_file(file);
4203         if (ret)
4204                 return ret;
4205
4206         sa = memdup_user(arg, sizeof(*sa));
4207         if (IS_ERR(sa)) {
4208                 ret = PTR_ERR(sa);
4209                 goto drop_write;
4210         }
4211
4212         if (!sa->qgroupid) {
4213                 ret = -EINVAL;
4214                 goto out;
4215         }
4216
4217         trans = btrfs_join_transaction(root);
4218         if (IS_ERR(trans)) {
4219                 ret = PTR_ERR(trans);
4220                 goto out;
4221         }
4222
4223         /* FIXME: check if the IDs really exist */
4224         if (sa->create) {
4225                 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid,
4226                                           NULL);
4227         } else {
4228                 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
4229         }
4230
4231         err = btrfs_end_transaction(trans, root);
4232         if (err && !ret)
4233                 ret = err;
4234
4235 out:
4236         kfree(sa);
4237 drop_write:
4238         mnt_drop_write_file(file);
4239         return ret;
4240 }
4241
4242 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4243 {
4244         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4245         struct btrfs_ioctl_qgroup_limit_args *sa;
4246         struct btrfs_trans_handle *trans;
4247         int ret;
4248         int err;
4249         u64 qgroupid;
4250
4251         if (!capable(CAP_SYS_ADMIN))
4252                 return -EPERM;
4253
4254         ret = mnt_want_write_file(file);
4255         if (ret)
4256                 return ret;
4257
4258         sa = memdup_user(arg, sizeof(*sa));
4259         if (IS_ERR(sa)) {
4260                 ret = PTR_ERR(sa);
4261                 goto drop_write;
4262         }
4263
4264         trans = btrfs_join_transaction(root);
4265         if (IS_ERR(trans)) {
4266                 ret = PTR_ERR(trans);
4267                 goto out;
4268         }
4269
4270         qgroupid = sa->qgroupid;
4271         if (!qgroupid) {
4272                 /* take the current subvol as qgroup */
4273                 qgroupid = root->root_key.objectid;
4274         }
4275
4276         /* FIXME: check if the IDs really exist */
4277         ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
4278
4279         err = btrfs_end_transaction(trans, root);
4280         if (err && !ret)
4281                 ret = err;
4282
4283 out:
4284         kfree(sa);
4285 drop_write:
4286         mnt_drop_write_file(file);
4287         return ret;
4288 }
4289
4290 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4291 {
4292         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4293         struct btrfs_ioctl_quota_rescan_args *qsa;
4294         int ret;
4295
4296         if (!capable(CAP_SYS_ADMIN))
4297                 return -EPERM;
4298
4299         ret = mnt_want_write_file(file);
4300         if (ret)
4301                 return ret;
4302
4303         qsa = memdup_user(arg, sizeof(*qsa));
4304         if (IS_ERR(qsa)) {
4305                 ret = PTR_ERR(qsa);
4306                 goto drop_write;
4307         }
4308
4309         if (qsa->flags) {
4310                 ret = -EINVAL;
4311                 goto out;
4312         }
4313
4314         ret = btrfs_qgroup_rescan(root->fs_info);
4315
4316 out:
4317         kfree(qsa);
4318 drop_write:
4319         mnt_drop_write_file(file);
4320         return ret;
4321 }
4322
4323 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
4324 {
4325         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4326         struct btrfs_ioctl_quota_rescan_args *qsa;
4327         int ret = 0;
4328
4329         if (!capable(CAP_SYS_ADMIN))
4330                 return -EPERM;
4331
4332         qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
4333         if (!qsa)
4334                 return -ENOMEM;
4335
4336         if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4337                 qsa->flags = 1;
4338                 qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
4339         }
4340
4341         if (copy_to_user(arg, qsa, sizeof(*qsa)))
4342                 ret = -EFAULT;
4343
4344         kfree(qsa);
4345         return ret;
4346 }
4347
4348 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
4349 {
4350         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4351
4352         if (!capable(CAP_SYS_ADMIN))
4353                 return -EPERM;
4354
4355         return btrfs_qgroup_wait_for_completion(root->fs_info);
4356 }
4357
4358 static long btrfs_ioctl_set_received_subvol(struct file *file,
4359                                             void __user *arg)
4360 {
4361         struct btrfs_ioctl_received_subvol_args *sa = NULL;
4362         struct inode *inode = file_inode(file);
4363         struct btrfs_root *root = BTRFS_I(inode)->root;
4364         struct btrfs_root_item *root_item = &root->root_item;
4365         struct btrfs_trans_handle *trans;
4366         struct timespec ct = CURRENT_TIME;
4367         int ret = 0;
4368         int received_uuid_changed;
4369
4370         ret = mnt_want_write_file(file);
4371         if (ret < 0)
4372                 return ret;
4373
4374         down_write(&root->fs_info->subvol_sem);
4375
4376         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
4377                 ret = -EINVAL;
4378                 goto out;
4379         }
4380
4381         if (btrfs_root_readonly(root)) {
4382                 ret = -EROFS;
4383                 goto out;
4384         }
4385
4386         if (!inode_owner_or_capable(inode)) {
4387                 ret = -EACCES;
4388                 goto out;
4389         }
4390
4391         sa = memdup_user(arg, sizeof(*sa));
4392         if (IS_ERR(sa)) {
4393                 ret = PTR_ERR(sa);
4394                 sa = NULL;
4395                 goto out;
4396         }
4397
4398         /*
4399          * 1 - root item
4400          * 2 - uuid items (received uuid + subvol uuid)
4401          */
4402         trans = btrfs_start_transaction(root, 3);
4403         if (IS_ERR(trans)) {
4404                 ret = PTR_ERR(trans);
4405                 trans = NULL;
4406                 goto out;
4407         }
4408
4409         sa->rtransid = trans->transid;
4410         sa->rtime.sec = ct.tv_sec;
4411         sa->rtime.nsec = ct.tv_nsec;
4412
4413         received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4414                                        BTRFS_UUID_SIZE);
4415         if (received_uuid_changed &&
4416             !btrfs_is_empty_uuid(root_item->received_uuid))
4417                 btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
4418                                     root_item->received_uuid,
4419                                     BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4420                                     root->root_key.objectid);
4421         memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4422         btrfs_set_root_stransid(root_item, sa->stransid);
4423         btrfs_set_root_rtransid(root_item, sa->rtransid);
4424         btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4425         btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4426         btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4427         btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4428
4429         ret = btrfs_update_root(trans, root->fs_info->tree_root,
4430                                 &root->root_key, &root->root_item);
4431         if (ret < 0) {
4432                 btrfs_end_transaction(trans, root);
4433                 goto out;
4434         }
4435         if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4436                 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
4437                                           sa->uuid,
4438                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4439                                           root->root_key.objectid);
4440                 if (ret < 0 && ret != -EEXIST) {
4441                         btrfs_abort_transaction(trans, root, ret);
4442                         goto out;
4443                 }
4444         }
4445         ret = btrfs_commit_transaction(trans, root);
4446         if (ret < 0) {
4447                 btrfs_abort_transaction(trans, root, ret);
4448                 goto out;
4449         }
4450
4451         ret = copy_to_user(arg, sa, sizeof(*sa));
4452         if (ret)
4453                 ret = -EFAULT;
4454
4455 out:
4456         kfree(sa);
4457         up_write(&root->fs_info->subvol_sem);
4458         mnt_drop_write_file(file);
4459         return ret;
4460 }
4461
4462 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
4463 {
4464         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4465         size_t len;
4466         int ret;
4467         char label[BTRFS_LABEL_SIZE];
4468
4469         spin_lock(&root->fs_info->super_lock);
4470         memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4471         spin_unlock(&root->fs_info->super_lock);
4472
4473         len = strnlen(label, BTRFS_LABEL_SIZE);
4474
4475         if (len == BTRFS_LABEL_SIZE) {
4476                 btrfs_warn(root->fs_info,
4477                         "label is too long, return the first %zu bytes", --len);
4478         }
4479
4480         ret = copy_to_user(arg, label, len);
4481
4482         return ret ? -EFAULT : 0;
4483 }
4484
4485 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4486 {
4487         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4488         struct btrfs_super_block *super_block = root->fs_info->super_copy;
4489         struct btrfs_trans_handle *trans;
4490         char label[BTRFS_LABEL_SIZE];
4491         int ret;
4492
4493         if (!capable(CAP_SYS_ADMIN))
4494                 return -EPERM;
4495
4496         if (copy_from_user(label, arg, sizeof(label)))
4497                 return -EFAULT;
4498
4499         if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4500                 btrfs_err(root->fs_info, "unable to set label with more than %d bytes",
4501                        BTRFS_LABEL_SIZE - 1);
4502                 return -EINVAL;
4503         }
4504
4505         ret = mnt_want_write_file(file);
4506         if (ret)
4507                 return ret;
4508
4509         trans = btrfs_start_transaction(root, 0);
4510         if (IS_ERR(trans)) {
4511                 ret = PTR_ERR(trans);
4512                 goto out_unlock;
4513         }
4514
4515         spin_lock(&root->fs_info->super_lock);
4516         strcpy(super_block->label, label);
4517         spin_unlock(&root->fs_info->super_lock);
4518         ret = btrfs_end_transaction(trans, root);
4519
4520 out_unlock:
4521         mnt_drop_write_file(file);
4522         return ret;
4523 }
4524
4525 #define INIT_FEATURE_FLAGS(suffix) \
4526         { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
4527           .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
4528           .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
4529
4530 static int btrfs_ioctl_get_supported_features(struct file *file,
4531                                               void __user *arg)
4532 {
4533         static struct btrfs_ioctl_feature_flags features[3] = {
4534                 INIT_FEATURE_FLAGS(SUPP),
4535                 INIT_FEATURE_FLAGS(SAFE_SET),
4536                 INIT_FEATURE_FLAGS(SAFE_CLEAR)
4537         };
4538
4539         if (copy_to_user(arg, &features, sizeof(features)))
4540                 return -EFAULT;
4541
4542         return 0;
4543 }
4544
4545 static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
4546 {
4547         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4548         struct btrfs_super_block *super_block = root->fs_info->super_copy;
4549         struct btrfs_ioctl_feature_flags features;
4550
4551         features.compat_flags = btrfs_super_compat_flags(super_block);
4552         features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
4553         features.incompat_flags = btrfs_super_incompat_flags(super_block);
4554
4555         if (copy_to_user(arg, &features, sizeof(features)))
4556                 return -EFAULT;
4557
4558         return 0;
4559 }
4560
4561 static int check_feature_bits(struct btrfs_root *root,
4562                               enum btrfs_feature_set set,
4563                               u64 change_mask, u64 flags, u64 supported_flags,
4564                               u64 safe_set, u64 safe_clear)
4565 {
4566         const char *type = btrfs_feature_set_names[set];
4567         char *names;
4568         u64 disallowed, unsupported;
4569         u64 set_mask = flags & change_mask;
4570         u64 clear_mask = ~flags & change_mask;
4571
4572         unsupported = set_mask & ~supported_flags;
4573         if (unsupported) {
4574                 names = btrfs_printable_features(set, unsupported);
4575                 if (names) {
4576                         btrfs_warn(root->fs_info,
4577                            "this kernel does not support the %s feature bit%s",
4578                            names, strchr(names, ',') ? "s" : "");
4579                         kfree(names);
4580                 } else
4581                         btrfs_warn(root->fs_info,
4582                            "this kernel does not support %s bits 0x%llx",
4583                            type, unsupported);
4584                 return -EOPNOTSUPP;
4585         }
4586
4587         disallowed = set_mask & ~safe_set;
4588         if (disallowed) {
4589                 names = btrfs_printable_features(set, disallowed);
4590                 if (names) {
4591                         btrfs_warn(root->fs_info,
4592                            "can't set the %s feature bit%s while mounted",
4593                            names, strchr(names, ',') ? "s" : "");
4594                         kfree(names);
4595                 } else
4596                         btrfs_warn(root->fs_info,
4597                            "can't set %s bits 0x%llx while mounted",
4598                            type, disallowed);
4599                 return -EPERM;
4600         }
4601
4602         disallowed = clear_mask & ~safe_clear;
4603         if (disallowed) {
4604                 names = btrfs_printable_features(set, disallowed);
4605                 if (names) {
4606                         btrfs_warn(root->fs_info,
4607                            "can't clear the %s feature bit%s while mounted",
4608                            names, strchr(names, ',') ? "s" : "");
4609                         kfree(names);
4610                 } else
4611                         btrfs_warn(root->fs_info,
4612                            "can't clear %s bits 0x%llx while mounted",
4613                            type, disallowed);
4614                 return -EPERM;
4615         }
4616
4617         return 0;
4618 }
4619
4620 #define check_feature(root, change_mask, flags, mask_base)      \
4621 check_feature_bits(root, FEAT_##mask_base, change_mask, flags,  \
4622                    BTRFS_FEATURE_ ## mask_base ## _SUPP,        \
4623                    BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,    \
4624                    BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
4625
4626 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
4627 {
4628         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4629         struct btrfs_super_block *super_block = root->fs_info->super_copy;
4630         struct btrfs_ioctl_feature_flags flags[2];
4631         struct btrfs_trans_handle *trans;
4632         u64 newflags;
4633         int ret;
4634
4635         if (!capable(CAP_SYS_ADMIN))
4636                 return -EPERM;
4637
4638         if (copy_from_user(flags, arg, sizeof(flags)))
4639                 return -EFAULT;
4640
4641         /* Nothing to do */
4642         if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
4643             !flags[0].incompat_flags)
4644                 return 0;
4645
4646         ret = check_feature(root, flags[0].compat_flags,
4647                             flags[1].compat_flags, COMPAT);
4648         if (ret)
4649                 return ret;
4650
4651         ret = check_feature(root, flags[0].compat_ro_flags,
4652                             flags[1].compat_ro_flags, COMPAT_RO);
4653         if (ret)
4654                 return ret;
4655
4656         ret = check_feature(root, flags[0].incompat_flags,
4657                             flags[1].incompat_flags, INCOMPAT);
4658         if (ret)
4659                 return ret;
4660
4661         trans = btrfs_start_transaction(root, 1);
4662         if (IS_ERR(trans))
4663                 return PTR_ERR(trans);
4664
4665         spin_lock(&root->fs_info->super_lock);
4666         newflags = btrfs_super_compat_flags(super_block);
4667         newflags |= flags[0].compat_flags & flags[1].compat_flags;
4668         newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
4669         btrfs_set_super_compat_flags(super_block, newflags);
4670
4671         newflags = btrfs_super_compat_ro_flags(super_block);
4672         newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
4673         newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
4674         btrfs_set_super_compat_ro_flags(super_block, newflags);
4675
4676         newflags = btrfs_super_incompat_flags(super_block);
4677         newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
4678         newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
4679         btrfs_set_super_incompat_flags(super_block, newflags);
4680         spin_unlock(&root->fs_info->super_lock);
4681
4682         return btrfs_end_transaction(trans, root);
4683 }
4684
4685 long btrfs_ioctl(struct file *file, unsigned int
4686                 cmd, unsigned long arg)
4687 {
4688         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4689         void __user *argp = (void __user *)arg;
4690
4691         switch (cmd) {
4692         case FS_IOC_GETFLAGS:
4693                 return btrfs_ioctl_getflags(file, argp);
4694         case FS_IOC_SETFLAGS:
4695                 return btrfs_ioctl_setflags(file, argp);
4696         case FS_IOC_GETVERSION:
4697                 return btrfs_ioctl_getversion(file, argp);
4698         case FITRIM:
4699                 return btrfs_ioctl_fitrim(file, argp);
4700         case BTRFS_IOC_SNAP_CREATE:
4701                 return btrfs_ioctl_snap_create(file, argp, 0);
4702         case BTRFS_IOC_SNAP_CREATE_V2:
4703                 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4704         case BTRFS_IOC_SUBVOL_CREATE:
4705                 return btrfs_ioctl_snap_create(file, argp, 1);
4706         case BTRFS_IOC_SUBVOL_CREATE_V2:
4707                 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4708         case BTRFS_IOC_SNAP_DESTROY:
4709                 return btrfs_ioctl_snap_destroy(file, argp);
4710         case BTRFS_IOC_SUBVOL_GETFLAGS:
4711                 return btrfs_ioctl_subvol_getflags(file, argp);
4712         case BTRFS_IOC_SUBVOL_SETFLAGS:
4713                 return btrfs_ioctl_subvol_setflags(file, argp);
4714         case BTRFS_IOC_DEFAULT_SUBVOL:
4715                 return btrfs_ioctl_default_subvol(file, argp);
4716         case BTRFS_IOC_DEFRAG:
4717                 return btrfs_ioctl_defrag(file, NULL);
4718         case BTRFS_IOC_DEFRAG_RANGE:
4719                 return btrfs_ioctl_defrag(file, argp);
4720         case BTRFS_IOC_RESIZE:
4721                 return btrfs_ioctl_resize(file, argp);
4722         case BTRFS_IOC_ADD_DEV:
4723                 return btrfs_ioctl_add_dev(root, argp);
4724         case BTRFS_IOC_RM_DEV:
4725                 return btrfs_ioctl_rm_dev(file, argp);
4726         case BTRFS_IOC_FS_INFO:
4727                 return btrfs_ioctl_fs_info(root, argp);
4728         case BTRFS_IOC_DEV_INFO:
4729                 return btrfs_ioctl_dev_info(root, argp);
4730         case BTRFS_IOC_BALANCE:
4731                 return btrfs_ioctl_balance(file, NULL);
4732         case BTRFS_IOC_CLONE:
4733                 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
4734         case BTRFS_IOC_CLONE_RANGE:
4735                 return btrfs_ioctl_clone_range(file, argp);
4736         case BTRFS_IOC_TRANS_START:
4737                 return btrfs_ioctl_trans_start(file);
4738         case BTRFS_IOC_TRANS_END:
4739                 return btrfs_ioctl_trans_end(file);
4740         case BTRFS_IOC_TREE_SEARCH:
4741                 return btrfs_ioctl_tree_search(file, argp);
4742         case BTRFS_IOC_INO_LOOKUP:
4743                 return btrfs_ioctl_ino_lookup(file, argp);
4744         case BTRFS_IOC_INO_PATHS:
4745                 return btrfs_ioctl_ino_to_path(root, argp);
4746         case BTRFS_IOC_LOGICAL_INO:
4747                 return btrfs_ioctl_logical_to_ino(root, argp);
4748         case BTRFS_IOC_SPACE_INFO:
4749                 return btrfs_ioctl_space_info(root, argp);
4750         case BTRFS_IOC_GLOBAL_RSV:
4751                 return btrfs_ioctl_global_rsv(root, argp);
4752         case BTRFS_IOC_SYNC: {
4753                 int ret;
4754
4755                 ret = btrfs_start_delalloc_roots(root->fs_info, 0);
4756                 if (ret)
4757                         return ret;
4758                 ret = btrfs_sync_fs(file->f_dentry->d_sb, 1);
4759                 return ret;
4760         }
4761         case BTRFS_IOC_START_SYNC:
4762                 return btrfs_ioctl_start_sync(root, argp);
4763         case BTRFS_IOC_WAIT_SYNC:
4764                 return btrfs_ioctl_wait_sync(root, argp);
4765         case BTRFS_IOC_SCRUB:
4766                 return btrfs_ioctl_scrub(file, argp);
4767         case BTRFS_IOC_SCRUB_CANCEL:
4768                 return btrfs_ioctl_scrub_cancel(root, argp);
4769         case BTRFS_IOC_SCRUB_PROGRESS:
4770                 return btrfs_ioctl_scrub_progress(root, argp);
4771         case BTRFS_IOC_BALANCE_V2:
4772                 return btrfs_ioctl_balance(file, argp);
4773         case BTRFS_IOC_BALANCE_CTL:
4774                 return btrfs_ioctl_balance_ctl(root, arg);
4775         case BTRFS_IOC_BALANCE_PROGRESS:
4776                 return btrfs_ioctl_balance_progress(root, argp);
4777         case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4778                 return btrfs_ioctl_set_received_subvol(file, argp);
4779         case BTRFS_IOC_SEND:
4780                 return btrfs_ioctl_send(file, argp);
4781         case BTRFS_IOC_GET_DEV_STATS:
4782                 return btrfs_ioctl_get_dev_stats(root, argp);
4783         case BTRFS_IOC_QUOTA_CTL:
4784                 return btrfs_ioctl_quota_ctl(file, argp);
4785         case BTRFS_IOC_QGROUP_ASSIGN:
4786                 return btrfs_ioctl_qgroup_assign(file, argp);
4787         case BTRFS_IOC_QGROUP_CREATE:
4788                 return btrfs_ioctl_qgroup_create(file, argp);
4789         case BTRFS_IOC_QGROUP_LIMIT:
4790                 return btrfs_ioctl_qgroup_limit(file, argp);
4791         case BTRFS_IOC_QUOTA_RESCAN:
4792                 return btrfs_ioctl_quota_rescan(file, argp);
4793         case BTRFS_IOC_QUOTA_RESCAN_STATUS:
4794                 return btrfs_ioctl_quota_rescan_status(file, argp);
4795         case BTRFS_IOC_QUOTA_RESCAN_WAIT:
4796                 return btrfs_ioctl_quota_rescan_wait(file, argp);
4797         case BTRFS_IOC_DEV_REPLACE:
4798                 return btrfs_ioctl_dev_replace(root, argp);
4799         case BTRFS_IOC_GET_FSLABEL:
4800                 return btrfs_ioctl_get_fslabel(file, argp);
4801         case BTRFS_IOC_SET_FSLABEL:
4802                 return btrfs_ioctl_set_fslabel(file, argp);
4803         case BTRFS_IOC_FILE_EXTENT_SAME:
4804                 return btrfs_ioctl_file_extent_same(file, argp);
4805         case BTRFS_IOC_GET_SUPPORTED_FEATURES:
4806                 return btrfs_ioctl_get_supported_features(file, argp);
4807         case BTRFS_IOC_GET_FEATURES:
4808                 return btrfs_ioctl_get_features(file, argp);
4809         case BTRFS_IOC_SET_FEATURES:
4810                 return btrfs_ioctl_set_features(file, argp);
4811         }
4812
4813         return -ENOTTY;
4814 }