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