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