Merge branch 'drm-intel-fixes' of git://people.freedesktop.org/~danvet/drm-intel...
[linux.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 "compat.h"
45 #include "ctree.h"
46 #include "disk-io.h"
47 #include "transaction.h"
48 #include "btrfs_inode.h"
49 #include "ioctl.h"
50 #include "print-tree.h"
51 #include "volumes.h"
52 #include "locking.h"
53 #include "inode-map.h"
54 #include "backref.h"
55
56 /* Mask out flags that are inappropriate for the given type of inode. */
57 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
58 {
59         if (S_ISDIR(mode))
60                 return flags;
61         else if (S_ISREG(mode))
62                 return flags & ~FS_DIRSYNC_FL;
63         else
64                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
65 }
66
67 /*
68  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
69  */
70 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
71 {
72         unsigned int iflags = 0;
73
74         if (flags & BTRFS_INODE_SYNC)
75                 iflags |= FS_SYNC_FL;
76         if (flags & BTRFS_INODE_IMMUTABLE)
77                 iflags |= FS_IMMUTABLE_FL;
78         if (flags & BTRFS_INODE_APPEND)
79                 iflags |= FS_APPEND_FL;
80         if (flags & BTRFS_INODE_NODUMP)
81                 iflags |= FS_NODUMP_FL;
82         if (flags & BTRFS_INODE_NOATIME)
83                 iflags |= FS_NOATIME_FL;
84         if (flags & BTRFS_INODE_DIRSYNC)
85                 iflags |= FS_DIRSYNC_FL;
86         if (flags & BTRFS_INODE_NODATACOW)
87                 iflags |= FS_NOCOW_FL;
88
89         if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
90                 iflags |= FS_COMPR_FL;
91         else if (flags & BTRFS_INODE_NOCOMPRESS)
92                 iflags |= FS_NOCOMP_FL;
93
94         return iflags;
95 }
96
97 /*
98  * Update inode->i_flags based on the btrfs internal flags.
99  */
100 void btrfs_update_iflags(struct inode *inode)
101 {
102         struct btrfs_inode *ip = BTRFS_I(inode);
103
104         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
105
106         if (ip->flags & BTRFS_INODE_SYNC)
107                 inode->i_flags |= S_SYNC;
108         if (ip->flags & BTRFS_INODE_IMMUTABLE)
109                 inode->i_flags |= S_IMMUTABLE;
110         if (ip->flags & BTRFS_INODE_APPEND)
111                 inode->i_flags |= S_APPEND;
112         if (ip->flags & BTRFS_INODE_NOATIME)
113                 inode->i_flags |= S_NOATIME;
114         if (ip->flags & BTRFS_INODE_DIRSYNC)
115                 inode->i_flags |= S_DIRSYNC;
116 }
117
118 /*
119  * Inherit flags from the parent inode.
120  *
121  * Currently only the compression flags and the cow flags are inherited.
122  */
123 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
124 {
125         unsigned int flags;
126
127         if (!dir)
128                 return;
129
130         flags = BTRFS_I(dir)->flags;
131
132         if (flags & BTRFS_INODE_NOCOMPRESS) {
133                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
134                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
135         } else if (flags & BTRFS_INODE_COMPRESS) {
136                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
137                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
138         }
139
140         if (flags & BTRFS_INODE_NODATACOW)
141                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
142
143         btrfs_update_iflags(inode);
144 }
145
146 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
147 {
148         struct btrfs_inode *ip = BTRFS_I(file->f_path.dentry->d_inode);
149         unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
150
151         if (copy_to_user(arg, &flags, sizeof(flags)))
152                 return -EFAULT;
153         return 0;
154 }
155
156 static int check_flags(unsigned int flags)
157 {
158         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
159                       FS_NOATIME_FL | FS_NODUMP_FL | \
160                       FS_SYNC_FL | FS_DIRSYNC_FL | \
161                       FS_NOCOMP_FL | FS_COMPR_FL |
162                       FS_NOCOW_FL))
163                 return -EOPNOTSUPP;
164
165         if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
166                 return -EINVAL;
167
168         return 0;
169 }
170
171 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
172 {
173         struct inode *inode = file->f_path.dentry->d_inode;
174         struct btrfs_inode *ip = BTRFS_I(inode);
175         struct btrfs_root *root = ip->root;
176         struct btrfs_trans_handle *trans;
177         unsigned int flags, oldflags;
178         int ret;
179         u64 ip_oldflags;
180         unsigned int i_oldflags;
181
182         if (btrfs_root_readonly(root))
183                 return -EROFS;
184
185         if (copy_from_user(&flags, arg, sizeof(flags)))
186                 return -EFAULT;
187
188         ret = check_flags(flags);
189         if (ret)
190                 return ret;
191
192         if (!inode_owner_or_capable(inode))
193                 return -EACCES;
194
195         mutex_lock(&inode->i_mutex);
196
197         ip_oldflags = ip->flags;
198         i_oldflags = inode->i_flags;
199
200         flags = btrfs_mask_flags(inode->i_mode, flags);
201         oldflags = btrfs_flags_to_ioctl(ip->flags);
202         if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
203                 if (!capable(CAP_LINUX_IMMUTABLE)) {
204                         ret = -EPERM;
205                         goto out_unlock;
206                 }
207         }
208
209         ret = mnt_want_write_file(file);
210         if (ret)
211                 goto out_unlock;
212
213         if (flags & FS_SYNC_FL)
214                 ip->flags |= BTRFS_INODE_SYNC;
215         else
216                 ip->flags &= ~BTRFS_INODE_SYNC;
217         if (flags & FS_IMMUTABLE_FL)
218                 ip->flags |= BTRFS_INODE_IMMUTABLE;
219         else
220                 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
221         if (flags & FS_APPEND_FL)
222                 ip->flags |= BTRFS_INODE_APPEND;
223         else
224                 ip->flags &= ~BTRFS_INODE_APPEND;
225         if (flags & FS_NODUMP_FL)
226                 ip->flags |= BTRFS_INODE_NODUMP;
227         else
228                 ip->flags &= ~BTRFS_INODE_NODUMP;
229         if (flags & FS_NOATIME_FL)
230                 ip->flags |= BTRFS_INODE_NOATIME;
231         else
232                 ip->flags &= ~BTRFS_INODE_NOATIME;
233         if (flags & FS_DIRSYNC_FL)
234                 ip->flags |= BTRFS_INODE_DIRSYNC;
235         else
236                 ip->flags &= ~BTRFS_INODE_DIRSYNC;
237         if (flags & FS_NOCOW_FL)
238                 ip->flags |= BTRFS_INODE_NODATACOW;
239         else
240                 ip->flags &= ~BTRFS_INODE_NODATACOW;
241
242         /*
243          * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
244          * flag may be changed automatically if compression code won't make
245          * things smaller.
246          */
247         if (flags & FS_NOCOMP_FL) {
248                 ip->flags &= ~BTRFS_INODE_COMPRESS;
249                 ip->flags |= BTRFS_INODE_NOCOMPRESS;
250         } else if (flags & FS_COMPR_FL) {
251                 ip->flags |= BTRFS_INODE_COMPRESS;
252                 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
253         } else {
254                 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
255         }
256
257         trans = btrfs_start_transaction(root, 1);
258         if (IS_ERR(trans)) {
259                 ret = PTR_ERR(trans);
260                 goto out_drop;
261         }
262
263         btrfs_update_iflags(inode);
264         inode_inc_iversion(inode);
265         inode->i_ctime = CURRENT_TIME;
266         ret = btrfs_update_inode(trans, root, inode);
267
268         btrfs_end_transaction(trans, root);
269  out_drop:
270         if (ret) {
271                 ip->flags = ip_oldflags;
272                 inode->i_flags = i_oldflags;
273         }
274
275         mnt_drop_write_file(file);
276  out_unlock:
277         mutex_unlock(&inode->i_mutex);
278         return ret;
279 }
280
281 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
282 {
283         struct inode *inode = file->f_path.dentry->d_inode;
284
285         return put_user(inode->i_generation, arg);
286 }
287
288 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
289 {
290         struct btrfs_fs_info *fs_info = btrfs_sb(fdentry(file)->d_sb);
291         struct btrfs_device *device;
292         struct request_queue *q;
293         struct fstrim_range range;
294         u64 minlen = ULLONG_MAX;
295         u64 num_devices = 0;
296         u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
297         int ret;
298
299         if (!capable(CAP_SYS_ADMIN))
300                 return -EPERM;
301
302         rcu_read_lock();
303         list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
304                                 dev_list) {
305                 if (!device->bdev)
306                         continue;
307                 q = bdev_get_queue(device->bdev);
308                 if (blk_queue_discard(q)) {
309                         num_devices++;
310                         minlen = min((u64)q->limits.discard_granularity,
311                                      minlen);
312                 }
313         }
314         rcu_read_unlock();
315
316         if (!num_devices)
317                 return -EOPNOTSUPP;
318         if (copy_from_user(&range, arg, sizeof(range)))
319                 return -EFAULT;
320         if (range.start > total_bytes)
321                 return -EINVAL;
322
323         range.len = min(range.len, total_bytes - range.start);
324         range.minlen = max(range.minlen, minlen);
325         ret = btrfs_trim_fs(fs_info->tree_root, &range);
326         if (ret < 0)
327                 return ret;
328
329         if (copy_to_user(arg, &range, sizeof(range)))
330                 return -EFAULT;
331
332         return 0;
333 }
334
335 static noinline int create_subvol(struct btrfs_root *root,
336                                   struct dentry *dentry,
337                                   char *name, int namelen,
338                                   u64 *async_transid)
339 {
340         struct btrfs_trans_handle *trans;
341         struct btrfs_key key;
342         struct btrfs_root_item root_item;
343         struct btrfs_inode_item *inode_item;
344         struct extent_buffer *leaf;
345         struct btrfs_root *new_root;
346         struct dentry *parent = dentry->d_parent;
347         struct inode *dir;
348         int ret;
349         int err;
350         u64 objectid;
351         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
352         u64 index = 0;
353
354         ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
355         if (ret)
356                 return ret;
357
358         dir = parent->d_inode;
359
360         /*
361          * 1 - inode item
362          * 2 - refs
363          * 1 - root item
364          * 2 - dir items
365          */
366         trans = btrfs_start_transaction(root, 6);
367         if (IS_ERR(trans))
368                 return PTR_ERR(trans);
369
370         leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
371                                       0, objectid, NULL, 0, 0, 0);
372         if (IS_ERR(leaf)) {
373                 ret = PTR_ERR(leaf);
374                 goto fail;
375         }
376
377         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
378         btrfs_set_header_bytenr(leaf, leaf->start);
379         btrfs_set_header_generation(leaf, trans->transid);
380         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
381         btrfs_set_header_owner(leaf, objectid);
382
383         write_extent_buffer(leaf, root->fs_info->fsid,
384                             (unsigned long)btrfs_header_fsid(leaf),
385                             BTRFS_FSID_SIZE);
386         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
387                             (unsigned long)btrfs_header_chunk_tree_uuid(leaf),
388                             BTRFS_UUID_SIZE);
389         btrfs_mark_buffer_dirty(leaf);
390
391         inode_item = &root_item.inode;
392         memset(inode_item, 0, sizeof(*inode_item));
393         inode_item->generation = cpu_to_le64(1);
394         inode_item->size = cpu_to_le64(3);
395         inode_item->nlink = cpu_to_le32(1);
396         inode_item->nbytes = cpu_to_le64(root->leafsize);
397         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
398
399         root_item.flags = 0;
400         root_item.byte_limit = 0;
401         inode_item->flags = cpu_to_le64(BTRFS_INODE_ROOT_ITEM_INIT);
402
403         btrfs_set_root_bytenr(&root_item, leaf->start);
404         btrfs_set_root_generation(&root_item, trans->transid);
405         btrfs_set_root_level(&root_item, 0);
406         btrfs_set_root_refs(&root_item, 1);
407         btrfs_set_root_used(&root_item, leaf->len);
408         btrfs_set_root_last_snapshot(&root_item, 0);
409
410         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
411         root_item.drop_level = 0;
412
413         btrfs_tree_unlock(leaf);
414         free_extent_buffer(leaf);
415         leaf = NULL;
416
417         btrfs_set_root_dirid(&root_item, new_dirid);
418
419         key.objectid = objectid;
420         key.offset = 0;
421         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
422         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
423                                 &root_item);
424         if (ret)
425                 goto fail;
426
427         key.offset = (u64)-1;
428         new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
429         if (IS_ERR(new_root)) {
430                 btrfs_abort_transaction(trans, root, PTR_ERR(new_root));
431                 ret = PTR_ERR(new_root);
432                 goto fail;
433         }
434
435         btrfs_record_root_in_trans(trans, new_root);
436
437         ret = btrfs_create_subvol_root(trans, new_root, new_dirid);
438         if (ret) {
439                 /* We potentially lose an unused inode item here */
440                 btrfs_abort_transaction(trans, root, ret);
441                 goto fail;
442         }
443
444         /*
445          * insert the directory item
446          */
447         ret = btrfs_set_inode_index(dir, &index);
448         if (ret) {
449                 btrfs_abort_transaction(trans, root, ret);
450                 goto fail;
451         }
452
453         ret = btrfs_insert_dir_item(trans, root,
454                                     name, namelen, dir, &key,
455                                     BTRFS_FT_DIR, index);
456         if (ret) {
457                 btrfs_abort_transaction(trans, root, ret);
458                 goto fail;
459         }
460
461         btrfs_i_size_write(dir, dir->i_size + namelen * 2);
462         ret = btrfs_update_inode(trans, root, dir);
463         BUG_ON(ret);
464
465         ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
466                                  objectid, root->root_key.objectid,
467                                  btrfs_ino(dir), index, name, namelen);
468
469         BUG_ON(ret);
470
471         d_instantiate(dentry, btrfs_lookup_dentry(dir, dentry));
472 fail:
473         if (async_transid) {
474                 *async_transid = trans->transid;
475                 err = btrfs_commit_transaction_async(trans, root, 1);
476         } else {
477                 err = btrfs_commit_transaction(trans, root);
478         }
479         if (err && !ret)
480                 ret = err;
481         return ret;
482 }
483
484 static int create_snapshot(struct btrfs_root *root, struct dentry *dentry,
485                            char *name, int namelen, u64 *async_transid,
486                            bool readonly)
487 {
488         struct inode *inode;
489         struct btrfs_pending_snapshot *pending_snapshot;
490         struct btrfs_trans_handle *trans;
491         int ret;
492
493         if (!root->ref_cows)
494                 return -EINVAL;
495
496         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
497         if (!pending_snapshot)
498                 return -ENOMEM;
499
500         btrfs_init_block_rsv(&pending_snapshot->block_rsv);
501         pending_snapshot->dentry = dentry;
502         pending_snapshot->root = root;
503         pending_snapshot->readonly = readonly;
504
505         trans = btrfs_start_transaction(root->fs_info->extent_root, 5);
506         if (IS_ERR(trans)) {
507                 ret = PTR_ERR(trans);
508                 goto fail;
509         }
510
511         ret = btrfs_snap_reserve_metadata(trans, pending_snapshot);
512         BUG_ON(ret);
513
514         spin_lock(&root->fs_info->trans_lock);
515         list_add(&pending_snapshot->list,
516                  &trans->transaction->pending_snapshots);
517         spin_unlock(&root->fs_info->trans_lock);
518         if (async_transid) {
519                 *async_transid = trans->transid;
520                 ret = btrfs_commit_transaction_async(trans,
521                                      root->fs_info->extent_root, 1);
522         } else {
523                 ret = btrfs_commit_transaction(trans,
524                                                root->fs_info->extent_root);
525         }
526         BUG_ON(ret);
527
528         ret = pending_snapshot->error;
529         if (ret)
530                 goto fail;
531
532         ret = btrfs_orphan_cleanup(pending_snapshot->snap);
533         if (ret)
534                 goto fail;
535
536         inode = btrfs_lookup_dentry(dentry->d_parent->d_inode, dentry);
537         if (IS_ERR(inode)) {
538                 ret = PTR_ERR(inode);
539                 goto fail;
540         }
541         BUG_ON(!inode);
542         d_instantiate(dentry, inode);
543         ret = 0;
544 fail:
545         kfree(pending_snapshot);
546         return ret;
547 }
548
549 /*  copy of check_sticky in fs/namei.c()
550 * It's inline, so penalty for filesystems that don't use sticky bit is
551 * minimal.
552 */
553 static inline int btrfs_check_sticky(struct inode *dir, struct inode *inode)
554 {
555         uid_t fsuid = current_fsuid();
556
557         if (!(dir->i_mode & S_ISVTX))
558                 return 0;
559         if (inode->i_uid == fsuid)
560                 return 0;
561         if (dir->i_uid == fsuid)
562                 return 0;
563         return !capable(CAP_FOWNER);
564 }
565
566 /*  copy of may_delete in fs/namei.c()
567  *      Check whether we can remove a link victim from directory dir, check
568  *  whether the type of victim is right.
569  *  1. We can't do it if dir is read-only (done in permission())
570  *  2. We should have write and exec permissions on dir
571  *  3. We can't remove anything from append-only dir
572  *  4. We can't do anything with immutable dir (done in permission())
573  *  5. If the sticky bit on dir is set we should either
574  *      a. be owner of dir, or
575  *      b. be owner of victim, or
576  *      c. have CAP_FOWNER capability
577  *  6. If the victim is append-only or immutable we can't do antyhing with
578  *     links pointing to it.
579  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
580  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
581  *  9. We can't remove a root or mountpoint.
582  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
583  *     nfs_async_unlink().
584  */
585
586 static int btrfs_may_delete(struct inode *dir,struct dentry *victim,int isdir)
587 {
588         int error;
589
590         if (!victim->d_inode)
591                 return -ENOENT;
592
593         BUG_ON(victim->d_parent->d_inode != dir);
594         audit_inode_child(victim, dir);
595
596         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
597         if (error)
598                 return error;
599         if (IS_APPEND(dir))
600                 return -EPERM;
601         if (btrfs_check_sticky(dir, victim->d_inode)||
602                 IS_APPEND(victim->d_inode)||
603             IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
604                 return -EPERM;
605         if (isdir) {
606                 if (!S_ISDIR(victim->d_inode->i_mode))
607                         return -ENOTDIR;
608                 if (IS_ROOT(victim))
609                         return -EBUSY;
610         } else if (S_ISDIR(victim->d_inode->i_mode))
611                 return -EISDIR;
612         if (IS_DEADDIR(dir))
613                 return -ENOENT;
614         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
615                 return -EBUSY;
616         return 0;
617 }
618
619 /* copy of may_create in fs/namei.c() */
620 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
621 {
622         if (child->d_inode)
623                 return -EEXIST;
624         if (IS_DEADDIR(dir))
625                 return -ENOENT;
626         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
627 }
628
629 /*
630  * Create a new subvolume below @parent.  This is largely modeled after
631  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
632  * inside this filesystem so it's quite a bit simpler.
633  */
634 static noinline int btrfs_mksubvol(struct path *parent,
635                                    char *name, int namelen,
636                                    struct btrfs_root *snap_src,
637                                    u64 *async_transid, bool readonly)
638 {
639         struct inode *dir  = parent->dentry->d_inode;
640         struct dentry *dentry;
641         int error;
642
643         mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
644
645         dentry = lookup_one_len(name, parent->dentry, namelen);
646         error = PTR_ERR(dentry);
647         if (IS_ERR(dentry))
648                 goto out_unlock;
649
650         error = -EEXIST;
651         if (dentry->d_inode)
652                 goto out_dput;
653
654         error = mnt_want_write(parent->mnt);
655         if (error)
656                 goto out_dput;
657
658         error = btrfs_may_create(dir, dentry);
659         if (error)
660                 goto out_drop_write;
661
662         down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
663
664         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
665                 goto out_up_read;
666
667         if (snap_src) {
668                 error = create_snapshot(snap_src, dentry,
669                                         name, namelen, async_transid, readonly);
670         } else {
671                 error = create_subvol(BTRFS_I(dir)->root, dentry,
672                                       name, namelen, async_transid);
673         }
674         if (!error)
675                 fsnotify_mkdir(dir, dentry);
676 out_up_read:
677         up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
678 out_drop_write:
679         mnt_drop_write(parent->mnt);
680 out_dput:
681         dput(dentry);
682 out_unlock:
683         mutex_unlock(&dir->i_mutex);
684         return error;
685 }
686
687 /*
688  * When we're defragging a range, we don't want to kick it off again
689  * if it is really just waiting for delalloc to send it down.
690  * If we find a nice big extent or delalloc range for the bytes in the
691  * file you want to defrag, we return 0 to let you know to skip this
692  * part of the file
693  */
694 static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh)
695 {
696         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
697         struct extent_map *em = NULL;
698         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
699         u64 end;
700
701         read_lock(&em_tree->lock);
702         em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
703         read_unlock(&em_tree->lock);
704
705         if (em) {
706                 end = extent_map_end(em);
707                 free_extent_map(em);
708                 if (end - offset > thresh)
709                         return 0;
710         }
711         /* if we already have a nice delalloc here, just stop */
712         thresh /= 2;
713         end = count_range_bits(io_tree, &offset, offset + thresh,
714                                thresh, EXTENT_DELALLOC, 1);
715         if (end >= thresh)
716                 return 0;
717         return 1;
718 }
719
720 /*
721  * helper function to walk through a file and find extents
722  * newer than a specific transid, and smaller than thresh.
723  *
724  * This is used by the defragging code to find new and small
725  * extents
726  */
727 static int find_new_extents(struct btrfs_root *root,
728                             struct inode *inode, u64 newer_than,
729                             u64 *off, int thresh)
730 {
731         struct btrfs_path *path;
732         struct btrfs_key min_key;
733         struct btrfs_key max_key;
734         struct extent_buffer *leaf;
735         struct btrfs_file_extent_item *extent;
736         int type;
737         int ret;
738         u64 ino = btrfs_ino(inode);
739
740         path = btrfs_alloc_path();
741         if (!path)
742                 return -ENOMEM;
743
744         min_key.objectid = ino;
745         min_key.type = BTRFS_EXTENT_DATA_KEY;
746         min_key.offset = *off;
747
748         max_key.objectid = ino;
749         max_key.type = (u8)-1;
750         max_key.offset = (u64)-1;
751
752         path->keep_locks = 1;
753
754         while(1) {
755                 ret = btrfs_search_forward(root, &min_key, &max_key,
756                                            path, 0, newer_than);
757                 if (ret != 0)
758                         goto none;
759                 if (min_key.objectid != ino)
760                         goto none;
761                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
762                         goto none;
763
764                 leaf = path->nodes[0];
765                 extent = btrfs_item_ptr(leaf, path->slots[0],
766                                         struct btrfs_file_extent_item);
767
768                 type = btrfs_file_extent_type(leaf, extent);
769                 if (type == BTRFS_FILE_EXTENT_REG &&
770                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
771                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
772                         *off = min_key.offset;
773                         btrfs_free_path(path);
774                         return 0;
775                 }
776
777                 if (min_key.offset == (u64)-1)
778                         goto none;
779
780                 min_key.offset++;
781                 btrfs_release_path(path);
782         }
783 none:
784         btrfs_free_path(path);
785         return -ENOENT;
786 }
787
788 /*
789  * Validaty check of prev em and next em:
790  * 1) no prev/next em
791  * 2) prev/next em is an hole/inline extent
792  */
793 static int check_adjacent_extents(struct inode *inode, struct extent_map *em)
794 {
795         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
796         struct extent_map *prev = NULL, *next = NULL;
797         int ret = 0;
798
799         read_lock(&em_tree->lock);
800         prev = lookup_extent_mapping(em_tree, em->start - 1, (u64)-1);
801         next = lookup_extent_mapping(em_tree, em->start + em->len, (u64)-1);
802         read_unlock(&em_tree->lock);
803
804         if ((!prev || prev->block_start >= EXTENT_MAP_LAST_BYTE) &&
805             (!next || next->block_start >= EXTENT_MAP_LAST_BYTE))
806                 ret = 1;
807         free_extent_map(prev);
808         free_extent_map(next);
809
810         return ret;
811 }
812
813 static int should_defrag_range(struct inode *inode, u64 start, u64 len,
814                                int thresh, u64 *last_len, u64 *skip,
815                                u64 *defrag_end)
816 {
817         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
818         struct extent_map *em = NULL;
819         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
820         int ret = 1;
821
822         /*
823          * make sure that once we start defragging an extent, we keep on
824          * defragging it
825          */
826         if (start < *defrag_end)
827                 return 1;
828
829         *skip = 0;
830
831         /*
832          * hopefully we have this extent in the tree already, try without
833          * the full extent lock
834          */
835         read_lock(&em_tree->lock);
836         em = lookup_extent_mapping(em_tree, start, len);
837         read_unlock(&em_tree->lock);
838
839         if (!em) {
840                 /* get the big lock and read metadata off disk */
841                 lock_extent(io_tree, start, start + len - 1);
842                 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
843                 unlock_extent(io_tree, start, start + len - 1);
844
845                 if (IS_ERR(em))
846                         return 0;
847         }
848
849         /* this will cover holes, and inline extents */
850         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
851                 ret = 0;
852                 goto out;
853         }
854
855         /* If we have nothing to merge with us, just skip. */
856         if (check_adjacent_extents(inode, em)) {
857                 ret = 0;
858                 goto out;
859         }
860
861         /*
862          * we hit a real extent, if it is big don't bother defragging it again
863          */
864         if ((*last_len == 0 || *last_len >= thresh) && em->len >= thresh)
865                 ret = 0;
866
867 out:
868         /*
869          * last_len ends up being a counter of how many bytes we've defragged.
870          * every time we choose not to defrag an extent, we reset *last_len
871          * so that the next tiny extent will force a defrag.
872          *
873          * The end result of this is that tiny extents before a single big
874          * extent will force at least part of that big extent to be defragged.
875          */
876         if (ret) {
877                 *defrag_end = extent_map_end(em);
878         } else {
879                 *last_len = 0;
880                 *skip = extent_map_end(em);
881                 *defrag_end = 0;
882         }
883
884         free_extent_map(em);
885         return ret;
886 }
887
888 /*
889  * it doesn't do much good to defrag one or two pages
890  * at a time.  This pulls in a nice chunk of pages
891  * to COW and defrag.
892  *
893  * It also makes sure the delalloc code has enough
894  * dirty data to avoid making new small extents as part
895  * of the defrag
896  *
897  * It's a good idea to start RA on this range
898  * before calling this.
899  */
900 static int cluster_pages_for_defrag(struct inode *inode,
901                                     struct page **pages,
902                                     unsigned long start_index,
903                                     int num_pages)
904 {
905         unsigned long file_end;
906         u64 isize = i_size_read(inode);
907         u64 page_start;
908         u64 page_end;
909         u64 page_cnt;
910         int ret;
911         int i;
912         int i_done;
913         struct btrfs_ordered_extent *ordered;
914         struct extent_state *cached_state = NULL;
915         struct extent_io_tree *tree;
916         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
917
918         file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
919         if (!isize || start_index > file_end)
920                 return 0;
921
922         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
923
924         ret = btrfs_delalloc_reserve_space(inode,
925                                            page_cnt << PAGE_CACHE_SHIFT);
926         if (ret)
927                 return ret;
928         i_done = 0;
929         tree = &BTRFS_I(inode)->io_tree;
930
931         /* step one, lock all the pages */
932         for (i = 0; i < page_cnt; i++) {
933                 struct page *page;
934 again:
935                 page = find_or_create_page(inode->i_mapping,
936                                            start_index + i, mask);
937                 if (!page)
938                         break;
939
940                 page_start = page_offset(page);
941                 page_end = page_start + PAGE_CACHE_SIZE - 1;
942                 while (1) {
943                         lock_extent(tree, page_start, page_end);
944                         ordered = btrfs_lookup_ordered_extent(inode,
945                                                               page_start);
946                         unlock_extent(tree, page_start, page_end);
947                         if (!ordered)
948                                 break;
949
950                         unlock_page(page);
951                         btrfs_start_ordered_extent(inode, ordered, 1);
952                         btrfs_put_ordered_extent(ordered);
953                         lock_page(page);
954                         /*
955                          * we unlocked the page above, so we need check if
956                          * it was released or not.
957                          */
958                         if (page->mapping != inode->i_mapping) {
959                                 unlock_page(page);
960                                 page_cache_release(page);
961                                 goto again;
962                         }
963                 }
964
965                 if (!PageUptodate(page)) {
966                         btrfs_readpage(NULL, page);
967                         lock_page(page);
968                         if (!PageUptodate(page)) {
969                                 unlock_page(page);
970                                 page_cache_release(page);
971                                 ret = -EIO;
972                                 break;
973                         }
974                 }
975
976                 if (page->mapping != inode->i_mapping) {
977                         unlock_page(page);
978                         page_cache_release(page);
979                         goto again;
980                 }
981
982                 pages[i] = page;
983                 i_done++;
984         }
985         if (!i_done || ret)
986                 goto out;
987
988         if (!(inode->i_sb->s_flags & MS_ACTIVE))
989                 goto out;
990
991         /*
992          * so now we have a nice long stream of locked
993          * and up to date pages, lets wait on them
994          */
995         for (i = 0; i < i_done; i++)
996                 wait_on_page_writeback(pages[i]);
997
998         page_start = page_offset(pages[0]);
999         page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1000
1001         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1002                          page_start, page_end - 1, 0, &cached_state);
1003         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1004                           page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1005                           EXTENT_DO_ACCOUNTING, 0, 0, &cached_state,
1006                           GFP_NOFS);
1007
1008         if (i_done != page_cnt) {
1009                 spin_lock(&BTRFS_I(inode)->lock);
1010                 BTRFS_I(inode)->outstanding_extents++;
1011                 spin_unlock(&BTRFS_I(inode)->lock);
1012                 btrfs_delalloc_release_space(inode,
1013                                      (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1014         }
1015
1016
1017         btrfs_set_extent_delalloc(inode, page_start, page_end - 1,
1018                                   &cached_state);
1019
1020         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1021                              page_start, page_end - 1, &cached_state,
1022                              GFP_NOFS);
1023
1024         for (i = 0; i < i_done; i++) {
1025                 clear_page_dirty_for_io(pages[i]);
1026                 ClearPageChecked(pages[i]);
1027                 set_page_extent_mapped(pages[i]);
1028                 set_page_dirty(pages[i]);
1029                 unlock_page(pages[i]);
1030                 page_cache_release(pages[i]);
1031         }
1032         return i_done;
1033 out:
1034         for (i = 0; i < i_done; i++) {
1035                 unlock_page(pages[i]);
1036                 page_cache_release(pages[i]);
1037         }
1038         btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1039         return ret;
1040
1041 }
1042
1043 int btrfs_defrag_file(struct inode *inode, struct file *file,
1044                       struct btrfs_ioctl_defrag_range_args *range,
1045                       u64 newer_than, unsigned long max_to_defrag)
1046 {
1047         struct btrfs_root *root = BTRFS_I(inode)->root;
1048         struct btrfs_super_block *disk_super;
1049         struct file_ra_state *ra = NULL;
1050         unsigned long last_index;
1051         u64 isize = i_size_read(inode);
1052         u64 features;
1053         u64 last_len = 0;
1054         u64 skip = 0;
1055         u64 defrag_end = 0;
1056         u64 newer_off = range->start;
1057         unsigned long i;
1058         unsigned long ra_index = 0;
1059         int ret;
1060         int defrag_count = 0;
1061         int compress_type = BTRFS_COMPRESS_ZLIB;
1062         int extent_thresh = range->extent_thresh;
1063         int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1064         int cluster = max_cluster;
1065         u64 new_align = ~((u64)128 * 1024 - 1);
1066         struct page **pages = NULL;
1067
1068         if (extent_thresh == 0)
1069                 extent_thresh = 256 * 1024;
1070
1071         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1072                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1073                         return -EINVAL;
1074                 if (range->compress_type)
1075                         compress_type = range->compress_type;
1076         }
1077
1078         if (isize == 0)
1079                 return 0;
1080
1081         /*
1082          * if we were not given a file, allocate a readahead
1083          * context
1084          */
1085         if (!file) {
1086                 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1087                 if (!ra)
1088                         return -ENOMEM;
1089                 file_ra_state_init(ra, inode->i_mapping);
1090         } else {
1091                 ra = &file->f_ra;
1092         }
1093
1094         pages = kmalloc(sizeof(struct page *) * max_cluster,
1095                         GFP_NOFS);
1096         if (!pages) {
1097                 ret = -ENOMEM;
1098                 goto out_ra;
1099         }
1100
1101         /* find the last page to defrag */
1102         if (range->start + range->len > range->start) {
1103                 last_index = min_t(u64, isize - 1,
1104                          range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1105         } else {
1106                 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1107         }
1108
1109         if (newer_than) {
1110                 ret = find_new_extents(root, inode, newer_than,
1111                                        &newer_off, 64 * 1024);
1112                 if (!ret) {
1113                         range->start = newer_off;
1114                         /*
1115                          * we always align our defrag to help keep
1116                          * the extents in the file evenly spaced
1117                          */
1118                         i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1119                 } else
1120                         goto out_ra;
1121         } else {
1122                 i = range->start >> PAGE_CACHE_SHIFT;
1123         }
1124         if (!max_to_defrag)
1125                 max_to_defrag = last_index + 1;
1126
1127         /*
1128          * make writeback starts from i, so the defrag range can be
1129          * written sequentially.
1130          */
1131         if (i < inode->i_mapping->writeback_index)
1132                 inode->i_mapping->writeback_index = i;
1133
1134         while (i <= last_index && defrag_count < max_to_defrag &&
1135                (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
1136                 PAGE_CACHE_SHIFT)) {
1137                 /*
1138                  * make sure we stop running if someone unmounts
1139                  * the FS
1140                  */
1141                 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1142                         break;
1143
1144                 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1145                                          PAGE_CACHE_SIZE, extent_thresh,
1146                                          &last_len, &skip, &defrag_end)) {
1147                         unsigned long next;
1148                         /*
1149                          * the should_defrag function tells us how much to skip
1150                          * bump our counter by the suggested amount
1151                          */
1152                         next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1153                         i = max(i + 1, next);
1154                         continue;
1155                 }
1156
1157                 if (!newer_than) {
1158                         cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1159                                    PAGE_CACHE_SHIFT) - i;
1160                         cluster = min(cluster, max_cluster);
1161                 } else {
1162                         cluster = max_cluster;
1163                 }
1164
1165                 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1166                         BTRFS_I(inode)->force_compress = compress_type;
1167
1168                 if (i + cluster > ra_index) {
1169                         ra_index = max(i, ra_index);
1170                         btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1171                                        cluster);
1172                         ra_index += max_cluster;
1173                 }
1174
1175                 mutex_lock(&inode->i_mutex);
1176                 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1177                 if (ret < 0) {
1178                         mutex_unlock(&inode->i_mutex);
1179                         goto out_ra;
1180                 }
1181
1182                 defrag_count += ret;
1183                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, ret);
1184                 mutex_unlock(&inode->i_mutex);
1185
1186                 if (newer_than) {
1187                         if (newer_off == (u64)-1)
1188                                 break;
1189
1190                         if (ret > 0)
1191                                 i += ret;
1192
1193                         newer_off = max(newer_off + 1,
1194                                         (u64)i << PAGE_CACHE_SHIFT);
1195
1196                         ret = find_new_extents(root, inode,
1197                                                newer_than, &newer_off,
1198                                                64 * 1024);
1199                         if (!ret) {
1200                                 range->start = newer_off;
1201                                 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1202                         } else {
1203                                 break;
1204                         }
1205                 } else {
1206                         if (ret > 0) {
1207                                 i += ret;
1208                                 last_len += ret << PAGE_CACHE_SHIFT;
1209                         } else {
1210                                 i++;
1211                                 last_len = 0;
1212                         }
1213                 }
1214         }
1215
1216         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
1217                 filemap_flush(inode->i_mapping);
1218
1219         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1220                 /* the filemap_flush will queue IO into the worker threads, but
1221                  * we have to make sure the IO is actually started and that
1222                  * ordered extents get created before we return
1223                  */
1224                 atomic_inc(&root->fs_info->async_submit_draining);
1225                 while (atomic_read(&root->fs_info->nr_async_submits) ||
1226                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1227                         wait_event(root->fs_info->async_submit_wait,
1228                            (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1229                             atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1230                 }
1231                 atomic_dec(&root->fs_info->async_submit_draining);
1232
1233                 mutex_lock(&inode->i_mutex);
1234                 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1235                 mutex_unlock(&inode->i_mutex);
1236         }
1237
1238         disk_super = root->fs_info->super_copy;
1239         features = btrfs_super_incompat_flags(disk_super);
1240         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1241                 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
1242                 btrfs_set_super_incompat_flags(disk_super, features);
1243         }
1244
1245         ret = defrag_count;
1246
1247 out_ra:
1248         if (!file)
1249                 kfree(ra);
1250         kfree(pages);
1251         return ret;
1252 }
1253
1254 static noinline int btrfs_ioctl_resize(struct btrfs_root *root,
1255                                         void __user *arg)
1256 {
1257         u64 new_size;
1258         u64 old_size;
1259         u64 devid = 1;
1260         struct btrfs_ioctl_vol_args *vol_args;
1261         struct btrfs_trans_handle *trans;
1262         struct btrfs_device *device = NULL;
1263         char *sizestr;
1264         char *devstr = NULL;
1265         int ret = 0;
1266         int mod = 0;
1267
1268         if (root->fs_info->sb->s_flags & MS_RDONLY)
1269                 return -EROFS;
1270
1271         if (!capable(CAP_SYS_ADMIN))
1272                 return -EPERM;
1273
1274         mutex_lock(&root->fs_info->volume_mutex);
1275         if (root->fs_info->balance_ctl) {
1276                 printk(KERN_INFO "btrfs: balance in progress\n");
1277                 ret = -EINVAL;
1278                 goto out;
1279         }
1280
1281         vol_args = memdup_user(arg, sizeof(*vol_args));
1282         if (IS_ERR(vol_args)) {
1283                 ret = PTR_ERR(vol_args);
1284                 goto out;
1285         }
1286
1287         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1288
1289         sizestr = vol_args->name;
1290         devstr = strchr(sizestr, ':');
1291         if (devstr) {
1292                 char *end;
1293                 sizestr = devstr + 1;
1294                 *devstr = '\0';
1295                 devstr = vol_args->name;
1296                 devid = simple_strtoull(devstr, &end, 10);
1297                 printk(KERN_INFO "btrfs: resizing devid %llu\n",
1298                        (unsigned long long)devid);
1299         }
1300         device = btrfs_find_device(root, devid, NULL, NULL);
1301         if (!device) {
1302                 printk(KERN_INFO "btrfs: resizer unable to find device %llu\n",
1303                        (unsigned long long)devid);
1304                 ret = -EINVAL;
1305                 goto out_free;
1306         }
1307         if (!strcmp(sizestr, "max"))
1308                 new_size = device->bdev->bd_inode->i_size;
1309         else {
1310                 if (sizestr[0] == '-') {
1311                         mod = -1;
1312                         sizestr++;
1313                 } else if (sizestr[0] == '+') {
1314                         mod = 1;
1315                         sizestr++;
1316                 }
1317                 new_size = memparse(sizestr, NULL);
1318                 if (new_size == 0) {
1319                         ret = -EINVAL;
1320                         goto out_free;
1321                 }
1322         }
1323
1324         old_size = device->total_bytes;
1325
1326         if (mod < 0) {
1327                 if (new_size > old_size) {
1328                         ret = -EINVAL;
1329                         goto out_free;
1330                 }
1331                 new_size = old_size - new_size;
1332         } else if (mod > 0) {
1333                 new_size = old_size + new_size;
1334         }
1335
1336         if (new_size < 256 * 1024 * 1024) {
1337                 ret = -EINVAL;
1338                 goto out_free;
1339         }
1340         if (new_size > device->bdev->bd_inode->i_size) {
1341                 ret = -EFBIG;
1342                 goto out_free;
1343         }
1344
1345         do_div(new_size, root->sectorsize);
1346         new_size *= root->sectorsize;
1347
1348         printk(KERN_INFO "btrfs: new size for %s is %llu\n",
1349                 device->name, (unsigned long long)new_size);
1350
1351         if (new_size > old_size) {
1352                 trans = btrfs_start_transaction(root, 0);
1353                 if (IS_ERR(trans)) {
1354                         ret = PTR_ERR(trans);
1355                         goto out_free;
1356                 }
1357                 ret = btrfs_grow_device(trans, device, new_size);
1358                 btrfs_commit_transaction(trans, root);
1359         } else if (new_size < old_size) {
1360                 ret = btrfs_shrink_device(device, new_size);
1361         }
1362
1363 out_free:
1364         kfree(vol_args);
1365 out:
1366         mutex_unlock(&root->fs_info->volume_mutex);
1367         return ret;
1368 }
1369
1370 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1371                                                     char *name,
1372                                                     unsigned long fd,
1373                                                     int subvol,
1374                                                     u64 *transid,
1375                                                     bool readonly)
1376 {
1377         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
1378         struct file *src_file;
1379         int namelen;
1380         int ret = 0;
1381
1382         if (root->fs_info->sb->s_flags & MS_RDONLY)
1383                 return -EROFS;
1384
1385         namelen = strlen(name);
1386         if (strchr(name, '/')) {
1387                 ret = -EINVAL;
1388                 goto out;
1389         }
1390
1391         if (name[0] == '.' &&
1392            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1393                 ret = -EEXIST;
1394                 goto out;
1395         }
1396
1397         if (subvol) {
1398                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1399                                      NULL, transid, readonly);
1400         } else {
1401                 struct inode *src_inode;
1402                 src_file = fget(fd);
1403                 if (!src_file) {
1404                         ret = -EINVAL;
1405                         goto out;
1406                 }
1407
1408                 src_inode = src_file->f_path.dentry->d_inode;
1409                 if (src_inode->i_sb != file->f_path.dentry->d_inode->i_sb) {
1410                         printk(KERN_INFO "btrfs: Snapshot src from "
1411                                "another FS\n");
1412                         ret = -EINVAL;
1413                         fput(src_file);
1414                         goto out;
1415                 }
1416                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1417                                      BTRFS_I(src_inode)->root,
1418                                      transid, readonly);
1419                 fput(src_file);
1420         }
1421 out:
1422         return ret;
1423 }
1424
1425 static noinline int btrfs_ioctl_snap_create(struct file *file,
1426                                             void __user *arg, int subvol)
1427 {
1428         struct btrfs_ioctl_vol_args *vol_args;
1429         int ret;
1430
1431         vol_args = memdup_user(arg, sizeof(*vol_args));
1432         if (IS_ERR(vol_args))
1433                 return PTR_ERR(vol_args);
1434         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1435
1436         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1437                                               vol_args->fd, subvol,
1438                                               NULL, false);
1439
1440         kfree(vol_args);
1441         return ret;
1442 }
1443
1444 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1445                                                void __user *arg, int subvol)
1446 {
1447         struct btrfs_ioctl_vol_args_v2 *vol_args;
1448         int ret;
1449         u64 transid = 0;
1450         u64 *ptr = NULL;
1451         bool readonly = false;
1452
1453         vol_args = memdup_user(arg, sizeof(*vol_args));
1454         if (IS_ERR(vol_args))
1455                 return PTR_ERR(vol_args);
1456         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1457
1458         if (vol_args->flags &
1459             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY)) {
1460                 ret = -EOPNOTSUPP;
1461                 goto out;
1462         }
1463
1464         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1465                 ptr = &transid;
1466         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1467                 readonly = true;
1468
1469         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1470                                               vol_args->fd, subvol,
1471                                               ptr, readonly);
1472
1473         if (ret == 0 && ptr &&
1474             copy_to_user(arg +
1475                          offsetof(struct btrfs_ioctl_vol_args_v2,
1476                                   transid), ptr, sizeof(*ptr)))
1477                 ret = -EFAULT;
1478 out:
1479         kfree(vol_args);
1480         return ret;
1481 }
1482
1483 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1484                                                 void __user *arg)
1485 {
1486         struct inode *inode = fdentry(file)->d_inode;
1487         struct btrfs_root *root = BTRFS_I(inode)->root;
1488         int ret = 0;
1489         u64 flags = 0;
1490
1491         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1492                 return -EINVAL;
1493
1494         down_read(&root->fs_info->subvol_sem);
1495         if (btrfs_root_readonly(root))
1496                 flags |= BTRFS_SUBVOL_RDONLY;
1497         up_read(&root->fs_info->subvol_sem);
1498
1499         if (copy_to_user(arg, &flags, sizeof(flags)))
1500                 ret = -EFAULT;
1501
1502         return ret;
1503 }
1504
1505 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1506                                               void __user *arg)
1507 {
1508         struct inode *inode = fdentry(file)->d_inode;
1509         struct btrfs_root *root = BTRFS_I(inode)->root;
1510         struct btrfs_trans_handle *trans;
1511         u64 root_flags;
1512         u64 flags;
1513         int ret = 0;
1514
1515         if (root->fs_info->sb->s_flags & MS_RDONLY)
1516                 return -EROFS;
1517
1518         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1519                 return -EINVAL;
1520
1521         if (copy_from_user(&flags, arg, sizeof(flags)))
1522                 return -EFAULT;
1523
1524         if (flags & BTRFS_SUBVOL_CREATE_ASYNC)
1525                 return -EINVAL;
1526
1527         if (flags & ~BTRFS_SUBVOL_RDONLY)
1528                 return -EOPNOTSUPP;
1529
1530         if (!inode_owner_or_capable(inode))
1531                 return -EACCES;
1532
1533         down_write(&root->fs_info->subvol_sem);
1534
1535         /* nothing to do */
1536         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1537                 goto out;
1538
1539         root_flags = btrfs_root_flags(&root->root_item);
1540         if (flags & BTRFS_SUBVOL_RDONLY)
1541                 btrfs_set_root_flags(&root->root_item,
1542                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1543         else
1544                 btrfs_set_root_flags(&root->root_item,
1545                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1546
1547         trans = btrfs_start_transaction(root, 1);
1548         if (IS_ERR(trans)) {
1549                 ret = PTR_ERR(trans);
1550                 goto out_reset;
1551         }
1552
1553         ret = btrfs_update_root(trans, root->fs_info->tree_root,
1554                                 &root->root_key, &root->root_item);
1555
1556         btrfs_commit_transaction(trans, root);
1557 out_reset:
1558         if (ret)
1559                 btrfs_set_root_flags(&root->root_item, root_flags);
1560 out:
1561         up_write(&root->fs_info->subvol_sem);
1562         return ret;
1563 }
1564
1565 /*
1566  * helper to check if the subvolume references other subvolumes
1567  */
1568 static noinline int may_destroy_subvol(struct btrfs_root *root)
1569 {
1570         struct btrfs_path *path;
1571         struct btrfs_key key;
1572         int ret;
1573
1574         path = btrfs_alloc_path();
1575         if (!path)
1576                 return -ENOMEM;
1577
1578         key.objectid = root->root_key.objectid;
1579         key.type = BTRFS_ROOT_REF_KEY;
1580         key.offset = (u64)-1;
1581
1582         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1583                                 &key, path, 0, 0);
1584         if (ret < 0)
1585                 goto out;
1586         BUG_ON(ret == 0);
1587
1588         ret = 0;
1589         if (path->slots[0] > 0) {
1590                 path->slots[0]--;
1591                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1592                 if (key.objectid == root->root_key.objectid &&
1593                     key.type == BTRFS_ROOT_REF_KEY)
1594                         ret = -ENOTEMPTY;
1595         }
1596 out:
1597         btrfs_free_path(path);
1598         return ret;
1599 }
1600
1601 static noinline int key_in_sk(struct btrfs_key *key,
1602                               struct btrfs_ioctl_search_key *sk)
1603 {
1604         struct btrfs_key test;
1605         int ret;
1606
1607         test.objectid = sk->min_objectid;
1608         test.type = sk->min_type;
1609         test.offset = sk->min_offset;
1610
1611         ret = btrfs_comp_cpu_keys(key, &test);
1612         if (ret < 0)
1613                 return 0;
1614
1615         test.objectid = sk->max_objectid;
1616         test.type = sk->max_type;
1617         test.offset = sk->max_offset;
1618
1619         ret = btrfs_comp_cpu_keys(key, &test);
1620         if (ret > 0)
1621                 return 0;
1622         return 1;
1623 }
1624
1625 static noinline int copy_to_sk(struct btrfs_root *root,
1626                                struct btrfs_path *path,
1627                                struct btrfs_key *key,
1628                                struct btrfs_ioctl_search_key *sk,
1629                                char *buf,
1630                                unsigned long *sk_offset,
1631                                int *num_found)
1632 {
1633         u64 found_transid;
1634         struct extent_buffer *leaf;
1635         struct btrfs_ioctl_search_header sh;
1636         unsigned long item_off;
1637         unsigned long item_len;
1638         int nritems;
1639         int i;
1640         int slot;
1641         int ret = 0;
1642
1643         leaf = path->nodes[0];
1644         slot = path->slots[0];
1645         nritems = btrfs_header_nritems(leaf);
1646
1647         if (btrfs_header_generation(leaf) > sk->max_transid) {
1648                 i = nritems;
1649                 goto advance_key;
1650         }
1651         found_transid = btrfs_header_generation(leaf);
1652
1653         for (i = slot; i < nritems; i++) {
1654                 item_off = btrfs_item_ptr_offset(leaf, i);
1655                 item_len = btrfs_item_size_nr(leaf, i);
1656
1657                 if (item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
1658                         item_len = 0;
1659
1660                 if (sizeof(sh) + item_len + *sk_offset >
1661                     BTRFS_SEARCH_ARGS_BUFSIZE) {
1662                         ret = 1;
1663                         goto overflow;
1664                 }
1665
1666                 btrfs_item_key_to_cpu(leaf, key, i);
1667                 if (!key_in_sk(key, sk))
1668                         continue;
1669
1670                 sh.objectid = key->objectid;
1671                 sh.offset = key->offset;
1672                 sh.type = key->type;
1673                 sh.len = item_len;
1674                 sh.transid = found_transid;
1675
1676                 /* copy search result header */
1677                 memcpy(buf + *sk_offset, &sh, sizeof(sh));
1678                 *sk_offset += sizeof(sh);
1679
1680                 if (item_len) {
1681                         char *p = buf + *sk_offset;
1682                         /* copy the item */
1683                         read_extent_buffer(leaf, p,
1684                                            item_off, item_len);
1685                         *sk_offset += item_len;
1686                 }
1687                 (*num_found)++;
1688
1689                 if (*num_found >= sk->nr_items)
1690                         break;
1691         }
1692 advance_key:
1693         ret = 0;
1694         if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1695                 key->offset++;
1696         else if (key->type < (u8)-1 && key->type < sk->max_type) {
1697                 key->offset = 0;
1698                 key->type++;
1699         } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1700                 key->offset = 0;
1701                 key->type = 0;
1702                 key->objectid++;
1703         } else
1704                 ret = 1;
1705 overflow:
1706         return ret;
1707 }
1708
1709 static noinline int search_ioctl(struct inode *inode,
1710                                  struct btrfs_ioctl_search_args *args)
1711 {
1712         struct btrfs_root *root;
1713         struct btrfs_key key;
1714         struct btrfs_key max_key;
1715         struct btrfs_path *path;
1716         struct btrfs_ioctl_search_key *sk = &args->key;
1717         struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1718         int ret;
1719         int num_found = 0;
1720         unsigned long sk_offset = 0;
1721
1722         path = btrfs_alloc_path();
1723         if (!path)
1724                 return -ENOMEM;
1725
1726         if (sk->tree_id == 0) {
1727                 /* search the root of the inode that was passed */
1728                 root = BTRFS_I(inode)->root;
1729         } else {
1730                 key.objectid = sk->tree_id;
1731                 key.type = BTRFS_ROOT_ITEM_KEY;
1732                 key.offset = (u64)-1;
1733                 root = btrfs_read_fs_root_no_name(info, &key);
1734                 if (IS_ERR(root)) {
1735                         printk(KERN_ERR "could not find root %llu\n",
1736                                sk->tree_id);
1737                         btrfs_free_path(path);
1738                         return -ENOENT;
1739                 }
1740         }
1741
1742         key.objectid = sk->min_objectid;
1743         key.type = sk->min_type;
1744         key.offset = sk->min_offset;
1745
1746         max_key.objectid = sk->max_objectid;
1747         max_key.type = sk->max_type;
1748         max_key.offset = sk->max_offset;
1749
1750         path->keep_locks = 1;
1751
1752         while(1) {
1753                 ret = btrfs_search_forward(root, &key, &max_key, path, 0,
1754                                            sk->min_transid);
1755                 if (ret != 0) {
1756                         if (ret > 0)
1757                                 ret = 0;
1758                         goto err;
1759                 }
1760                 ret = copy_to_sk(root, path, &key, sk, args->buf,
1761                                  &sk_offset, &num_found);
1762                 btrfs_release_path(path);
1763                 if (ret || num_found >= sk->nr_items)
1764                         break;
1765
1766         }
1767         ret = 0;
1768 err:
1769         sk->nr_items = num_found;
1770         btrfs_free_path(path);
1771         return ret;
1772 }
1773
1774 static noinline int btrfs_ioctl_tree_search(struct file *file,
1775                                            void __user *argp)
1776 {
1777          struct btrfs_ioctl_search_args *args;
1778          struct inode *inode;
1779          int ret;
1780
1781         if (!capable(CAP_SYS_ADMIN))
1782                 return -EPERM;
1783
1784         args = memdup_user(argp, sizeof(*args));
1785         if (IS_ERR(args))
1786                 return PTR_ERR(args);
1787
1788         inode = fdentry(file)->d_inode;
1789         ret = search_ioctl(inode, args);
1790         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1791                 ret = -EFAULT;
1792         kfree(args);
1793         return ret;
1794 }
1795
1796 /*
1797  * Search INODE_REFs to identify path name of 'dirid' directory
1798  * in a 'tree_id' tree. and sets path name to 'name'.
1799  */
1800 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
1801                                 u64 tree_id, u64 dirid, char *name)
1802 {
1803         struct btrfs_root *root;
1804         struct btrfs_key key;
1805         char *ptr;
1806         int ret = -1;
1807         int slot;
1808         int len;
1809         int total_len = 0;
1810         struct btrfs_inode_ref *iref;
1811         struct extent_buffer *l;
1812         struct btrfs_path *path;
1813
1814         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
1815                 name[0]='\0';
1816                 return 0;
1817         }
1818
1819         path = btrfs_alloc_path();
1820         if (!path)
1821                 return -ENOMEM;
1822
1823         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
1824
1825         key.objectid = tree_id;
1826         key.type = BTRFS_ROOT_ITEM_KEY;
1827         key.offset = (u64)-1;
1828         root = btrfs_read_fs_root_no_name(info, &key);
1829         if (IS_ERR(root)) {
1830                 printk(KERN_ERR "could not find root %llu\n", tree_id);
1831                 ret = -ENOENT;
1832                 goto out;
1833         }
1834
1835         key.objectid = dirid;
1836         key.type = BTRFS_INODE_REF_KEY;
1837         key.offset = (u64)-1;
1838
1839         while(1) {
1840                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1841                 if (ret < 0)
1842                         goto out;
1843
1844                 l = path->nodes[0];
1845                 slot = path->slots[0];
1846                 if (ret > 0 && slot > 0)
1847                         slot--;
1848                 btrfs_item_key_to_cpu(l, &key, slot);
1849
1850                 if (ret > 0 && (key.objectid != dirid ||
1851                                 key.type != BTRFS_INODE_REF_KEY)) {
1852                         ret = -ENOENT;
1853                         goto out;
1854                 }
1855
1856                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
1857                 len = btrfs_inode_ref_name_len(l, iref);
1858                 ptr -= len + 1;
1859                 total_len += len + 1;
1860                 if (ptr < name)
1861                         goto out;
1862
1863                 *(ptr + len) = '/';
1864                 read_extent_buffer(l, ptr,(unsigned long)(iref + 1), len);
1865
1866                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
1867                         break;
1868
1869                 btrfs_release_path(path);
1870                 key.objectid = key.offset;
1871                 key.offset = (u64)-1;
1872                 dirid = key.objectid;
1873         }
1874         if (ptr < name)
1875                 goto out;
1876         memmove(name, ptr, total_len);
1877         name[total_len]='\0';
1878         ret = 0;
1879 out:
1880         btrfs_free_path(path);
1881         return ret;
1882 }
1883
1884 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
1885                                            void __user *argp)
1886 {
1887          struct btrfs_ioctl_ino_lookup_args *args;
1888          struct inode *inode;
1889          int ret;
1890
1891         if (!capable(CAP_SYS_ADMIN))
1892                 return -EPERM;
1893
1894         args = memdup_user(argp, sizeof(*args));
1895         if (IS_ERR(args))
1896                 return PTR_ERR(args);
1897
1898         inode = fdentry(file)->d_inode;
1899
1900         if (args->treeid == 0)
1901                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
1902
1903         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
1904                                         args->treeid, args->objectid,
1905                                         args->name);
1906
1907         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1908                 ret = -EFAULT;
1909
1910         kfree(args);
1911         return ret;
1912 }
1913
1914 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
1915                                              void __user *arg)
1916 {
1917         struct dentry *parent = fdentry(file);
1918         struct dentry *dentry;
1919         struct inode *dir = parent->d_inode;
1920         struct inode *inode;
1921         struct btrfs_root *root = BTRFS_I(dir)->root;
1922         struct btrfs_root *dest = NULL;
1923         struct btrfs_ioctl_vol_args *vol_args;
1924         struct btrfs_trans_handle *trans;
1925         int namelen;
1926         int ret;
1927         int err = 0;
1928
1929         vol_args = memdup_user(arg, sizeof(*vol_args));
1930         if (IS_ERR(vol_args))
1931                 return PTR_ERR(vol_args);
1932
1933         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1934         namelen = strlen(vol_args->name);
1935         if (strchr(vol_args->name, '/') ||
1936             strncmp(vol_args->name, "..", namelen) == 0) {
1937                 err = -EINVAL;
1938                 goto out;
1939         }
1940
1941         err = mnt_want_write_file(file);
1942         if (err)
1943                 goto out;
1944
1945         mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
1946         dentry = lookup_one_len(vol_args->name, parent, namelen);
1947         if (IS_ERR(dentry)) {
1948                 err = PTR_ERR(dentry);
1949                 goto out_unlock_dir;
1950         }
1951
1952         if (!dentry->d_inode) {
1953                 err = -ENOENT;
1954                 goto out_dput;
1955         }
1956
1957         inode = dentry->d_inode;
1958         dest = BTRFS_I(inode)->root;
1959         if (!capable(CAP_SYS_ADMIN)){
1960                 /*
1961                  * Regular user.  Only allow this with a special mount
1962                  * option, when the user has write+exec access to the
1963                  * subvol root, and when rmdir(2) would have been
1964                  * allowed.
1965                  *
1966                  * Note that this is _not_ check that the subvol is
1967                  * empty or doesn't contain data that we wouldn't
1968                  * otherwise be able to delete.
1969                  *
1970                  * Users who want to delete empty subvols should try
1971                  * rmdir(2).
1972                  */
1973                 err = -EPERM;
1974                 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
1975                         goto out_dput;
1976
1977                 /*
1978                  * Do not allow deletion if the parent dir is the same
1979                  * as the dir to be deleted.  That means the ioctl
1980                  * must be called on the dentry referencing the root
1981                  * of the subvol, not a random directory contained
1982                  * within it.
1983                  */
1984                 err = -EINVAL;
1985                 if (root == dest)
1986                         goto out_dput;
1987
1988                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
1989                 if (err)
1990                         goto out_dput;
1991
1992                 /* check if subvolume may be deleted by a non-root user */
1993                 err = btrfs_may_delete(dir, dentry, 1);
1994                 if (err)
1995                         goto out_dput;
1996         }
1997
1998         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1999                 err = -EINVAL;
2000                 goto out_dput;
2001         }
2002
2003         mutex_lock(&inode->i_mutex);
2004         err = d_invalidate(dentry);
2005         if (err)
2006                 goto out_unlock;
2007
2008         down_write(&root->fs_info->subvol_sem);
2009
2010         err = may_destroy_subvol(dest);
2011         if (err)
2012                 goto out_up_write;
2013
2014         trans = btrfs_start_transaction(root, 0);
2015         if (IS_ERR(trans)) {
2016                 err = PTR_ERR(trans);
2017                 goto out_up_write;
2018         }
2019         trans->block_rsv = &root->fs_info->global_block_rsv;
2020
2021         ret = btrfs_unlink_subvol(trans, root, dir,
2022                                 dest->root_key.objectid,
2023                                 dentry->d_name.name,
2024                                 dentry->d_name.len);
2025         if (ret) {
2026                 err = ret;
2027                 btrfs_abort_transaction(trans, root, ret);
2028                 goto out_end_trans;
2029         }
2030
2031         btrfs_record_root_in_trans(trans, dest);
2032
2033         memset(&dest->root_item.drop_progress, 0,
2034                 sizeof(dest->root_item.drop_progress));
2035         dest->root_item.drop_level = 0;
2036         btrfs_set_root_refs(&dest->root_item, 0);
2037
2038         if (!xchg(&dest->orphan_item_inserted, 1)) {
2039                 ret = btrfs_insert_orphan_item(trans,
2040                                         root->fs_info->tree_root,
2041                                         dest->root_key.objectid);
2042                 if (ret) {
2043                         btrfs_abort_transaction(trans, root, ret);
2044                         err = ret;
2045                         goto out_end_trans;
2046                 }
2047         }
2048 out_end_trans:
2049         ret = btrfs_end_transaction(trans, root);
2050         if (ret && !err)
2051                 err = ret;
2052         inode->i_flags |= S_DEAD;
2053 out_up_write:
2054         up_write(&root->fs_info->subvol_sem);
2055 out_unlock:
2056         mutex_unlock(&inode->i_mutex);
2057         if (!err) {
2058                 shrink_dcache_sb(root->fs_info->sb);
2059                 btrfs_invalidate_inodes(dest);
2060                 d_delete(dentry);
2061         }
2062 out_dput:
2063         dput(dentry);
2064 out_unlock_dir:
2065         mutex_unlock(&dir->i_mutex);
2066         mnt_drop_write_file(file);
2067 out:
2068         kfree(vol_args);
2069         return err;
2070 }
2071
2072 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2073 {
2074         struct inode *inode = fdentry(file)->d_inode;
2075         struct btrfs_root *root = BTRFS_I(inode)->root;
2076         struct btrfs_ioctl_defrag_range_args *range;
2077         int ret;
2078
2079         if (btrfs_root_readonly(root))
2080                 return -EROFS;
2081
2082         ret = mnt_want_write_file(file);
2083         if (ret)
2084                 return ret;
2085
2086         switch (inode->i_mode & S_IFMT) {
2087         case S_IFDIR:
2088                 if (!capable(CAP_SYS_ADMIN)) {
2089                         ret = -EPERM;
2090                         goto out;
2091                 }
2092                 ret = btrfs_defrag_root(root, 0);
2093                 if (ret)
2094                         goto out;
2095                 ret = btrfs_defrag_root(root->fs_info->extent_root, 0);
2096                 break;
2097         case S_IFREG:
2098                 if (!(file->f_mode & FMODE_WRITE)) {
2099                         ret = -EINVAL;
2100                         goto out;
2101                 }
2102
2103                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2104                 if (!range) {
2105                         ret = -ENOMEM;
2106                         goto out;
2107                 }
2108
2109                 if (argp) {
2110                         if (copy_from_user(range, argp,
2111                                            sizeof(*range))) {
2112                                 ret = -EFAULT;
2113                                 kfree(range);
2114                                 goto out;
2115                         }
2116                         /* compression requires us to start the IO */
2117                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2118                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2119                                 range->extent_thresh = (u32)-1;
2120                         }
2121                 } else {
2122                         /* the rest are all set to zero by kzalloc */
2123                         range->len = (u64)-1;
2124                 }
2125                 ret = btrfs_defrag_file(fdentry(file)->d_inode, file,
2126                                         range, 0, 0);
2127                 if (ret > 0)
2128                         ret = 0;
2129                 kfree(range);
2130                 break;
2131         default:
2132                 ret = -EINVAL;
2133         }
2134 out:
2135         mnt_drop_write_file(file);
2136         return ret;
2137 }
2138
2139 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2140 {
2141         struct btrfs_ioctl_vol_args *vol_args;
2142         int ret;
2143
2144         if (!capable(CAP_SYS_ADMIN))
2145                 return -EPERM;
2146
2147         mutex_lock(&root->fs_info->volume_mutex);
2148         if (root->fs_info->balance_ctl) {
2149                 printk(KERN_INFO "btrfs: balance in progress\n");
2150                 ret = -EINVAL;
2151                 goto out;
2152         }
2153
2154         vol_args = memdup_user(arg, sizeof(*vol_args));
2155         if (IS_ERR(vol_args)) {
2156                 ret = PTR_ERR(vol_args);
2157                 goto out;
2158         }
2159
2160         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2161         ret = btrfs_init_new_device(root, vol_args->name);
2162
2163         kfree(vol_args);
2164 out:
2165         mutex_unlock(&root->fs_info->volume_mutex);
2166         return ret;
2167 }
2168
2169 static long btrfs_ioctl_rm_dev(struct btrfs_root *root, void __user *arg)
2170 {
2171         struct btrfs_ioctl_vol_args *vol_args;
2172         int ret;
2173
2174         if (!capable(CAP_SYS_ADMIN))
2175                 return -EPERM;
2176
2177         if (root->fs_info->sb->s_flags & MS_RDONLY)
2178                 return -EROFS;
2179
2180         mutex_lock(&root->fs_info->volume_mutex);
2181         if (root->fs_info->balance_ctl) {
2182                 printk(KERN_INFO "btrfs: balance in progress\n");
2183                 ret = -EINVAL;
2184                 goto out;
2185         }
2186
2187         vol_args = memdup_user(arg, sizeof(*vol_args));
2188         if (IS_ERR(vol_args)) {
2189                 ret = PTR_ERR(vol_args);
2190                 goto out;
2191         }
2192
2193         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2194         ret = btrfs_rm_device(root, vol_args->name);
2195
2196         kfree(vol_args);
2197 out:
2198         mutex_unlock(&root->fs_info->volume_mutex);
2199         return ret;
2200 }
2201
2202 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2203 {
2204         struct btrfs_ioctl_fs_info_args *fi_args;
2205         struct btrfs_device *device;
2206         struct btrfs_device *next;
2207         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2208         int ret = 0;
2209
2210         if (!capable(CAP_SYS_ADMIN))
2211                 return -EPERM;
2212
2213         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2214         if (!fi_args)
2215                 return -ENOMEM;
2216
2217         fi_args->num_devices = fs_devices->num_devices;
2218         memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2219
2220         mutex_lock(&fs_devices->device_list_mutex);
2221         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2222                 if (device->devid > fi_args->max_id)
2223                         fi_args->max_id = device->devid;
2224         }
2225         mutex_unlock(&fs_devices->device_list_mutex);
2226
2227         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2228                 ret = -EFAULT;
2229
2230         kfree(fi_args);
2231         return ret;
2232 }
2233
2234 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2235 {
2236         struct btrfs_ioctl_dev_info_args *di_args;
2237         struct btrfs_device *dev;
2238         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2239         int ret = 0;
2240         char *s_uuid = NULL;
2241         char empty_uuid[BTRFS_UUID_SIZE] = {0};
2242
2243         if (!capable(CAP_SYS_ADMIN))
2244                 return -EPERM;
2245
2246         di_args = memdup_user(arg, sizeof(*di_args));
2247         if (IS_ERR(di_args))
2248                 return PTR_ERR(di_args);
2249
2250         if (memcmp(empty_uuid, di_args->uuid, BTRFS_UUID_SIZE) != 0)
2251                 s_uuid = di_args->uuid;
2252
2253         mutex_lock(&fs_devices->device_list_mutex);
2254         dev = btrfs_find_device(root, di_args->devid, s_uuid, NULL);
2255         mutex_unlock(&fs_devices->device_list_mutex);
2256
2257         if (!dev) {
2258                 ret = -ENODEV;
2259                 goto out;
2260         }
2261
2262         di_args->devid = dev->devid;
2263         di_args->bytes_used = dev->bytes_used;
2264         di_args->total_bytes = dev->total_bytes;
2265         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2266         if (dev->name) {
2267                 strncpy(di_args->path, dev->name, sizeof(di_args->path));
2268                 di_args->path[sizeof(di_args->path) - 1] = 0;
2269         } else {
2270                 di_args->path[0] = '\0';
2271         }
2272
2273 out:
2274         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2275                 ret = -EFAULT;
2276
2277         kfree(di_args);
2278         return ret;
2279 }
2280
2281 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
2282                                        u64 off, u64 olen, u64 destoff)
2283 {
2284         struct inode *inode = fdentry(file)->d_inode;
2285         struct btrfs_root *root = BTRFS_I(inode)->root;
2286         struct file *src_file;
2287         struct inode *src;
2288         struct btrfs_trans_handle *trans;
2289         struct btrfs_path *path;
2290         struct extent_buffer *leaf;
2291         char *buf;
2292         struct btrfs_key key;
2293         u32 nritems;
2294         int slot;
2295         int ret;
2296         u64 len = olen;
2297         u64 bs = root->fs_info->sb->s_blocksize;
2298         u64 hint_byte;
2299
2300         /*
2301          * TODO:
2302          * - split compressed inline extents.  annoying: we need to
2303          *   decompress into destination's address_space (the file offset
2304          *   may change, so source mapping won't do), then recompress (or
2305          *   otherwise reinsert) a subrange.
2306          * - allow ranges within the same file to be cloned (provided
2307          *   they don't overlap)?
2308          */
2309
2310         /* the destination must be opened for writing */
2311         if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
2312                 return -EINVAL;
2313
2314         if (btrfs_root_readonly(root))
2315                 return -EROFS;
2316
2317         ret = mnt_want_write_file(file);
2318         if (ret)
2319                 return ret;
2320
2321         src_file = fget(srcfd);
2322         if (!src_file) {
2323                 ret = -EBADF;
2324                 goto out_drop_write;
2325         }
2326
2327         src = src_file->f_dentry->d_inode;
2328
2329         ret = -EINVAL;
2330         if (src == inode)
2331                 goto out_fput;
2332
2333         /* the src must be open for reading */
2334         if (!(src_file->f_mode & FMODE_READ))
2335                 goto out_fput;
2336
2337         /* don't make the dst file partly checksummed */
2338         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2339             (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
2340                 goto out_fput;
2341
2342         ret = -EISDIR;
2343         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
2344                 goto out_fput;
2345
2346         ret = -EXDEV;
2347         if (src->i_sb != inode->i_sb || BTRFS_I(src)->root != root)
2348                 goto out_fput;
2349
2350         ret = -ENOMEM;
2351         buf = vmalloc(btrfs_level_size(root, 0));
2352         if (!buf)
2353                 goto out_fput;
2354
2355         path = btrfs_alloc_path();
2356         if (!path) {
2357                 vfree(buf);
2358                 goto out_fput;
2359         }
2360         path->reada = 2;
2361
2362         if (inode < src) {
2363                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
2364                 mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
2365         } else {
2366                 mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
2367                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2368         }
2369
2370         /* determine range to clone */
2371         ret = -EINVAL;
2372         if (off + len > src->i_size || off + len < off)
2373                 goto out_unlock;
2374         if (len == 0)
2375                 olen = len = src->i_size - off;
2376         /* if we extend to eof, continue to block boundary */
2377         if (off + len == src->i_size)
2378                 len = ALIGN(src->i_size, bs) - off;
2379
2380         /* verify the end result is block aligned */
2381         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
2382             !IS_ALIGNED(destoff, bs))
2383                 goto out_unlock;
2384
2385         if (destoff > inode->i_size) {
2386                 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
2387                 if (ret)
2388                         goto out_unlock;
2389         }
2390
2391         /* truncate page cache pages from target inode range */
2392         truncate_inode_pages_range(&inode->i_data, destoff,
2393                                    PAGE_CACHE_ALIGN(destoff + len) - 1);
2394
2395         /* do any pending delalloc/csum calc on src, one way or
2396            another, and lock file content */
2397         while (1) {
2398                 struct btrfs_ordered_extent *ordered;
2399                 lock_extent(&BTRFS_I(src)->io_tree, off, off+len);
2400                 ordered = btrfs_lookup_first_ordered_extent(src, off+len);
2401                 if (!ordered &&
2402                     !test_range_bit(&BTRFS_I(src)->io_tree, off, off+len,
2403                                    EXTENT_DELALLOC, 0, NULL))
2404                         break;
2405                 unlock_extent(&BTRFS_I(src)->io_tree, off, off+len);
2406                 if (ordered)
2407                         btrfs_put_ordered_extent(ordered);
2408                 btrfs_wait_ordered_range(src, off, len);
2409         }
2410
2411         /* clone data */
2412         key.objectid = btrfs_ino(src);
2413         key.type = BTRFS_EXTENT_DATA_KEY;
2414         key.offset = 0;
2415
2416         while (1) {
2417                 /*
2418                  * note the key will change type as we walk through the
2419                  * tree.
2420                  */
2421                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2422                 if (ret < 0)
2423                         goto out;
2424
2425                 nritems = btrfs_header_nritems(path->nodes[0]);
2426                 if (path->slots[0] >= nritems) {
2427                         ret = btrfs_next_leaf(root, path);
2428                         if (ret < 0)
2429                                 goto out;
2430                         if (ret > 0)
2431                                 break;
2432                         nritems = btrfs_header_nritems(path->nodes[0]);
2433                 }
2434                 leaf = path->nodes[0];
2435                 slot = path->slots[0];
2436
2437                 btrfs_item_key_to_cpu(leaf, &key, slot);
2438                 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
2439                     key.objectid != btrfs_ino(src))
2440                         break;
2441
2442                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
2443                         struct btrfs_file_extent_item *extent;
2444                         int type;
2445                         u32 size;
2446                         struct btrfs_key new_key;
2447                         u64 disko = 0, diskl = 0;
2448                         u64 datao = 0, datal = 0;
2449                         u8 comp;
2450                         u64 endoff;
2451
2452                         size = btrfs_item_size_nr(leaf, slot);
2453                         read_extent_buffer(leaf, buf,
2454                                            btrfs_item_ptr_offset(leaf, slot),
2455                                            size);
2456
2457                         extent = btrfs_item_ptr(leaf, slot,
2458                                                 struct btrfs_file_extent_item);
2459                         comp = btrfs_file_extent_compression(leaf, extent);
2460                         type = btrfs_file_extent_type(leaf, extent);
2461                         if (type == BTRFS_FILE_EXTENT_REG ||
2462                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2463                                 disko = btrfs_file_extent_disk_bytenr(leaf,
2464                                                                       extent);
2465                                 diskl = btrfs_file_extent_disk_num_bytes(leaf,
2466                                                                  extent);
2467                                 datao = btrfs_file_extent_offset(leaf, extent);
2468                                 datal = btrfs_file_extent_num_bytes(leaf,
2469                                                                     extent);
2470                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2471                                 /* take upper bound, may be compressed */
2472                                 datal = btrfs_file_extent_ram_bytes(leaf,
2473                                                                     extent);
2474                         }
2475                         btrfs_release_path(path);
2476
2477                         if (key.offset + datal <= off ||
2478                             key.offset >= off+len)
2479                                 goto next;
2480
2481                         memcpy(&new_key, &key, sizeof(new_key));
2482                         new_key.objectid = btrfs_ino(inode);
2483                         if (off <= key.offset)
2484                                 new_key.offset = key.offset + destoff - off;
2485                         else
2486                                 new_key.offset = destoff;
2487
2488                         /*
2489                          * 1 - adjusting old extent (we may have to split it)
2490                          * 1 - add new extent
2491                          * 1 - inode update
2492                          */
2493                         trans = btrfs_start_transaction(root, 3);
2494                         if (IS_ERR(trans)) {
2495                                 ret = PTR_ERR(trans);
2496                                 goto out;
2497                         }
2498
2499                         if (type == BTRFS_FILE_EXTENT_REG ||
2500                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2501                                 /*
2502                                  *    a  | --- range to clone ---|  b
2503                                  * | ------------- extent ------------- |
2504                                  */
2505
2506                                 /* substract range b */
2507                                 if (key.offset + datal > off + len)
2508                                         datal = off + len - key.offset;
2509
2510                                 /* substract range a */
2511                                 if (off > key.offset) {
2512                                         datao += off - key.offset;
2513                                         datal -= off - key.offset;
2514                                 }
2515
2516                                 ret = btrfs_drop_extents(trans, inode,
2517                                                          new_key.offset,
2518                                                          new_key.offset + datal,
2519                                                          &hint_byte, 1);
2520                                 if (ret) {
2521                                         btrfs_abort_transaction(trans, root,
2522                                                                 ret);
2523                                         btrfs_end_transaction(trans, root);
2524                                         goto out;
2525                                 }
2526
2527                                 ret = btrfs_insert_empty_item(trans, root, path,
2528                                                               &new_key, size);
2529                                 if (ret) {
2530                                         btrfs_abort_transaction(trans, root,
2531                                                                 ret);
2532                                         btrfs_end_transaction(trans, root);
2533                                         goto out;
2534                                 }
2535
2536                                 leaf = path->nodes[0];
2537                                 slot = path->slots[0];
2538                                 write_extent_buffer(leaf, buf,
2539                                             btrfs_item_ptr_offset(leaf, slot),
2540                                             size);
2541
2542                                 extent = btrfs_item_ptr(leaf, slot,
2543                                                 struct btrfs_file_extent_item);
2544
2545                                 /* disko == 0 means it's a hole */
2546                                 if (!disko)
2547                                         datao = 0;
2548
2549                                 btrfs_set_file_extent_offset(leaf, extent,
2550                                                              datao);
2551                                 btrfs_set_file_extent_num_bytes(leaf, extent,
2552                                                                 datal);
2553                                 if (disko) {
2554                                         inode_add_bytes(inode, datal);
2555                                         ret = btrfs_inc_extent_ref(trans, root,
2556                                                         disko, diskl, 0,
2557                                                         root->root_key.objectid,
2558                                                         btrfs_ino(inode),
2559                                                         new_key.offset - datao,
2560                                                         0);
2561                                         if (ret) {
2562                                                 btrfs_abort_transaction(trans,
2563                                                                         root,
2564                                                                         ret);
2565                                                 btrfs_end_transaction(trans,
2566                                                                       root);
2567                                                 goto out;
2568
2569                                         }
2570                                 }
2571                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2572                                 u64 skip = 0;
2573                                 u64 trim = 0;
2574                                 if (off > key.offset) {
2575                                         skip = off - key.offset;
2576                                         new_key.offset += skip;
2577                                 }
2578
2579                                 if (key.offset + datal > off+len)
2580                                         trim = key.offset + datal - (off+len);
2581
2582                                 if (comp && (skip || trim)) {
2583                                         ret = -EINVAL;
2584                                         btrfs_end_transaction(trans, root);
2585                                         goto out;
2586                                 }
2587                                 size -= skip + trim;
2588                                 datal -= skip + trim;
2589
2590                                 ret = btrfs_drop_extents(trans, inode,
2591                                                          new_key.offset,
2592                                                          new_key.offset + datal,
2593                                                          &hint_byte, 1);
2594                                 if (ret) {
2595                                         btrfs_abort_transaction(trans, root,
2596                                                                 ret);
2597                                         btrfs_end_transaction(trans, root);
2598                                         goto out;
2599                                 }
2600
2601                                 ret = btrfs_insert_empty_item(trans, root, path,
2602                                                               &new_key, size);
2603                                 if (ret) {
2604                                         btrfs_abort_transaction(trans, root,
2605                                                                 ret);
2606                                         btrfs_end_transaction(trans, root);
2607                                         goto out;
2608                                 }
2609
2610                                 if (skip) {
2611                                         u32 start =
2612                                           btrfs_file_extent_calc_inline_size(0);
2613                                         memmove(buf+start, buf+start+skip,
2614                                                 datal);
2615                                 }
2616
2617                                 leaf = path->nodes[0];
2618                                 slot = path->slots[0];
2619                                 write_extent_buffer(leaf, buf,
2620                                             btrfs_item_ptr_offset(leaf, slot),
2621                                             size);
2622                                 inode_add_bytes(inode, datal);
2623                         }
2624
2625                         btrfs_mark_buffer_dirty(leaf);
2626                         btrfs_release_path(path);
2627
2628                         inode_inc_iversion(inode);
2629                         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
2630
2631                         /*
2632                          * we round up to the block size at eof when
2633                          * determining which extents to clone above,
2634                          * but shouldn't round up the file size
2635                          */
2636                         endoff = new_key.offset + datal;
2637                         if (endoff > destoff+olen)
2638                                 endoff = destoff+olen;
2639                         if (endoff > inode->i_size)
2640                                 btrfs_i_size_write(inode, endoff);
2641
2642                         ret = btrfs_update_inode(trans, root, inode);
2643                         if (ret) {
2644                                 btrfs_abort_transaction(trans, root, ret);
2645                                 btrfs_end_transaction(trans, root);
2646                                 goto out;
2647                         }
2648                         ret = btrfs_end_transaction(trans, root);
2649                 }
2650 next:
2651                 btrfs_release_path(path);
2652                 key.offset++;
2653         }
2654         ret = 0;
2655 out:
2656         btrfs_release_path(path);
2657         unlock_extent(&BTRFS_I(src)->io_tree, off, off+len);
2658 out_unlock:
2659         mutex_unlock(&src->i_mutex);
2660         mutex_unlock(&inode->i_mutex);
2661         vfree(buf);
2662         btrfs_free_path(path);
2663 out_fput:
2664         fput(src_file);
2665 out_drop_write:
2666         mnt_drop_write_file(file);
2667         return ret;
2668 }
2669
2670 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
2671 {
2672         struct btrfs_ioctl_clone_range_args args;
2673
2674         if (copy_from_user(&args, argp, sizeof(args)))
2675                 return -EFAULT;
2676         return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
2677                                  args.src_length, args.dest_offset);
2678 }
2679
2680 /*
2681  * there are many ways the trans_start and trans_end ioctls can lead
2682  * to deadlocks.  They should only be used by applications that
2683  * basically own the machine, and have a very in depth understanding
2684  * of all the possible deadlocks and enospc problems.
2685  */
2686 static long btrfs_ioctl_trans_start(struct file *file)
2687 {
2688         struct inode *inode = fdentry(file)->d_inode;
2689         struct btrfs_root *root = BTRFS_I(inode)->root;
2690         struct btrfs_trans_handle *trans;
2691         int ret;
2692
2693         ret = -EPERM;
2694         if (!capable(CAP_SYS_ADMIN))
2695                 goto out;
2696
2697         ret = -EINPROGRESS;
2698         if (file->private_data)
2699                 goto out;
2700
2701         ret = -EROFS;
2702         if (btrfs_root_readonly(root))
2703                 goto out;
2704
2705         ret = mnt_want_write_file(file);
2706         if (ret)
2707                 goto out;
2708
2709         atomic_inc(&root->fs_info->open_ioctl_trans);
2710
2711         ret = -ENOMEM;
2712         trans = btrfs_start_ioctl_transaction(root);
2713         if (IS_ERR(trans))
2714                 goto out_drop;
2715
2716         file->private_data = trans;
2717         return 0;
2718
2719 out_drop:
2720         atomic_dec(&root->fs_info->open_ioctl_trans);
2721         mnt_drop_write_file(file);
2722 out:
2723         return ret;
2724 }
2725
2726 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
2727 {
2728         struct inode *inode = fdentry(file)->d_inode;
2729         struct btrfs_root *root = BTRFS_I(inode)->root;
2730         struct btrfs_root *new_root;
2731         struct btrfs_dir_item *di;
2732         struct btrfs_trans_handle *trans;
2733         struct btrfs_path *path;
2734         struct btrfs_key location;
2735         struct btrfs_disk_key disk_key;
2736         struct btrfs_super_block *disk_super;
2737         u64 features;
2738         u64 objectid = 0;
2739         u64 dir_id;
2740
2741         if (!capable(CAP_SYS_ADMIN))
2742                 return -EPERM;
2743
2744         if (copy_from_user(&objectid, argp, sizeof(objectid)))
2745                 return -EFAULT;
2746
2747         if (!objectid)
2748                 objectid = root->root_key.objectid;
2749
2750         location.objectid = objectid;
2751         location.type = BTRFS_ROOT_ITEM_KEY;
2752         location.offset = (u64)-1;
2753
2754         new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
2755         if (IS_ERR(new_root))
2756                 return PTR_ERR(new_root);
2757
2758         if (btrfs_root_refs(&new_root->root_item) == 0)
2759                 return -ENOENT;
2760
2761         path = btrfs_alloc_path();
2762         if (!path)
2763                 return -ENOMEM;
2764         path->leave_spinning = 1;
2765
2766         trans = btrfs_start_transaction(root, 1);
2767         if (IS_ERR(trans)) {
2768                 btrfs_free_path(path);
2769                 return PTR_ERR(trans);
2770         }
2771
2772         dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
2773         di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
2774                                    dir_id, "default", 7, 1);
2775         if (IS_ERR_OR_NULL(di)) {
2776                 btrfs_free_path(path);
2777                 btrfs_end_transaction(trans, root);
2778                 printk(KERN_ERR "Umm, you don't have the default dir item, "
2779                        "this isn't going to work\n");
2780                 return -ENOENT;
2781         }
2782
2783         btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
2784         btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
2785         btrfs_mark_buffer_dirty(path->nodes[0]);
2786         btrfs_free_path(path);
2787
2788         disk_super = root->fs_info->super_copy;
2789         features = btrfs_super_incompat_flags(disk_super);
2790         if (!(features & BTRFS_FEATURE_INCOMPAT_DEFAULT_SUBVOL)) {
2791                 features |= BTRFS_FEATURE_INCOMPAT_DEFAULT_SUBVOL;
2792                 btrfs_set_super_incompat_flags(disk_super, features);
2793         }
2794         btrfs_end_transaction(trans, root);
2795
2796         return 0;
2797 }
2798
2799 static void get_block_group_info(struct list_head *groups_list,
2800                                  struct btrfs_ioctl_space_info *space)
2801 {
2802         struct btrfs_block_group_cache *block_group;
2803
2804         space->total_bytes = 0;
2805         space->used_bytes = 0;
2806         space->flags = 0;
2807         list_for_each_entry(block_group, groups_list, list) {
2808                 space->flags = block_group->flags;
2809                 space->total_bytes += block_group->key.offset;
2810                 space->used_bytes +=
2811                         btrfs_block_group_used(&block_group->item);
2812         }
2813 }
2814
2815 long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
2816 {
2817         struct btrfs_ioctl_space_args space_args;
2818         struct btrfs_ioctl_space_info space;
2819         struct btrfs_ioctl_space_info *dest;
2820         struct btrfs_ioctl_space_info *dest_orig;
2821         struct btrfs_ioctl_space_info __user *user_dest;
2822         struct btrfs_space_info *info;
2823         u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
2824                        BTRFS_BLOCK_GROUP_SYSTEM,
2825                        BTRFS_BLOCK_GROUP_METADATA,
2826                        BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
2827         int num_types = 4;
2828         int alloc_size;
2829         int ret = 0;
2830         u64 slot_count = 0;
2831         int i, c;
2832
2833         if (copy_from_user(&space_args,
2834                            (struct btrfs_ioctl_space_args __user *)arg,
2835                            sizeof(space_args)))
2836                 return -EFAULT;
2837
2838         for (i = 0; i < num_types; i++) {
2839                 struct btrfs_space_info *tmp;
2840
2841                 info = NULL;
2842                 rcu_read_lock();
2843                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
2844                                         list) {
2845                         if (tmp->flags == types[i]) {
2846                                 info = tmp;
2847                                 break;
2848                         }
2849                 }
2850                 rcu_read_unlock();
2851
2852                 if (!info)
2853                         continue;
2854
2855                 down_read(&info->groups_sem);
2856                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
2857                         if (!list_empty(&info->block_groups[c]))
2858                                 slot_count++;
2859                 }
2860                 up_read(&info->groups_sem);
2861         }
2862
2863         /* space_slots == 0 means they are asking for a count */
2864         if (space_args.space_slots == 0) {
2865                 space_args.total_spaces = slot_count;
2866                 goto out;
2867         }
2868
2869         slot_count = min_t(u64, space_args.space_slots, slot_count);
2870
2871         alloc_size = sizeof(*dest) * slot_count;
2872
2873         /* we generally have at most 6 or so space infos, one for each raid
2874          * level.  So, a whole page should be more than enough for everyone
2875          */
2876         if (alloc_size > PAGE_CACHE_SIZE)
2877                 return -ENOMEM;
2878
2879         space_args.total_spaces = 0;
2880         dest = kmalloc(alloc_size, GFP_NOFS);
2881         if (!dest)
2882                 return -ENOMEM;
2883         dest_orig = dest;
2884
2885         /* now we have a buffer to copy into */
2886         for (i = 0; i < num_types; i++) {
2887                 struct btrfs_space_info *tmp;
2888
2889                 if (!slot_count)
2890                         break;
2891
2892                 info = NULL;
2893                 rcu_read_lock();
2894                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
2895                                         list) {
2896                         if (tmp->flags == types[i]) {
2897                                 info = tmp;
2898                                 break;
2899                         }
2900                 }
2901                 rcu_read_unlock();
2902
2903                 if (!info)
2904                         continue;
2905                 down_read(&info->groups_sem);
2906                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
2907                         if (!list_empty(&info->block_groups[c])) {
2908                                 get_block_group_info(&info->block_groups[c],
2909                                                      &space);
2910                                 memcpy(dest, &space, sizeof(space));
2911                                 dest++;
2912                                 space_args.total_spaces++;
2913                                 slot_count--;
2914                         }
2915                         if (!slot_count)
2916                                 break;
2917                 }
2918                 up_read(&info->groups_sem);
2919         }
2920
2921         user_dest = (struct btrfs_ioctl_space_info __user *)
2922                 (arg + sizeof(struct btrfs_ioctl_space_args));
2923
2924         if (copy_to_user(user_dest, dest_orig, alloc_size))
2925                 ret = -EFAULT;
2926
2927         kfree(dest_orig);
2928 out:
2929         if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
2930                 ret = -EFAULT;
2931
2932         return ret;
2933 }
2934
2935 /*
2936  * there are many ways the trans_start and trans_end ioctls can lead
2937  * to deadlocks.  They should only be used by applications that
2938  * basically own the machine, and have a very in depth understanding
2939  * of all the possible deadlocks and enospc problems.
2940  */
2941 long btrfs_ioctl_trans_end(struct file *file)
2942 {
2943         struct inode *inode = fdentry(file)->d_inode;
2944         struct btrfs_root *root = BTRFS_I(inode)->root;
2945         struct btrfs_trans_handle *trans;
2946
2947         trans = file->private_data;
2948         if (!trans)
2949                 return -EINVAL;
2950         file->private_data = NULL;
2951
2952         btrfs_end_transaction(trans, root);
2953
2954         atomic_dec(&root->fs_info->open_ioctl_trans);
2955
2956         mnt_drop_write_file(file);
2957         return 0;
2958 }
2959
2960 static noinline long btrfs_ioctl_start_sync(struct file *file, void __user *argp)
2961 {
2962         struct btrfs_root *root = BTRFS_I(file->f_dentry->d_inode)->root;
2963         struct btrfs_trans_handle *trans;
2964         u64 transid;
2965         int ret;
2966
2967         trans = btrfs_start_transaction(root, 0);
2968         if (IS_ERR(trans))
2969                 return PTR_ERR(trans);
2970         transid = trans->transid;
2971         ret = btrfs_commit_transaction_async(trans, root, 0);
2972         if (ret) {
2973                 btrfs_end_transaction(trans, root);
2974                 return ret;
2975         }
2976
2977         if (argp)
2978                 if (copy_to_user(argp, &transid, sizeof(transid)))
2979                         return -EFAULT;
2980         return 0;
2981 }
2982
2983 static noinline long btrfs_ioctl_wait_sync(struct file *file, void __user *argp)
2984 {
2985         struct btrfs_root *root = BTRFS_I(file->f_dentry->d_inode)->root;
2986         u64 transid;
2987
2988         if (argp) {
2989                 if (copy_from_user(&transid, argp, sizeof(transid)))
2990                         return -EFAULT;
2991         } else {
2992                 transid = 0;  /* current trans */
2993         }
2994         return btrfs_wait_for_commit(root, transid);
2995 }
2996
2997 static long btrfs_ioctl_scrub(struct btrfs_root *root, void __user *arg)
2998 {
2999         int ret;
3000         struct btrfs_ioctl_scrub_args *sa;
3001
3002         if (!capable(CAP_SYS_ADMIN))
3003                 return -EPERM;
3004
3005         sa = memdup_user(arg, sizeof(*sa));
3006         if (IS_ERR(sa))
3007                 return PTR_ERR(sa);
3008
3009         ret = btrfs_scrub_dev(root, sa->devid, sa->start, sa->end,
3010                               &sa->progress, sa->flags & BTRFS_SCRUB_READONLY);
3011
3012         if (copy_to_user(arg, sa, sizeof(*sa)))
3013                 ret = -EFAULT;
3014
3015         kfree(sa);
3016         return ret;
3017 }
3018
3019 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
3020 {
3021         if (!capable(CAP_SYS_ADMIN))
3022                 return -EPERM;
3023
3024         return btrfs_scrub_cancel(root);
3025 }
3026
3027 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
3028                                        void __user *arg)
3029 {
3030         struct btrfs_ioctl_scrub_args *sa;
3031         int ret;
3032
3033         if (!capable(CAP_SYS_ADMIN))
3034                 return -EPERM;
3035
3036         sa = memdup_user(arg, sizeof(*sa));
3037         if (IS_ERR(sa))
3038                 return PTR_ERR(sa);
3039
3040         ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
3041
3042         if (copy_to_user(arg, sa, sizeof(*sa)))
3043                 ret = -EFAULT;
3044
3045         kfree(sa);
3046         return ret;
3047 }
3048
3049 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
3050                                       void __user *arg, int reset_after_read)
3051 {
3052         struct btrfs_ioctl_get_dev_stats *sa;
3053         int ret;
3054
3055         if (reset_after_read && !capable(CAP_SYS_ADMIN))
3056                 return -EPERM;
3057
3058         sa = memdup_user(arg, sizeof(*sa));
3059         if (IS_ERR(sa))
3060                 return PTR_ERR(sa);
3061
3062         ret = btrfs_get_dev_stats(root, sa, reset_after_read);
3063
3064         if (copy_to_user(arg, sa, sizeof(*sa)))
3065                 ret = -EFAULT;
3066
3067         kfree(sa);
3068         return ret;
3069 }
3070
3071 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3072 {
3073         int ret = 0;
3074         int i;
3075         u64 rel_ptr;
3076         int size;
3077         struct btrfs_ioctl_ino_path_args *ipa = NULL;
3078         struct inode_fs_paths *ipath = NULL;
3079         struct btrfs_path *path;
3080
3081         if (!capable(CAP_SYS_ADMIN))
3082                 return -EPERM;
3083
3084         path = btrfs_alloc_path();
3085         if (!path) {
3086                 ret = -ENOMEM;
3087                 goto out;
3088         }
3089
3090         ipa = memdup_user(arg, sizeof(*ipa));
3091         if (IS_ERR(ipa)) {
3092                 ret = PTR_ERR(ipa);
3093                 ipa = NULL;
3094                 goto out;
3095         }
3096
3097         size = min_t(u32, ipa->size, 4096);
3098         ipath = init_ipath(size, root, path);
3099         if (IS_ERR(ipath)) {
3100                 ret = PTR_ERR(ipath);
3101                 ipath = NULL;
3102                 goto out;
3103         }
3104
3105         ret = paths_from_inode(ipa->inum, ipath);
3106         if (ret < 0)
3107                 goto out;
3108
3109         for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3110                 rel_ptr = ipath->fspath->val[i] -
3111                           (u64)(unsigned long)ipath->fspath->val;
3112                 ipath->fspath->val[i] = rel_ptr;
3113         }
3114
3115         ret = copy_to_user((void *)(unsigned long)ipa->fspath,
3116                            (void *)(unsigned long)ipath->fspath, size);
3117         if (ret) {
3118                 ret = -EFAULT;
3119                 goto out;
3120         }
3121
3122 out:
3123         btrfs_free_path(path);
3124         free_ipath(ipath);
3125         kfree(ipa);
3126
3127         return ret;
3128 }
3129
3130 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3131 {
3132         struct btrfs_data_container *inodes = ctx;
3133         const size_t c = 3 * sizeof(u64);
3134
3135         if (inodes->bytes_left >= c) {
3136                 inodes->bytes_left -= c;
3137                 inodes->val[inodes->elem_cnt] = inum;
3138                 inodes->val[inodes->elem_cnt + 1] = offset;
3139                 inodes->val[inodes->elem_cnt + 2] = root;
3140                 inodes->elem_cnt += 3;
3141         } else {
3142                 inodes->bytes_missing += c - inodes->bytes_left;
3143                 inodes->bytes_left = 0;
3144                 inodes->elem_missed += 3;
3145         }
3146
3147         return 0;
3148 }
3149
3150 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
3151                                         void __user *arg)
3152 {
3153         int ret = 0;
3154         int size;
3155         u64 extent_item_pos;
3156         struct btrfs_ioctl_logical_ino_args *loi;
3157         struct btrfs_data_container *inodes = NULL;
3158         struct btrfs_path *path = NULL;
3159         struct btrfs_key key;
3160
3161         if (!capable(CAP_SYS_ADMIN))
3162                 return -EPERM;
3163
3164         loi = memdup_user(arg, sizeof(*loi));
3165         if (IS_ERR(loi)) {
3166                 ret = PTR_ERR(loi);
3167                 loi = NULL;
3168                 goto out;
3169         }
3170
3171         path = btrfs_alloc_path();
3172         if (!path) {
3173                 ret = -ENOMEM;
3174                 goto out;
3175         }
3176
3177         size = min_t(u32, loi->size, 4096);
3178         inodes = init_data_container(size);
3179         if (IS_ERR(inodes)) {
3180                 ret = PTR_ERR(inodes);
3181                 inodes = NULL;
3182                 goto out;
3183         }
3184
3185         ret = extent_from_logical(root->fs_info, loi->logical, path, &key);
3186         btrfs_release_path(path);
3187
3188         if (ret & BTRFS_EXTENT_FLAG_TREE_BLOCK)
3189                 ret = -ENOENT;
3190         if (ret < 0)
3191                 goto out;
3192
3193         extent_item_pos = loi->logical - key.objectid;
3194         ret = iterate_extent_inodes(root->fs_info, key.objectid,
3195                                         extent_item_pos, 0, build_ino_list,
3196                                         inodes);
3197
3198         if (ret < 0)
3199                 goto out;
3200
3201         ret = copy_to_user((void *)(unsigned long)loi->inodes,
3202                            (void *)(unsigned long)inodes, size);
3203         if (ret)
3204                 ret = -EFAULT;
3205
3206 out:
3207         btrfs_free_path(path);
3208         kfree(inodes);
3209         kfree(loi);
3210
3211         return ret;
3212 }
3213
3214 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
3215                                struct btrfs_ioctl_balance_args *bargs)
3216 {
3217         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3218
3219         bargs->flags = bctl->flags;
3220
3221         if (atomic_read(&fs_info->balance_running))
3222                 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3223         if (atomic_read(&fs_info->balance_pause_req))
3224                 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3225         if (atomic_read(&fs_info->balance_cancel_req))
3226                 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3227
3228         memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3229         memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3230         memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3231
3232         if (lock) {
3233                 spin_lock(&fs_info->balance_lock);
3234                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3235                 spin_unlock(&fs_info->balance_lock);
3236         } else {
3237                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3238         }
3239 }
3240
3241 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3242 {
3243         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
3244         struct btrfs_fs_info *fs_info = root->fs_info;
3245         struct btrfs_ioctl_balance_args *bargs;
3246         struct btrfs_balance_control *bctl;
3247         int ret;
3248
3249         if (!capable(CAP_SYS_ADMIN))
3250                 return -EPERM;
3251
3252         if (fs_info->sb->s_flags & MS_RDONLY)
3253                 return -EROFS;
3254
3255         ret = mnt_want_write(file->f_path.mnt);
3256         if (ret)
3257                 return ret;
3258
3259         mutex_lock(&fs_info->volume_mutex);
3260         mutex_lock(&fs_info->balance_mutex);
3261
3262         if (arg) {
3263                 bargs = memdup_user(arg, sizeof(*bargs));
3264                 if (IS_ERR(bargs)) {
3265                         ret = PTR_ERR(bargs);
3266                         goto out;
3267                 }
3268
3269                 if (bargs->flags & BTRFS_BALANCE_RESUME) {
3270                         if (!fs_info->balance_ctl) {
3271                                 ret = -ENOTCONN;
3272                                 goto out_bargs;
3273                         }
3274
3275                         bctl = fs_info->balance_ctl;
3276                         spin_lock(&fs_info->balance_lock);
3277                         bctl->flags |= BTRFS_BALANCE_RESUME;
3278                         spin_unlock(&fs_info->balance_lock);
3279
3280                         goto do_balance;
3281                 }
3282         } else {
3283                 bargs = NULL;
3284         }
3285
3286         if (fs_info->balance_ctl) {
3287                 ret = -EINPROGRESS;
3288                 goto out_bargs;
3289         }
3290
3291         bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3292         if (!bctl) {
3293                 ret = -ENOMEM;
3294                 goto out_bargs;
3295         }
3296
3297         bctl->fs_info = fs_info;
3298         if (arg) {
3299                 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
3300                 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
3301                 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
3302
3303                 bctl->flags = bargs->flags;
3304         } else {
3305                 /* balance everything - no filters */
3306                 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
3307         }
3308
3309 do_balance:
3310         ret = btrfs_balance(bctl, bargs);
3311         /*
3312          * bctl is freed in __cancel_balance or in free_fs_info if
3313          * restriper was paused all the way until unmount
3314          */
3315         if (arg) {
3316                 if (copy_to_user(arg, bargs, sizeof(*bargs)))
3317                         ret = -EFAULT;
3318         }
3319
3320 out_bargs:
3321         kfree(bargs);
3322 out:
3323         mutex_unlock(&fs_info->balance_mutex);
3324         mutex_unlock(&fs_info->volume_mutex);
3325         mnt_drop_write(file->f_path.mnt);
3326         return ret;
3327 }
3328
3329 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
3330 {
3331         if (!capable(CAP_SYS_ADMIN))
3332                 return -EPERM;
3333
3334         switch (cmd) {
3335         case BTRFS_BALANCE_CTL_PAUSE:
3336                 return btrfs_pause_balance(root->fs_info);
3337         case BTRFS_BALANCE_CTL_CANCEL:
3338                 return btrfs_cancel_balance(root->fs_info);
3339         }
3340
3341         return -EINVAL;
3342 }
3343
3344 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
3345                                          void __user *arg)
3346 {
3347         struct btrfs_fs_info *fs_info = root->fs_info;
3348         struct btrfs_ioctl_balance_args *bargs;
3349         int ret = 0;
3350
3351         if (!capable(CAP_SYS_ADMIN))
3352                 return -EPERM;
3353
3354         mutex_lock(&fs_info->balance_mutex);
3355         if (!fs_info->balance_ctl) {
3356                 ret = -ENOTCONN;
3357                 goto out;
3358         }
3359
3360         bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
3361         if (!bargs) {
3362                 ret = -ENOMEM;
3363                 goto out;
3364         }
3365
3366         update_ioctl_balance_args(fs_info, 1, bargs);
3367
3368         if (copy_to_user(arg, bargs, sizeof(*bargs)))
3369                 ret = -EFAULT;
3370
3371         kfree(bargs);
3372 out:
3373         mutex_unlock(&fs_info->balance_mutex);
3374         return ret;
3375 }
3376
3377 long btrfs_ioctl(struct file *file, unsigned int
3378                 cmd, unsigned long arg)
3379 {
3380         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
3381         void __user *argp = (void __user *)arg;
3382
3383         switch (cmd) {
3384         case FS_IOC_GETFLAGS:
3385                 return btrfs_ioctl_getflags(file, argp);
3386         case FS_IOC_SETFLAGS:
3387                 return btrfs_ioctl_setflags(file, argp);
3388         case FS_IOC_GETVERSION:
3389                 return btrfs_ioctl_getversion(file, argp);
3390         case FITRIM:
3391                 return btrfs_ioctl_fitrim(file, argp);
3392         case BTRFS_IOC_SNAP_CREATE:
3393                 return btrfs_ioctl_snap_create(file, argp, 0);
3394         case BTRFS_IOC_SNAP_CREATE_V2:
3395                 return btrfs_ioctl_snap_create_v2(file, argp, 0);
3396         case BTRFS_IOC_SUBVOL_CREATE:
3397                 return btrfs_ioctl_snap_create(file, argp, 1);
3398         case BTRFS_IOC_SNAP_DESTROY:
3399                 return btrfs_ioctl_snap_destroy(file, argp);
3400         case BTRFS_IOC_SUBVOL_GETFLAGS:
3401                 return btrfs_ioctl_subvol_getflags(file, argp);
3402         case BTRFS_IOC_SUBVOL_SETFLAGS:
3403                 return btrfs_ioctl_subvol_setflags(file, argp);
3404         case BTRFS_IOC_DEFAULT_SUBVOL:
3405                 return btrfs_ioctl_default_subvol(file, argp);
3406         case BTRFS_IOC_DEFRAG:
3407                 return btrfs_ioctl_defrag(file, NULL);
3408         case BTRFS_IOC_DEFRAG_RANGE:
3409                 return btrfs_ioctl_defrag(file, argp);
3410         case BTRFS_IOC_RESIZE:
3411                 return btrfs_ioctl_resize(root, argp);
3412         case BTRFS_IOC_ADD_DEV:
3413                 return btrfs_ioctl_add_dev(root, argp);
3414         case BTRFS_IOC_RM_DEV:
3415                 return btrfs_ioctl_rm_dev(root, argp);
3416         case BTRFS_IOC_FS_INFO:
3417                 return btrfs_ioctl_fs_info(root, argp);
3418         case BTRFS_IOC_DEV_INFO:
3419                 return btrfs_ioctl_dev_info(root, argp);
3420         case BTRFS_IOC_BALANCE:
3421                 return btrfs_ioctl_balance(file, NULL);
3422         case BTRFS_IOC_CLONE:
3423                 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
3424         case BTRFS_IOC_CLONE_RANGE:
3425                 return btrfs_ioctl_clone_range(file, argp);
3426         case BTRFS_IOC_TRANS_START:
3427                 return btrfs_ioctl_trans_start(file);
3428         case BTRFS_IOC_TRANS_END:
3429                 return btrfs_ioctl_trans_end(file);
3430         case BTRFS_IOC_TREE_SEARCH:
3431                 return btrfs_ioctl_tree_search(file, argp);
3432         case BTRFS_IOC_INO_LOOKUP:
3433                 return btrfs_ioctl_ino_lookup(file, argp);
3434         case BTRFS_IOC_INO_PATHS:
3435                 return btrfs_ioctl_ino_to_path(root, argp);
3436         case BTRFS_IOC_LOGICAL_INO:
3437                 return btrfs_ioctl_logical_to_ino(root, argp);
3438         case BTRFS_IOC_SPACE_INFO:
3439                 return btrfs_ioctl_space_info(root, argp);
3440         case BTRFS_IOC_SYNC:
3441                 btrfs_sync_fs(file->f_dentry->d_sb, 1);
3442                 return 0;
3443         case BTRFS_IOC_START_SYNC:
3444                 return btrfs_ioctl_start_sync(file, argp);
3445         case BTRFS_IOC_WAIT_SYNC:
3446                 return btrfs_ioctl_wait_sync(file, argp);
3447         case BTRFS_IOC_SCRUB:
3448                 return btrfs_ioctl_scrub(root, argp);
3449         case BTRFS_IOC_SCRUB_CANCEL:
3450                 return btrfs_ioctl_scrub_cancel(root, argp);
3451         case BTRFS_IOC_SCRUB_PROGRESS:
3452                 return btrfs_ioctl_scrub_progress(root, argp);
3453         case BTRFS_IOC_BALANCE_V2:
3454                 return btrfs_ioctl_balance(file, argp);
3455         case BTRFS_IOC_BALANCE_CTL:
3456                 return btrfs_ioctl_balance_ctl(root, arg);
3457         case BTRFS_IOC_BALANCE_PROGRESS:
3458                 return btrfs_ioctl_balance_progress(root, argp);
3459         case BTRFS_IOC_GET_DEV_STATS:
3460                 return btrfs_ioctl_get_dev_stats(root, argp, 0);
3461         case BTRFS_IOC_GET_AND_RESET_DEV_STATS:
3462                 return btrfs_ioctl_get_dev_stats(root, argp, 1);
3463         }
3464
3465         return -ENOTTY;
3466 }