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