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