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