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