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