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