OSDN Git Service

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