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