Btrfs: get write access when removing a device
[pandora-kernel.git] / fs / btrfs / ioctl.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/fsnotify.h>
25 #include <linux/pagemap.h>
26 #include <linux/highmem.h>
27 #include <linux/time.h>
28 #include <linux/init.h>
29 #include <linux/string.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mount.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/swap.h>
35 #include <linux/writeback.h>
36 #include <linux/statfs.h>
37 #include <linux/compat.h>
38 #include <linux/bit_spinlock.h>
39 #include <linux/security.h>
40 #include <linux/xattr.h>
41 #include <linux/vmalloc.h>
42 #include <linux/slab.h>
43 #include <linux/blkdev.h>
44 #include <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         down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
714
715         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
716                 goto out_up_read;
717
718         if (snap_src) {
719                 error = create_snapshot(snap_src, dentry, name, namelen,
720                                         async_transid, readonly, inherit);
721         } else {
722                 error = create_subvol(BTRFS_I(dir)->root, dentry,
723                                       name, namelen, async_transid, inherit);
724         }
725         if (!error)
726                 fsnotify_mkdir(dir, dentry);
727 out_up_read:
728         up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
729 out_dput:
730         dput(dentry);
731 out_unlock:
732         mutex_unlock(&dir->i_mutex);
733         return error;
734 }
735
736 /*
737  * When we're defragging a range, we don't want to kick it off again
738  * if it is really just waiting for delalloc to send it down.
739  * If we find a nice big extent or delalloc range for the bytes in the
740  * file you want to defrag, we return 0 to let you know to skip this
741  * part of the file
742  */
743 static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh)
744 {
745         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
746         struct extent_map *em = NULL;
747         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
748         u64 end;
749
750         read_lock(&em_tree->lock);
751         em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
752         read_unlock(&em_tree->lock);
753
754         if (em) {
755                 end = extent_map_end(em);
756                 free_extent_map(em);
757                 if (end - offset > thresh)
758                         return 0;
759         }
760         /* if we already have a nice delalloc here, just stop */
761         thresh /= 2;
762         end = count_range_bits(io_tree, &offset, offset + thresh,
763                                thresh, EXTENT_DELALLOC, 1);
764         if (end >= thresh)
765                 return 0;
766         return 1;
767 }
768
769 /*
770  * helper function to walk through a file and find extents
771  * newer than a specific transid, and smaller than thresh.
772  *
773  * This is used by the defragging code to find new and small
774  * extents
775  */
776 static int find_new_extents(struct btrfs_root *root,
777                             struct inode *inode, u64 newer_than,
778                             u64 *off, int thresh)
779 {
780         struct btrfs_path *path;
781         struct btrfs_key min_key;
782         struct btrfs_key max_key;
783         struct extent_buffer *leaf;
784         struct btrfs_file_extent_item *extent;
785         int type;
786         int ret;
787         u64 ino = btrfs_ino(inode);
788
789         path = btrfs_alloc_path();
790         if (!path)
791                 return -ENOMEM;
792
793         min_key.objectid = ino;
794         min_key.type = BTRFS_EXTENT_DATA_KEY;
795         min_key.offset = *off;
796
797         max_key.objectid = ino;
798         max_key.type = (u8)-1;
799         max_key.offset = (u64)-1;
800
801         path->keep_locks = 1;
802
803         while(1) {
804                 ret = btrfs_search_forward(root, &min_key, &max_key,
805                                            path, 0, newer_than);
806                 if (ret != 0)
807                         goto none;
808                 if (min_key.objectid != ino)
809                         goto none;
810                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
811                         goto none;
812
813                 leaf = path->nodes[0];
814                 extent = btrfs_item_ptr(leaf, path->slots[0],
815                                         struct btrfs_file_extent_item);
816
817                 type = btrfs_file_extent_type(leaf, extent);
818                 if (type == BTRFS_FILE_EXTENT_REG &&
819                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
820                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
821                         *off = min_key.offset;
822                         btrfs_free_path(path);
823                         return 0;
824                 }
825
826                 if (min_key.offset == (u64)-1)
827                         goto none;
828
829                 min_key.offset++;
830                 btrfs_release_path(path);
831         }
832 none:
833         btrfs_free_path(path);
834         return -ENOENT;
835 }
836
837 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
838 {
839         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
840         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
841         struct extent_map *em;
842         u64 len = PAGE_CACHE_SIZE;
843
844         /*
845          * hopefully we have this extent in the tree already, try without
846          * the full extent lock
847          */
848         read_lock(&em_tree->lock);
849         em = lookup_extent_mapping(em_tree, start, len);
850         read_unlock(&em_tree->lock);
851
852         if (!em) {
853                 /* get the big lock and read metadata off disk */
854                 lock_extent(io_tree, start, start + len - 1);
855                 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
856                 unlock_extent(io_tree, start, start + len - 1);
857
858                 if (IS_ERR(em))
859                         return NULL;
860         }
861
862         return em;
863 }
864
865 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
866 {
867         struct extent_map *next;
868         bool ret = true;
869
870         /* this is the last extent */
871         if (em->start + em->len >= i_size_read(inode))
872                 return false;
873
874         next = defrag_lookup_extent(inode, em->start + em->len);
875         if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
876                 ret = false;
877
878         free_extent_map(next);
879         return ret;
880 }
881
882 static int should_defrag_range(struct inode *inode, u64 start, int thresh,
883                                u64 *last_len, u64 *skip, u64 *defrag_end,
884                                int compress)
885 {
886         struct extent_map *em;
887         int ret = 1;
888         bool next_mergeable = true;
889
890         /*
891          * make sure that once we start defragging an extent, we keep on
892          * defragging it
893          */
894         if (start < *defrag_end)
895                 return 1;
896
897         *skip = 0;
898
899         em = defrag_lookup_extent(inode, start);
900         if (!em)
901                 return 0;
902
903         /* this will cover holes, and inline extents */
904         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
905                 ret = 0;
906                 goto out;
907         }
908
909         next_mergeable = defrag_check_next_extent(inode, em);
910
911         /*
912          * we hit a real extent, if it is big or the next extent is not a
913          * real extent, don't bother defragging it
914          */
915         if (!compress && (*last_len == 0 || *last_len >= thresh) &&
916             (em->len >= thresh || !next_mergeable))
917                 ret = 0;
918 out:
919         /*
920          * last_len ends up being a counter of how many bytes we've defragged.
921          * every time we choose not to defrag an extent, we reset *last_len
922          * so that the next tiny extent will force a defrag.
923          *
924          * The end result of this is that tiny extents before a single big
925          * extent will force at least part of that big extent to be defragged.
926          */
927         if (ret) {
928                 *defrag_end = extent_map_end(em);
929         } else {
930                 *last_len = 0;
931                 *skip = extent_map_end(em);
932                 *defrag_end = 0;
933         }
934
935         free_extent_map(em);
936         return ret;
937 }
938
939 /*
940  * it doesn't do much good to defrag one or two pages
941  * at a time.  This pulls in a nice chunk of pages
942  * to COW and defrag.
943  *
944  * It also makes sure the delalloc code has enough
945  * dirty data to avoid making new small extents as part
946  * of the defrag
947  *
948  * It's a good idea to start RA on this range
949  * before calling this.
950  */
951 static int cluster_pages_for_defrag(struct inode *inode,
952                                     struct page **pages,
953                                     unsigned long start_index,
954                                     int num_pages)
955 {
956         unsigned long file_end;
957         u64 isize = i_size_read(inode);
958         u64 page_start;
959         u64 page_end;
960         u64 page_cnt;
961         int ret;
962         int i;
963         int i_done;
964         struct btrfs_ordered_extent *ordered;
965         struct extent_state *cached_state = NULL;
966         struct extent_io_tree *tree;
967         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
968
969         file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
970         if (!isize || start_index > file_end)
971                 return 0;
972
973         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
974
975         ret = btrfs_delalloc_reserve_space(inode,
976                                            page_cnt << PAGE_CACHE_SHIFT);
977         if (ret)
978                 return ret;
979         i_done = 0;
980         tree = &BTRFS_I(inode)->io_tree;
981
982         /* step one, lock all the pages */
983         for (i = 0; i < page_cnt; i++) {
984                 struct page *page;
985 again:
986                 page = find_or_create_page(inode->i_mapping,
987                                            start_index + i, mask);
988                 if (!page)
989                         break;
990
991                 page_start = page_offset(page);
992                 page_end = page_start + PAGE_CACHE_SIZE - 1;
993                 while (1) {
994                         lock_extent(tree, page_start, page_end);
995                         ordered = btrfs_lookup_ordered_extent(inode,
996                                                               page_start);
997                         unlock_extent(tree, page_start, page_end);
998                         if (!ordered)
999                                 break;
1000
1001                         unlock_page(page);
1002                         btrfs_start_ordered_extent(inode, ordered, 1);
1003                         btrfs_put_ordered_extent(ordered);
1004                         lock_page(page);
1005                         /*
1006                          * we unlocked the page above, so we need check if
1007                          * it was released or not.
1008                          */
1009                         if (page->mapping != inode->i_mapping) {
1010                                 unlock_page(page);
1011                                 page_cache_release(page);
1012                                 goto again;
1013                         }
1014                 }
1015
1016                 if (!PageUptodate(page)) {
1017                         btrfs_readpage(NULL, page);
1018                         lock_page(page);
1019                         if (!PageUptodate(page)) {
1020                                 unlock_page(page);
1021                                 page_cache_release(page);
1022                                 ret = -EIO;
1023                                 break;
1024                         }
1025                 }
1026
1027                 if (page->mapping != inode->i_mapping) {
1028                         unlock_page(page);
1029                         page_cache_release(page);
1030                         goto again;
1031                 }
1032
1033                 pages[i] = page;
1034                 i_done++;
1035         }
1036         if (!i_done || ret)
1037                 goto out;
1038
1039         if (!(inode->i_sb->s_flags & MS_ACTIVE))
1040                 goto out;
1041
1042         /*
1043          * so now we have a nice long stream of locked
1044          * and up to date pages, lets wait on them
1045          */
1046         for (i = 0; i < i_done; i++)
1047                 wait_on_page_writeback(pages[i]);
1048
1049         page_start = page_offset(pages[0]);
1050         page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1051
1052         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1053                          page_start, page_end - 1, 0, &cached_state);
1054         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1055                           page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1056                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1057                           &cached_state, GFP_NOFS);
1058
1059         if (i_done != page_cnt) {
1060                 spin_lock(&BTRFS_I(inode)->lock);
1061                 BTRFS_I(inode)->outstanding_extents++;
1062                 spin_unlock(&BTRFS_I(inode)->lock);
1063                 btrfs_delalloc_release_space(inode,
1064                                      (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1065         }
1066
1067
1068         set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1069                           &cached_state, GFP_NOFS);
1070
1071         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1072                              page_start, page_end - 1, &cached_state,
1073                              GFP_NOFS);
1074
1075         for (i = 0; i < i_done; i++) {
1076                 clear_page_dirty_for_io(pages[i]);
1077                 ClearPageChecked(pages[i]);
1078                 set_page_extent_mapped(pages[i]);
1079                 set_page_dirty(pages[i]);
1080                 unlock_page(pages[i]);
1081                 page_cache_release(pages[i]);
1082         }
1083         return i_done;
1084 out:
1085         for (i = 0; i < i_done; i++) {
1086                 unlock_page(pages[i]);
1087                 page_cache_release(pages[i]);
1088         }
1089         btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1090         return ret;
1091
1092 }
1093
1094 int btrfs_defrag_file(struct inode *inode, struct file *file,
1095                       struct btrfs_ioctl_defrag_range_args *range,
1096                       u64 newer_than, unsigned long max_to_defrag)
1097 {
1098         struct btrfs_root *root = BTRFS_I(inode)->root;
1099         struct file_ra_state *ra = NULL;
1100         unsigned long last_index;
1101         u64 isize = i_size_read(inode);
1102         u64 last_len = 0;
1103         u64 skip = 0;
1104         u64 defrag_end = 0;
1105         u64 newer_off = range->start;
1106         unsigned long i;
1107         unsigned long ra_index = 0;
1108         int ret;
1109         int defrag_count = 0;
1110         int compress_type = BTRFS_COMPRESS_ZLIB;
1111         int extent_thresh = range->extent_thresh;
1112         int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1113         int cluster = max_cluster;
1114         u64 new_align = ~((u64)128 * 1024 - 1);
1115         struct page **pages = NULL;
1116
1117         if (extent_thresh == 0)
1118                 extent_thresh = 256 * 1024;
1119
1120         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1121                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1122                         return -EINVAL;
1123                 if (range->compress_type)
1124                         compress_type = range->compress_type;
1125         }
1126
1127         if (isize == 0)
1128                 return 0;
1129
1130         /*
1131          * if we were not given a file, allocate a readahead
1132          * context
1133          */
1134         if (!file) {
1135                 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1136                 if (!ra)
1137                         return -ENOMEM;
1138                 file_ra_state_init(ra, inode->i_mapping);
1139         } else {
1140                 ra = &file->f_ra;
1141         }
1142
1143         pages = kmalloc(sizeof(struct page *) * max_cluster,
1144                         GFP_NOFS);
1145         if (!pages) {
1146                 ret = -ENOMEM;
1147                 goto out_ra;
1148         }
1149
1150         /* find the last page to defrag */
1151         if (range->start + range->len > range->start) {
1152                 last_index = min_t(u64, isize - 1,
1153                          range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1154         } else {
1155                 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1156         }
1157
1158         if (newer_than) {
1159                 ret = find_new_extents(root, inode, newer_than,
1160                                        &newer_off, 64 * 1024);
1161                 if (!ret) {
1162                         range->start = newer_off;
1163                         /*
1164                          * we always align our defrag to help keep
1165                          * the extents in the file evenly spaced
1166                          */
1167                         i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1168                 } else
1169                         goto out_ra;
1170         } else {
1171                 i = range->start >> PAGE_CACHE_SHIFT;
1172         }
1173         if (!max_to_defrag)
1174                 max_to_defrag = last_index + 1;
1175
1176         /*
1177          * make writeback starts from i, so the defrag range can be
1178          * written sequentially.
1179          */
1180         if (i < inode->i_mapping->writeback_index)
1181                 inode->i_mapping->writeback_index = i;
1182
1183         while (i <= last_index && defrag_count < max_to_defrag &&
1184                (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
1185                 PAGE_CACHE_SHIFT)) {
1186                 /*
1187                  * make sure we stop running if someone unmounts
1188                  * the FS
1189                  */
1190                 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1191                         break;
1192
1193                 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1194                                          extent_thresh, &last_len, &skip,
1195                                          &defrag_end, range->flags &
1196                                          BTRFS_DEFRAG_RANGE_COMPRESS)) {
1197                         unsigned long next;
1198                         /*
1199                          * the should_defrag function tells us how much to skip
1200                          * bump our counter by the suggested amount
1201                          */
1202                         next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1203                         i = max(i + 1, next);
1204                         continue;
1205                 }
1206
1207                 if (!newer_than) {
1208                         cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1209                                    PAGE_CACHE_SHIFT) - i;
1210                         cluster = min(cluster, max_cluster);
1211                 } else {
1212                         cluster = max_cluster;
1213                 }
1214
1215                 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1216                         BTRFS_I(inode)->force_compress = compress_type;
1217
1218                 if (i + cluster > ra_index) {
1219                         ra_index = max(i, ra_index);
1220                         btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1221                                        cluster);
1222                         ra_index += max_cluster;
1223                 }
1224
1225                 mutex_lock(&inode->i_mutex);
1226                 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1227                 if (ret < 0) {
1228                         mutex_unlock(&inode->i_mutex);
1229                         goto out_ra;
1230                 }
1231
1232                 defrag_count += ret;
1233                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, ret);
1234                 mutex_unlock(&inode->i_mutex);
1235
1236                 if (newer_than) {
1237                         if (newer_off == (u64)-1)
1238                                 break;
1239
1240                         if (ret > 0)
1241                                 i += ret;
1242
1243                         newer_off = max(newer_off + 1,
1244                                         (u64)i << PAGE_CACHE_SHIFT);
1245
1246                         ret = find_new_extents(root, inode,
1247                                                newer_than, &newer_off,
1248                                                64 * 1024);
1249                         if (!ret) {
1250                                 range->start = newer_off;
1251                                 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1252                         } else {
1253                                 break;
1254                         }
1255                 } else {
1256                         if (ret > 0) {
1257                                 i += ret;
1258                                 last_len += ret << PAGE_CACHE_SHIFT;
1259                         } else {
1260                                 i++;
1261                                 last_len = 0;
1262                         }
1263                 }
1264         }
1265
1266         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
1267                 filemap_flush(inode->i_mapping);
1268
1269         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1270                 /* the filemap_flush will queue IO into the worker threads, but
1271                  * we have to make sure the IO is actually started and that
1272                  * ordered extents get created before we return
1273                  */
1274                 atomic_inc(&root->fs_info->async_submit_draining);
1275                 while (atomic_read(&root->fs_info->nr_async_submits) ||
1276                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1277                         wait_event(root->fs_info->async_submit_wait,
1278                            (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1279                             atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1280                 }
1281                 atomic_dec(&root->fs_info->async_submit_draining);
1282
1283                 mutex_lock(&inode->i_mutex);
1284                 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1285                 mutex_unlock(&inode->i_mutex);
1286         }
1287
1288         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1289                 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1290         }
1291
1292         ret = defrag_count;
1293
1294 out_ra:
1295         if (!file)
1296                 kfree(ra);
1297         kfree(pages);
1298         return ret;
1299 }
1300
1301 static noinline int btrfs_ioctl_resize(struct file *file,
1302                                         void __user *arg)
1303 {
1304         u64 new_size;
1305         u64 old_size;
1306         u64 devid = 1;
1307         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
1308         struct btrfs_ioctl_vol_args *vol_args;
1309         struct btrfs_trans_handle *trans;
1310         struct btrfs_device *device = NULL;
1311         char *sizestr;
1312         char *devstr = NULL;
1313         int ret = 0;
1314         int mod = 0;
1315
1316         if (root->fs_info->sb->s_flags & MS_RDONLY)
1317                 return -EROFS;
1318
1319         if (!capable(CAP_SYS_ADMIN))
1320                 return -EPERM;
1321
1322         ret = mnt_want_write_file(file);
1323         if (ret)
1324                 return ret;
1325
1326         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1327                         1)) {
1328                 pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n");
1329                 return -EINPROGRESS;
1330         }
1331
1332         mutex_lock(&root->fs_info->volume_mutex);
1333         vol_args = memdup_user(arg, sizeof(*vol_args));
1334         if (IS_ERR(vol_args)) {
1335                 ret = PTR_ERR(vol_args);
1336                 goto out;
1337         }
1338
1339         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1340
1341         sizestr = vol_args->name;
1342         devstr = strchr(sizestr, ':');
1343         if (devstr) {
1344                 char *end;
1345                 sizestr = devstr + 1;
1346                 *devstr = '\0';
1347                 devstr = vol_args->name;
1348                 devid = simple_strtoull(devstr, &end, 10);
1349                 printk(KERN_INFO "btrfs: resizing devid %llu\n",
1350                        (unsigned long long)devid);
1351         }
1352         device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1353         if (!device) {
1354                 printk(KERN_INFO "btrfs: resizer unable to find device %llu\n",
1355                        (unsigned long long)devid);
1356                 ret = -EINVAL;
1357                 goto out_free;
1358         }
1359         if (device->fs_devices && device->fs_devices->seeding) {
1360                 printk(KERN_INFO "btrfs: resizer unable to apply on "
1361                        "seeding device %llu\n",
1362                        (unsigned long long)devid);
1363                 ret = -EINVAL;
1364                 goto out_free;
1365         }
1366
1367         if (!strcmp(sizestr, "max"))
1368                 new_size = device->bdev->bd_inode->i_size;
1369         else {
1370                 if (sizestr[0] == '-') {
1371                         mod = -1;
1372                         sizestr++;
1373                 } else if (sizestr[0] == '+') {
1374                         mod = 1;
1375                         sizestr++;
1376                 }
1377                 new_size = memparse(sizestr, NULL);
1378                 if (new_size == 0) {
1379                         ret = -EINVAL;
1380                         goto out_free;
1381                 }
1382         }
1383
1384         if (device->is_tgtdev_for_dev_replace) {
1385                 ret = -EINVAL;
1386                 goto out_free;
1387         }
1388
1389         old_size = device->total_bytes;
1390
1391         if (mod < 0) {
1392                 if (new_size > old_size) {
1393                         ret = -EINVAL;
1394                         goto out_free;
1395                 }
1396                 new_size = old_size - new_size;
1397         } else if (mod > 0) {
1398                 new_size = old_size + new_size;
1399         }
1400
1401         if (new_size < 256 * 1024 * 1024) {
1402                 ret = -EINVAL;
1403                 goto out_free;
1404         }
1405         if (new_size > device->bdev->bd_inode->i_size) {
1406                 ret = -EFBIG;
1407                 goto out_free;
1408         }
1409
1410         do_div(new_size, root->sectorsize);
1411         new_size *= root->sectorsize;
1412
1413         printk_in_rcu(KERN_INFO "btrfs: new size for %s is %llu\n",
1414                       rcu_str_deref(device->name),
1415                       (unsigned long long)new_size);
1416
1417         if (new_size > old_size) {
1418                 trans = btrfs_start_transaction(root, 0);
1419                 if (IS_ERR(trans)) {
1420                         ret = PTR_ERR(trans);
1421                         goto out_free;
1422                 }
1423                 ret = btrfs_grow_device(trans, device, new_size);
1424                 btrfs_commit_transaction(trans, root);
1425         } else if (new_size < old_size) {
1426                 ret = btrfs_shrink_device(device, new_size);
1427         } /* equal, nothing need to do */
1428
1429 out_free:
1430         kfree(vol_args);
1431 out:
1432         mutex_unlock(&root->fs_info->volume_mutex);
1433         mnt_drop_write_file(file);
1434         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1435         return ret;
1436 }
1437
1438 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1439                                 char *name, unsigned long fd, int subvol,
1440                                 u64 *transid, bool readonly,
1441                                 struct btrfs_qgroup_inherit **inherit)
1442 {
1443         int namelen;
1444         int ret = 0;
1445
1446         ret = mnt_want_write_file(file);
1447         if (ret)
1448                 goto out;
1449
1450         namelen = strlen(name);
1451         if (strchr(name, '/')) {
1452                 ret = -EINVAL;
1453                 goto out_drop_write;
1454         }
1455
1456         if (name[0] == '.' &&
1457            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1458                 ret = -EEXIST;
1459                 goto out_drop_write;
1460         }
1461
1462         if (subvol) {
1463                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1464                                      NULL, transid, readonly, inherit);
1465         } else {
1466                 struct fd src = fdget(fd);
1467                 struct inode *src_inode;
1468                 if (!src.file) {
1469                         ret = -EINVAL;
1470                         goto out_drop_write;
1471                 }
1472
1473                 src_inode = src.file->f_path.dentry->d_inode;
1474                 if (src_inode->i_sb != file->f_path.dentry->d_inode->i_sb) {
1475                         printk(KERN_INFO "btrfs: Snapshot src from "
1476                                "another FS\n");
1477                         ret = -EINVAL;
1478                 } else {
1479                         ret = btrfs_mksubvol(&file->f_path, name, namelen,
1480                                              BTRFS_I(src_inode)->root,
1481                                              transid, readonly, inherit);
1482                 }
1483                 fdput(src);
1484         }
1485 out_drop_write:
1486         mnt_drop_write_file(file);
1487 out:
1488         return ret;
1489 }
1490
1491 static noinline int btrfs_ioctl_snap_create(struct file *file,
1492                                             void __user *arg, int subvol)
1493 {
1494         struct btrfs_ioctl_vol_args *vol_args;
1495         int ret;
1496
1497         vol_args = memdup_user(arg, sizeof(*vol_args));
1498         if (IS_ERR(vol_args))
1499                 return PTR_ERR(vol_args);
1500         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1501
1502         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1503                                               vol_args->fd, subvol,
1504                                               NULL, false, NULL);
1505
1506         kfree(vol_args);
1507         return ret;
1508 }
1509
1510 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1511                                                void __user *arg, int subvol)
1512 {
1513         struct btrfs_ioctl_vol_args_v2 *vol_args;
1514         int ret;
1515         u64 transid = 0;
1516         u64 *ptr = NULL;
1517         bool readonly = false;
1518         struct btrfs_qgroup_inherit *inherit = NULL;
1519
1520         vol_args = memdup_user(arg, sizeof(*vol_args));
1521         if (IS_ERR(vol_args))
1522                 return PTR_ERR(vol_args);
1523         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1524
1525         if (vol_args->flags &
1526             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1527               BTRFS_SUBVOL_QGROUP_INHERIT)) {
1528                 ret = -EOPNOTSUPP;
1529                 goto out;
1530         }
1531
1532         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1533                 ptr = &transid;
1534         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1535                 readonly = true;
1536         if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1537                 if (vol_args->size > PAGE_CACHE_SIZE) {
1538                         ret = -EINVAL;
1539                         goto out;
1540                 }
1541                 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1542                 if (IS_ERR(inherit)) {
1543                         ret = PTR_ERR(inherit);
1544                         goto out;
1545                 }
1546         }
1547
1548         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1549                                               vol_args->fd, subvol, ptr,
1550                                               readonly, &inherit);
1551
1552         if (ret == 0 && ptr &&
1553             copy_to_user(arg +
1554                          offsetof(struct btrfs_ioctl_vol_args_v2,
1555                                   transid), ptr, sizeof(*ptr)))
1556                 ret = -EFAULT;
1557 out:
1558         kfree(vol_args);
1559         kfree(inherit);
1560         return ret;
1561 }
1562
1563 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1564                                                 void __user *arg)
1565 {
1566         struct inode *inode = fdentry(file)->d_inode;
1567         struct btrfs_root *root = BTRFS_I(inode)->root;
1568         int ret = 0;
1569         u64 flags = 0;
1570
1571         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1572                 return -EINVAL;
1573
1574         down_read(&root->fs_info->subvol_sem);
1575         if (btrfs_root_readonly(root))
1576                 flags |= BTRFS_SUBVOL_RDONLY;
1577         up_read(&root->fs_info->subvol_sem);
1578
1579         if (copy_to_user(arg, &flags, sizeof(flags)))
1580                 ret = -EFAULT;
1581
1582         return ret;
1583 }
1584
1585 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1586                                               void __user *arg)
1587 {
1588         struct inode *inode = fdentry(file)->d_inode;
1589         struct btrfs_root *root = BTRFS_I(inode)->root;
1590         struct btrfs_trans_handle *trans;
1591         u64 root_flags;
1592         u64 flags;
1593         int ret = 0;
1594
1595         ret = mnt_want_write_file(file);
1596         if (ret)
1597                 goto out;
1598
1599         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1600                 ret = -EINVAL;
1601                 goto out_drop_write;
1602         }
1603
1604         if (copy_from_user(&flags, arg, sizeof(flags))) {
1605                 ret = -EFAULT;
1606                 goto out_drop_write;
1607         }
1608
1609         if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1610                 ret = -EINVAL;
1611                 goto out_drop_write;
1612         }
1613
1614         if (flags & ~BTRFS_SUBVOL_RDONLY) {
1615                 ret = -EOPNOTSUPP;
1616                 goto out_drop_write;
1617         }
1618
1619         if (!inode_owner_or_capable(inode)) {
1620                 ret = -EACCES;
1621                 goto out_drop_write;
1622         }
1623
1624         down_write(&root->fs_info->subvol_sem);
1625
1626         /* nothing to do */
1627         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1628                 goto out_drop_sem;
1629
1630         root_flags = btrfs_root_flags(&root->root_item);
1631         if (flags & BTRFS_SUBVOL_RDONLY)
1632                 btrfs_set_root_flags(&root->root_item,
1633                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1634         else
1635                 btrfs_set_root_flags(&root->root_item,
1636                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1637
1638         trans = btrfs_start_transaction(root, 1);
1639         if (IS_ERR(trans)) {
1640                 ret = PTR_ERR(trans);
1641                 goto out_reset;
1642         }
1643
1644         ret = btrfs_update_root(trans, root->fs_info->tree_root,
1645                                 &root->root_key, &root->root_item);
1646
1647         btrfs_commit_transaction(trans, root);
1648 out_reset:
1649         if (ret)
1650                 btrfs_set_root_flags(&root->root_item, root_flags);
1651 out_drop_sem:
1652         up_write(&root->fs_info->subvol_sem);
1653 out_drop_write:
1654         mnt_drop_write_file(file);
1655 out:
1656         return ret;
1657 }
1658
1659 /*
1660  * helper to check if the subvolume references other subvolumes
1661  */
1662 static noinline int may_destroy_subvol(struct btrfs_root *root)
1663 {
1664         struct btrfs_path *path;
1665         struct btrfs_key key;
1666         int ret;
1667
1668         path = btrfs_alloc_path();
1669         if (!path)
1670                 return -ENOMEM;
1671
1672         key.objectid = root->root_key.objectid;
1673         key.type = BTRFS_ROOT_REF_KEY;
1674         key.offset = (u64)-1;
1675
1676         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1677                                 &key, path, 0, 0);
1678         if (ret < 0)
1679                 goto out;
1680         BUG_ON(ret == 0);
1681
1682         ret = 0;
1683         if (path->slots[0] > 0) {
1684                 path->slots[0]--;
1685                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1686                 if (key.objectid == root->root_key.objectid &&
1687                     key.type == BTRFS_ROOT_REF_KEY)
1688                         ret = -ENOTEMPTY;
1689         }
1690 out:
1691         btrfs_free_path(path);
1692         return ret;
1693 }
1694
1695 static noinline int key_in_sk(struct btrfs_key *key,
1696                               struct btrfs_ioctl_search_key *sk)
1697 {
1698         struct btrfs_key test;
1699         int ret;
1700
1701         test.objectid = sk->min_objectid;
1702         test.type = sk->min_type;
1703         test.offset = sk->min_offset;
1704
1705         ret = btrfs_comp_cpu_keys(key, &test);
1706         if (ret < 0)
1707                 return 0;
1708
1709         test.objectid = sk->max_objectid;
1710         test.type = sk->max_type;
1711         test.offset = sk->max_offset;
1712
1713         ret = btrfs_comp_cpu_keys(key, &test);
1714         if (ret > 0)
1715                 return 0;
1716         return 1;
1717 }
1718
1719 static noinline int copy_to_sk(struct btrfs_root *root,
1720                                struct btrfs_path *path,
1721                                struct btrfs_key *key,
1722                                struct btrfs_ioctl_search_key *sk,
1723                                char *buf,
1724                                unsigned long *sk_offset,
1725                                int *num_found)
1726 {
1727         u64 found_transid;
1728         struct extent_buffer *leaf;
1729         struct btrfs_ioctl_search_header sh;
1730         unsigned long item_off;
1731         unsigned long item_len;
1732         int nritems;
1733         int i;
1734         int slot;
1735         int ret = 0;
1736
1737         leaf = path->nodes[0];
1738         slot = path->slots[0];
1739         nritems = btrfs_header_nritems(leaf);
1740
1741         if (btrfs_header_generation(leaf) > sk->max_transid) {
1742                 i = nritems;
1743                 goto advance_key;
1744         }
1745         found_transid = btrfs_header_generation(leaf);
1746
1747         for (i = slot; i < nritems; i++) {
1748                 item_off = btrfs_item_ptr_offset(leaf, i);
1749                 item_len = btrfs_item_size_nr(leaf, i);
1750
1751                 if (item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
1752                         item_len = 0;
1753
1754                 if (sizeof(sh) + item_len + *sk_offset >
1755                     BTRFS_SEARCH_ARGS_BUFSIZE) {
1756                         ret = 1;
1757                         goto overflow;
1758                 }
1759
1760                 btrfs_item_key_to_cpu(leaf, key, i);
1761                 if (!key_in_sk(key, sk))
1762                         continue;
1763
1764                 sh.objectid = key->objectid;
1765                 sh.offset = key->offset;
1766                 sh.type = key->type;
1767                 sh.len = item_len;
1768                 sh.transid = found_transid;
1769
1770                 /* copy search result header */
1771                 memcpy(buf + *sk_offset, &sh, sizeof(sh));
1772                 *sk_offset += sizeof(sh);
1773
1774                 if (item_len) {
1775                         char *p = buf + *sk_offset;
1776                         /* copy the item */
1777                         read_extent_buffer(leaf, p,
1778                                            item_off, item_len);
1779                         *sk_offset += item_len;
1780                 }
1781                 (*num_found)++;
1782
1783                 if (*num_found >= sk->nr_items)
1784                         break;
1785         }
1786 advance_key:
1787         ret = 0;
1788         if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1789                 key->offset++;
1790         else if (key->type < (u8)-1 && key->type < sk->max_type) {
1791                 key->offset = 0;
1792                 key->type++;
1793         } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1794                 key->offset = 0;
1795                 key->type = 0;
1796                 key->objectid++;
1797         } else
1798                 ret = 1;
1799 overflow:
1800         return ret;
1801 }
1802
1803 static noinline int search_ioctl(struct inode *inode,
1804                                  struct btrfs_ioctl_search_args *args)
1805 {
1806         struct btrfs_root *root;
1807         struct btrfs_key key;
1808         struct btrfs_key max_key;
1809         struct btrfs_path *path;
1810         struct btrfs_ioctl_search_key *sk = &args->key;
1811         struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1812         int ret;
1813         int num_found = 0;
1814         unsigned long sk_offset = 0;
1815
1816         path = btrfs_alloc_path();
1817         if (!path)
1818                 return -ENOMEM;
1819
1820         if (sk->tree_id == 0) {
1821                 /* search the root of the inode that was passed */
1822                 root = BTRFS_I(inode)->root;
1823         } else {
1824                 key.objectid = sk->tree_id;
1825                 key.type = BTRFS_ROOT_ITEM_KEY;
1826                 key.offset = (u64)-1;
1827                 root = btrfs_read_fs_root_no_name(info, &key);
1828                 if (IS_ERR(root)) {
1829                         printk(KERN_ERR "could not find root %llu\n",
1830                                sk->tree_id);
1831                         btrfs_free_path(path);
1832                         return -ENOENT;
1833                 }
1834         }
1835
1836         key.objectid = sk->min_objectid;
1837         key.type = sk->min_type;
1838         key.offset = sk->min_offset;
1839
1840         max_key.objectid = sk->max_objectid;
1841         max_key.type = sk->max_type;
1842         max_key.offset = sk->max_offset;
1843
1844         path->keep_locks = 1;
1845
1846         while(1) {
1847                 ret = btrfs_search_forward(root, &key, &max_key, path, 0,
1848                                            sk->min_transid);
1849                 if (ret != 0) {
1850                         if (ret > 0)
1851                                 ret = 0;
1852                         goto err;
1853                 }
1854                 ret = copy_to_sk(root, path, &key, sk, args->buf,
1855                                  &sk_offset, &num_found);
1856                 btrfs_release_path(path);
1857                 if (ret || num_found >= sk->nr_items)
1858                         break;
1859
1860         }
1861         ret = 0;
1862 err:
1863         sk->nr_items = num_found;
1864         btrfs_free_path(path);
1865         return ret;
1866 }
1867
1868 static noinline int btrfs_ioctl_tree_search(struct file *file,
1869                                            void __user *argp)
1870 {
1871          struct btrfs_ioctl_search_args *args;
1872          struct inode *inode;
1873          int ret;
1874
1875         if (!capable(CAP_SYS_ADMIN))
1876                 return -EPERM;
1877
1878         args = memdup_user(argp, sizeof(*args));
1879         if (IS_ERR(args))
1880                 return PTR_ERR(args);
1881
1882         inode = fdentry(file)->d_inode;
1883         ret = search_ioctl(inode, args);
1884         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1885                 ret = -EFAULT;
1886         kfree(args);
1887         return ret;
1888 }
1889
1890 /*
1891  * Search INODE_REFs to identify path name of 'dirid' directory
1892  * in a 'tree_id' tree. and sets path name to 'name'.
1893  */
1894 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
1895                                 u64 tree_id, u64 dirid, char *name)
1896 {
1897         struct btrfs_root *root;
1898         struct btrfs_key key;
1899         char *ptr;
1900         int ret = -1;
1901         int slot;
1902         int len;
1903         int total_len = 0;
1904         struct btrfs_inode_ref *iref;
1905         struct extent_buffer *l;
1906         struct btrfs_path *path;
1907
1908         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
1909                 name[0]='\0';
1910                 return 0;
1911         }
1912
1913         path = btrfs_alloc_path();
1914         if (!path)
1915                 return -ENOMEM;
1916
1917         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
1918
1919         key.objectid = tree_id;
1920         key.type = BTRFS_ROOT_ITEM_KEY;
1921         key.offset = (u64)-1;
1922         root = btrfs_read_fs_root_no_name(info, &key);
1923         if (IS_ERR(root)) {
1924                 printk(KERN_ERR "could not find root %llu\n", tree_id);
1925                 ret = -ENOENT;
1926                 goto out;
1927         }
1928
1929         key.objectid = dirid;
1930         key.type = BTRFS_INODE_REF_KEY;
1931         key.offset = (u64)-1;
1932
1933         while(1) {
1934                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1935                 if (ret < 0)
1936                         goto out;
1937
1938                 l = path->nodes[0];
1939                 slot = path->slots[0];
1940                 if (ret > 0 && slot > 0)
1941                         slot--;
1942                 btrfs_item_key_to_cpu(l, &key, slot);
1943
1944                 if (ret > 0 && (key.objectid != dirid ||
1945                                 key.type != BTRFS_INODE_REF_KEY)) {
1946                         ret = -ENOENT;
1947                         goto out;
1948                 }
1949
1950                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
1951                 len = btrfs_inode_ref_name_len(l, iref);
1952                 ptr -= len + 1;
1953                 total_len += len + 1;
1954                 if (ptr < name)
1955                         goto out;
1956
1957                 *(ptr + len) = '/';
1958                 read_extent_buffer(l, ptr,(unsigned long)(iref + 1), len);
1959
1960                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
1961                         break;
1962
1963                 btrfs_release_path(path);
1964                 key.objectid = key.offset;
1965                 key.offset = (u64)-1;
1966                 dirid = key.objectid;
1967         }
1968         if (ptr < name)
1969                 goto out;
1970         memmove(name, ptr, total_len);
1971         name[total_len]='\0';
1972         ret = 0;
1973 out:
1974         btrfs_free_path(path);
1975         return ret;
1976 }
1977
1978 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
1979                                            void __user *argp)
1980 {
1981          struct btrfs_ioctl_ino_lookup_args *args;
1982          struct inode *inode;
1983          int ret;
1984
1985         if (!capable(CAP_SYS_ADMIN))
1986                 return -EPERM;
1987
1988         args = memdup_user(argp, sizeof(*args));
1989         if (IS_ERR(args))
1990                 return PTR_ERR(args);
1991
1992         inode = fdentry(file)->d_inode;
1993
1994         if (args->treeid == 0)
1995                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
1996
1997         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
1998                                         args->treeid, args->objectid,
1999                                         args->name);
2000
2001         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2002                 ret = -EFAULT;
2003
2004         kfree(args);
2005         return ret;
2006 }
2007
2008 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2009                                              void __user *arg)
2010 {
2011         struct dentry *parent = fdentry(file);
2012         struct dentry *dentry;
2013         struct inode *dir = parent->d_inode;
2014         struct inode *inode;
2015         struct btrfs_root *root = BTRFS_I(dir)->root;
2016         struct btrfs_root *dest = NULL;
2017         struct btrfs_ioctl_vol_args *vol_args;
2018         struct btrfs_trans_handle *trans;
2019         int namelen;
2020         int ret;
2021         int err = 0;
2022
2023         vol_args = memdup_user(arg, sizeof(*vol_args));
2024         if (IS_ERR(vol_args))
2025                 return PTR_ERR(vol_args);
2026
2027         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2028         namelen = strlen(vol_args->name);
2029         if (strchr(vol_args->name, '/') ||
2030             strncmp(vol_args->name, "..", namelen) == 0) {
2031                 err = -EINVAL;
2032                 goto out;
2033         }
2034
2035         err = mnt_want_write_file(file);
2036         if (err)
2037                 goto out;
2038
2039         mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
2040         dentry = lookup_one_len(vol_args->name, parent, namelen);
2041         if (IS_ERR(dentry)) {
2042                 err = PTR_ERR(dentry);
2043                 goto out_unlock_dir;
2044         }
2045
2046         if (!dentry->d_inode) {
2047                 err = -ENOENT;
2048                 goto out_dput;
2049         }
2050
2051         inode = dentry->d_inode;
2052         dest = BTRFS_I(inode)->root;
2053         if (!capable(CAP_SYS_ADMIN)){
2054                 /*
2055                  * Regular user.  Only allow this with a special mount
2056                  * option, when the user has write+exec access to the
2057                  * subvol root, and when rmdir(2) would have been
2058                  * allowed.
2059                  *
2060                  * Note that this is _not_ check that the subvol is
2061                  * empty or doesn't contain data that we wouldn't
2062                  * otherwise be able to delete.
2063                  *
2064                  * Users who want to delete empty subvols should try
2065                  * rmdir(2).
2066                  */
2067                 err = -EPERM;
2068                 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2069                         goto out_dput;
2070
2071                 /*
2072                  * Do not allow deletion if the parent dir is the same
2073                  * as the dir to be deleted.  That means the ioctl
2074                  * must be called on the dentry referencing the root
2075                  * of the subvol, not a random directory contained
2076                  * within it.
2077                  */
2078                 err = -EINVAL;
2079                 if (root == dest)
2080                         goto out_dput;
2081
2082                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2083                 if (err)
2084                         goto out_dput;
2085
2086                 /* check if subvolume may be deleted by a non-root user */
2087                 err = btrfs_may_delete(dir, dentry, 1);
2088                 if (err)
2089                         goto out_dput;
2090         }
2091
2092         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2093                 err = -EINVAL;
2094                 goto out_dput;
2095         }
2096
2097         mutex_lock(&inode->i_mutex);
2098         err = d_invalidate(dentry);
2099         if (err)
2100                 goto out_unlock;
2101
2102         down_write(&root->fs_info->subvol_sem);
2103
2104         err = may_destroy_subvol(dest);
2105         if (err)
2106                 goto out_up_write;
2107
2108         trans = btrfs_start_transaction(root, 0);
2109         if (IS_ERR(trans)) {
2110                 err = PTR_ERR(trans);
2111                 goto out_up_write;
2112         }
2113         trans->block_rsv = &root->fs_info->global_block_rsv;
2114
2115         ret = btrfs_unlink_subvol(trans, root, dir,
2116                                 dest->root_key.objectid,
2117                                 dentry->d_name.name,
2118                                 dentry->d_name.len);
2119         if (ret) {
2120                 err = ret;
2121                 btrfs_abort_transaction(trans, root, ret);
2122                 goto out_end_trans;
2123         }
2124
2125         btrfs_record_root_in_trans(trans, dest);
2126
2127         memset(&dest->root_item.drop_progress, 0,
2128                 sizeof(dest->root_item.drop_progress));
2129         dest->root_item.drop_level = 0;
2130         btrfs_set_root_refs(&dest->root_item, 0);
2131
2132         if (!xchg(&dest->orphan_item_inserted, 1)) {
2133                 ret = btrfs_insert_orphan_item(trans,
2134                                         root->fs_info->tree_root,
2135                                         dest->root_key.objectid);
2136                 if (ret) {
2137                         btrfs_abort_transaction(trans, root, ret);
2138                         err = ret;
2139                         goto out_end_trans;
2140                 }
2141         }
2142 out_end_trans:
2143         ret = btrfs_end_transaction(trans, root);
2144         if (ret && !err)
2145                 err = ret;
2146         inode->i_flags |= S_DEAD;
2147 out_up_write:
2148         up_write(&root->fs_info->subvol_sem);
2149 out_unlock:
2150         mutex_unlock(&inode->i_mutex);
2151         if (!err) {
2152                 shrink_dcache_sb(root->fs_info->sb);
2153                 btrfs_invalidate_inodes(dest);
2154                 d_delete(dentry);
2155         }
2156 out_dput:
2157         dput(dentry);
2158 out_unlock_dir:
2159         mutex_unlock(&dir->i_mutex);
2160         mnt_drop_write_file(file);
2161 out:
2162         kfree(vol_args);
2163         return err;
2164 }
2165
2166 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2167 {
2168         struct inode *inode = fdentry(file)->d_inode;
2169         struct btrfs_root *root = BTRFS_I(inode)->root;
2170         struct btrfs_ioctl_defrag_range_args *range;
2171         int ret;
2172
2173         if (btrfs_root_readonly(root))
2174                 return -EROFS;
2175
2176         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2177                         1)) {
2178                 pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n");
2179                 return -EINPROGRESS;
2180         }
2181         ret = mnt_want_write_file(file);
2182         if (ret) {
2183                 atomic_set(&root->fs_info->mutually_exclusive_operation_running,
2184                            0);
2185                 return ret;
2186         }
2187
2188         switch (inode->i_mode & S_IFMT) {
2189         case S_IFDIR:
2190                 if (!capable(CAP_SYS_ADMIN)) {
2191                         ret = -EPERM;
2192                         goto out;
2193                 }
2194                 ret = btrfs_defrag_root(root, 0);
2195                 if (ret)
2196                         goto out;
2197                 ret = btrfs_defrag_root(root->fs_info->extent_root, 0);
2198                 break;
2199         case S_IFREG:
2200                 if (!(file->f_mode & FMODE_WRITE)) {
2201                         ret = -EINVAL;
2202                         goto out;
2203                 }
2204
2205                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2206                 if (!range) {
2207                         ret = -ENOMEM;
2208                         goto out;
2209                 }
2210
2211                 if (argp) {
2212                         if (copy_from_user(range, argp,
2213                                            sizeof(*range))) {
2214                                 ret = -EFAULT;
2215                                 kfree(range);
2216                                 goto out;
2217                         }
2218                         /* compression requires us to start the IO */
2219                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2220                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2221                                 range->extent_thresh = (u32)-1;
2222                         }
2223                 } else {
2224                         /* the rest are all set to zero by kzalloc */
2225                         range->len = (u64)-1;
2226                 }
2227                 ret = btrfs_defrag_file(fdentry(file)->d_inode, file,
2228                                         range, 0, 0);
2229                 if (ret > 0)
2230                         ret = 0;
2231                 kfree(range);
2232                 break;
2233         default:
2234                 ret = -EINVAL;
2235         }
2236 out:
2237         mnt_drop_write_file(file);
2238         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2239         return ret;
2240 }
2241
2242 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2243 {
2244         struct btrfs_ioctl_vol_args *vol_args;
2245         int ret;
2246
2247         if (!capable(CAP_SYS_ADMIN))
2248                 return -EPERM;
2249
2250         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2251                         1)) {
2252                 pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n");
2253                 return -EINPROGRESS;
2254         }
2255
2256         mutex_lock(&root->fs_info->volume_mutex);
2257         vol_args = memdup_user(arg, sizeof(*vol_args));
2258         if (IS_ERR(vol_args)) {
2259                 ret = PTR_ERR(vol_args);
2260                 goto out;
2261         }
2262
2263         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2264         ret = btrfs_init_new_device(root, vol_args->name);
2265
2266         kfree(vol_args);
2267 out:
2268         mutex_unlock(&root->fs_info->volume_mutex);
2269         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2270         return ret;
2271 }
2272
2273 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2274 {
2275         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
2276         struct btrfs_ioctl_vol_args *vol_args;
2277         int ret;
2278
2279         if (!capable(CAP_SYS_ADMIN))
2280                 return -EPERM;
2281
2282         ret = mnt_want_write_file(file);
2283         if (ret)
2284                 return ret;
2285
2286         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2287                         1)) {
2288                 pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n");
2289                 mnt_drop_write_file(file);
2290                 return -EINPROGRESS;
2291         }
2292
2293         mutex_lock(&root->fs_info->volume_mutex);
2294         vol_args = memdup_user(arg, sizeof(*vol_args));
2295         if (IS_ERR(vol_args)) {
2296                 ret = PTR_ERR(vol_args);
2297                 goto out;
2298         }
2299
2300         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2301         ret = btrfs_rm_device(root, vol_args->name);
2302
2303         kfree(vol_args);
2304 out:
2305         mutex_unlock(&root->fs_info->volume_mutex);
2306         mnt_drop_write_file(file);
2307         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2308         return ret;
2309 }
2310
2311 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2312 {
2313         struct btrfs_ioctl_fs_info_args *fi_args;
2314         struct btrfs_device *device;
2315         struct btrfs_device *next;
2316         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2317         int ret = 0;
2318
2319         if (!capable(CAP_SYS_ADMIN))
2320                 return -EPERM;
2321
2322         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2323         if (!fi_args)
2324                 return -ENOMEM;
2325
2326         fi_args->num_devices = fs_devices->num_devices;
2327         memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2328
2329         mutex_lock(&fs_devices->device_list_mutex);
2330         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2331                 if (device->devid > fi_args->max_id)
2332                         fi_args->max_id = device->devid;
2333         }
2334         mutex_unlock(&fs_devices->device_list_mutex);
2335
2336         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2337                 ret = -EFAULT;
2338
2339         kfree(fi_args);
2340         return ret;
2341 }
2342
2343 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2344 {
2345         struct btrfs_ioctl_dev_info_args *di_args;
2346         struct btrfs_device *dev;
2347         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2348         int ret = 0;
2349         char *s_uuid = NULL;
2350         char empty_uuid[BTRFS_UUID_SIZE] = {0};
2351
2352         if (!capable(CAP_SYS_ADMIN))
2353                 return -EPERM;
2354
2355         di_args = memdup_user(arg, sizeof(*di_args));
2356         if (IS_ERR(di_args))
2357                 return PTR_ERR(di_args);
2358
2359         if (memcmp(empty_uuid, di_args->uuid, BTRFS_UUID_SIZE) != 0)
2360                 s_uuid = di_args->uuid;
2361
2362         mutex_lock(&fs_devices->device_list_mutex);
2363         dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2364         mutex_unlock(&fs_devices->device_list_mutex);
2365
2366         if (!dev) {
2367                 ret = -ENODEV;
2368                 goto out;
2369         }
2370
2371         di_args->devid = dev->devid;
2372         di_args->bytes_used = dev->bytes_used;
2373         di_args->total_bytes = dev->total_bytes;
2374         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2375         if (dev->name) {
2376                 struct rcu_string *name;
2377
2378                 rcu_read_lock();
2379                 name = rcu_dereference(dev->name);
2380                 strncpy(di_args->path, name->str, sizeof(di_args->path));
2381                 rcu_read_unlock();
2382                 di_args->path[sizeof(di_args->path) - 1] = 0;
2383         } else {
2384                 di_args->path[0] = '\0';
2385         }
2386
2387 out:
2388         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2389                 ret = -EFAULT;
2390
2391         kfree(di_args);
2392         return ret;
2393 }
2394
2395 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
2396                                        u64 off, u64 olen, u64 destoff)
2397 {
2398         struct inode *inode = fdentry(file)->d_inode;
2399         struct btrfs_root *root = BTRFS_I(inode)->root;
2400         struct fd src_file;
2401         struct inode *src;
2402         struct btrfs_trans_handle *trans;
2403         struct btrfs_path *path;
2404         struct extent_buffer *leaf;
2405         char *buf;
2406         struct btrfs_key key;
2407         u32 nritems;
2408         int slot;
2409         int ret;
2410         u64 len = olen;
2411         u64 bs = root->fs_info->sb->s_blocksize;
2412
2413         /*
2414          * TODO:
2415          * - split compressed inline extents.  annoying: we need to
2416          *   decompress into destination's address_space (the file offset
2417          *   may change, so source mapping won't do), then recompress (or
2418          *   otherwise reinsert) a subrange.
2419          * - allow ranges within the same file to be cloned (provided
2420          *   they don't overlap)?
2421          */
2422
2423         /* the destination must be opened for writing */
2424         if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
2425                 return -EINVAL;
2426
2427         if (btrfs_root_readonly(root))
2428                 return -EROFS;
2429
2430         ret = mnt_want_write_file(file);
2431         if (ret)
2432                 return ret;
2433
2434         src_file = fdget(srcfd);
2435         if (!src_file.file) {
2436                 ret = -EBADF;
2437                 goto out_drop_write;
2438         }
2439
2440         ret = -EXDEV;
2441         if (src_file.file->f_path.mnt != file->f_path.mnt)
2442                 goto out_fput;
2443
2444         src = src_file.file->f_dentry->d_inode;
2445
2446         ret = -EINVAL;
2447         if (src == inode)
2448                 goto out_fput;
2449
2450         /* the src must be open for reading */
2451         if (!(src_file.file->f_mode & FMODE_READ))
2452                 goto out_fput;
2453
2454         /* don't make the dst file partly checksummed */
2455         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2456             (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
2457                 goto out_fput;
2458
2459         ret = -EISDIR;
2460         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
2461                 goto out_fput;
2462
2463         ret = -EXDEV;
2464         if (src->i_sb != inode->i_sb)
2465                 goto out_fput;
2466
2467         ret = -ENOMEM;
2468         buf = vmalloc(btrfs_level_size(root, 0));
2469         if (!buf)
2470                 goto out_fput;
2471
2472         path = btrfs_alloc_path();
2473         if (!path) {
2474                 vfree(buf);
2475                 goto out_fput;
2476         }
2477         path->reada = 2;
2478
2479         if (inode < src) {
2480                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
2481                 mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
2482         } else {
2483                 mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
2484                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2485         }
2486
2487         /* determine range to clone */
2488         ret = -EINVAL;
2489         if (off + len > src->i_size || off + len < off)
2490                 goto out_unlock;
2491         if (len == 0)
2492                 olen = len = src->i_size - off;
2493         /* if we extend to eof, continue to block boundary */
2494         if (off + len == src->i_size)
2495                 len = ALIGN(src->i_size, bs) - off;
2496
2497         /* verify the end result is block aligned */
2498         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
2499             !IS_ALIGNED(destoff, bs))
2500                 goto out_unlock;
2501
2502         if (destoff > inode->i_size) {
2503                 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
2504                 if (ret)
2505                         goto out_unlock;
2506         }
2507
2508         /* truncate page cache pages from target inode range */
2509         truncate_inode_pages_range(&inode->i_data, destoff,
2510                                    PAGE_CACHE_ALIGN(destoff + len) - 1);
2511
2512         /* do any pending delalloc/csum calc on src, one way or
2513            another, and lock file content */
2514         while (1) {
2515                 struct btrfs_ordered_extent *ordered;
2516                 lock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
2517                 ordered = btrfs_lookup_first_ordered_extent(src, off + len - 1);
2518                 if (!ordered &&
2519                     !test_range_bit(&BTRFS_I(src)->io_tree, off, off + len - 1,
2520                                     EXTENT_DELALLOC, 0, NULL))
2521                         break;
2522                 unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
2523                 if (ordered)
2524                         btrfs_put_ordered_extent(ordered);
2525                 btrfs_wait_ordered_range(src, off, len);
2526         }
2527
2528         /* clone data */
2529         key.objectid = btrfs_ino(src);
2530         key.type = BTRFS_EXTENT_DATA_KEY;
2531         key.offset = 0;
2532
2533         while (1) {
2534                 /*
2535                  * note the key will change type as we walk through the
2536                  * tree.
2537                  */
2538                 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
2539                                 0, 0);
2540                 if (ret < 0)
2541                         goto out;
2542
2543                 nritems = btrfs_header_nritems(path->nodes[0]);
2544                 if (path->slots[0] >= nritems) {
2545                         ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
2546                         if (ret < 0)
2547                                 goto out;
2548                         if (ret > 0)
2549                                 break;
2550                         nritems = btrfs_header_nritems(path->nodes[0]);
2551                 }
2552                 leaf = path->nodes[0];
2553                 slot = path->slots[0];
2554
2555                 btrfs_item_key_to_cpu(leaf, &key, slot);
2556                 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
2557                     key.objectid != btrfs_ino(src))
2558                         break;
2559
2560                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
2561                         struct btrfs_file_extent_item *extent;
2562                         int type;
2563                         u32 size;
2564                         struct btrfs_key new_key;
2565                         u64 disko = 0, diskl = 0;
2566                         u64 datao = 0, datal = 0;
2567                         u8 comp;
2568                         u64 endoff;
2569
2570                         size = btrfs_item_size_nr(leaf, slot);
2571                         read_extent_buffer(leaf, buf,
2572                                            btrfs_item_ptr_offset(leaf, slot),
2573                                            size);
2574
2575                         extent = btrfs_item_ptr(leaf, slot,
2576                                                 struct btrfs_file_extent_item);
2577                         comp = btrfs_file_extent_compression(leaf, extent);
2578                         type = btrfs_file_extent_type(leaf, extent);
2579                         if (type == BTRFS_FILE_EXTENT_REG ||
2580                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2581                                 disko = btrfs_file_extent_disk_bytenr(leaf,
2582                                                                       extent);
2583                                 diskl = btrfs_file_extent_disk_num_bytes(leaf,
2584                                                                  extent);
2585                                 datao = btrfs_file_extent_offset(leaf, extent);
2586                                 datal = btrfs_file_extent_num_bytes(leaf,
2587                                                                     extent);
2588                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2589                                 /* take upper bound, may be compressed */
2590                                 datal = btrfs_file_extent_ram_bytes(leaf,
2591                                                                     extent);
2592                         }
2593                         btrfs_release_path(path);
2594
2595                         if (key.offset + datal <= off ||
2596                             key.offset >= off + len - 1)
2597                                 goto next;
2598
2599                         memcpy(&new_key, &key, sizeof(new_key));
2600                         new_key.objectid = btrfs_ino(inode);
2601                         if (off <= key.offset)
2602                                 new_key.offset = key.offset + destoff - off;
2603                         else
2604                                 new_key.offset = destoff;
2605
2606                         /*
2607                          * 1 - adjusting old extent (we may have to split it)
2608                          * 1 - add new extent
2609                          * 1 - inode update
2610                          */
2611                         trans = btrfs_start_transaction(root, 3);
2612                         if (IS_ERR(trans)) {
2613                                 ret = PTR_ERR(trans);
2614                                 goto out;
2615                         }
2616
2617                         if (type == BTRFS_FILE_EXTENT_REG ||
2618                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2619                                 /*
2620                                  *    a  | --- range to clone ---|  b
2621                                  * | ------------- extent ------------- |
2622                                  */
2623
2624                                 /* substract range b */
2625                                 if (key.offset + datal > off + len)
2626                                         datal = off + len - key.offset;
2627
2628                                 /* substract range a */
2629                                 if (off > key.offset) {
2630                                         datao += off - key.offset;
2631                                         datal -= off - key.offset;
2632                                 }
2633
2634                                 ret = btrfs_drop_extents(trans, root, inode,
2635                                                          new_key.offset,
2636                                                          new_key.offset + datal,
2637                                                          1);
2638                                 if (ret) {
2639                                         btrfs_abort_transaction(trans, root,
2640                                                                 ret);
2641                                         btrfs_end_transaction(trans, root);
2642                                         goto out;
2643                                 }
2644
2645                                 ret = btrfs_insert_empty_item(trans, root, path,
2646                                                               &new_key, size);
2647                                 if (ret) {
2648                                         btrfs_abort_transaction(trans, root,
2649                                                                 ret);
2650                                         btrfs_end_transaction(trans, root);
2651                                         goto out;
2652                                 }
2653
2654                                 leaf = path->nodes[0];
2655                                 slot = path->slots[0];
2656                                 write_extent_buffer(leaf, buf,
2657                                             btrfs_item_ptr_offset(leaf, slot),
2658                                             size);
2659
2660                                 extent = btrfs_item_ptr(leaf, slot,
2661                                                 struct btrfs_file_extent_item);
2662
2663                                 /* disko == 0 means it's a hole */
2664                                 if (!disko)
2665                                         datao = 0;
2666
2667                                 btrfs_set_file_extent_offset(leaf, extent,
2668                                                              datao);
2669                                 btrfs_set_file_extent_num_bytes(leaf, extent,
2670                                                                 datal);
2671                                 if (disko) {
2672                                         inode_add_bytes(inode, datal);
2673                                         ret = btrfs_inc_extent_ref(trans, root,
2674                                                         disko, diskl, 0,
2675                                                         root->root_key.objectid,
2676                                                         btrfs_ino(inode),
2677                                                         new_key.offset - datao,
2678                                                         0);
2679                                         if (ret) {
2680                                                 btrfs_abort_transaction(trans,
2681                                                                         root,
2682                                                                         ret);
2683                                                 btrfs_end_transaction(trans,
2684                                                                       root);
2685                                                 goto out;
2686
2687                                         }
2688                                 }
2689                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2690                                 u64 skip = 0;
2691                                 u64 trim = 0;
2692                                 if (off > key.offset) {
2693                                         skip = off - key.offset;
2694                                         new_key.offset += skip;
2695                                 }
2696
2697                                 if (key.offset + datal > off + len)
2698                                         trim = key.offset + datal - (off + len);
2699
2700                                 if (comp && (skip || trim)) {
2701                                         ret = -EINVAL;
2702                                         btrfs_end_transaction(trans, root);
2703                                         goto out;
2704                                 }
2705                                 size -= skip + trim;
2706                                 datal -= skip + trim;
2707
2708                                 ret = btrfs_drop_extents(trans, root, inode,
2709                                                          new_key.offset,
2710                                                          new_key.offset + datal,
2711                                                          1);
2712                                 if (ret) {
2713                                         btrfs_abort_transaction(trans, root,
2714                                                                 ret);
2715                                         btrfs_end_transaction(trans, root);
2716                                         goto out;
2717                                 }
2718
2719                                 ret = btrfs_insert_empty_item(trans, root, path,
2720                                                               &new_key, size);
2721                                 if (ret) {
2722                                         btrfs_abort_transaction(trans, root,
2723                                                                 ret);
2724                                         btrfs_end_transaction(trans, root);
2725                                         goto out;
2726                                 }
2727
2728                                 if (skip) {
2729                                         u32 start =
2730                                           btrfs_file_extent_calc_inline_size(0);
2731                                         memmove(buf+start, buf+start+skip,
2732                                                 datal);
2733                                 }
2734
2735                                 leaf = path->nodes[0];
2736                                 slot = path->slots[0];
2737                                 write_extent_buffer(leaf, buf,
2738                                             btrfs_item_ptr_offset(leaf, slot),
2739                                             size);
2740                                 inode_add_bytes(inode, datal);
2741                         }
2742
2743                         btrfs_mark_buffer_dirty(leaf);
2744                         btrfs_release_path(path);
2745
2746                         inode_inc_iversion(inode);
2747                         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
2748
2749                         /*
2750                          * we round up to the block size at eof when
2751                          * determining which extents to clone above,
2752                          * but shouldn't round up the file size
2753                          */
2754                         endoff = new_key.offset + datal;
2755                         if (endoff > destoff+olen)
2756                                 endoff = destoff+olen;
2757                         if (endoff > inode->i_size)
2758                                 btrfs_i_size_write(inode, endoff);
2759
2760                         ret = btrfs_update_inode(trans, root, inode);
2761                         if (ret) {
2762                                 btrfs_abort_transaction(trans, root, ret);
2763                                 btrfs_end_transaction(trans, root);
2764                                 goto out;
2765                         }
2766                         ret = btrfs_end_transaction(trans, root);
2767                 }
2768 next:
2769                 btrfs_release_path(path);
2770                 key.offset++;
2771         }
2772         ret = 0;
2773 out:
2774         btrfs_release_path(path);
2775         unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
2776 out_unlock:
2777         mutex_unlock(&src->i_mutex);
2778         mutex_unlock(&inode->i_mutex);
2779         vfree(buf);
2780         btrfs_free_path(path);
2781 out_fput:
2782         fdput(src_file);
2783 out_drop_write:
2784         mnt_drop_write_file(file);
2785         return ret;
2786 }
2787
2788 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
2789 {
2790         struct btrfs_ioctl_clone_range_args args;
2791
2792         if (copy_from_user(&args, argp, sizeof(args)))
2793                 return -EFAULT;
2794         return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
2795                                  args.src_length, args.dest_offset);
2796 }
2797
2798 /*
2799  * there are many ways the trans_start and trans_end ioctls can lead
2800  * to deadlocks.  They should only be used by applications that
2801  * basically own the machine, and have a very in depth understanding
2802  * of all the possible deadlocks and enospc problems.
2803  */
2804 static long btrfs_ioctl_trans_start(struct file *file)
2805 {
2806         struct inode *inode = fdentry(file)->d_inode;
2807         struct btrfs_root *root = BTRFS_I(inode)->root;
2808         struct btrfs_trans_handle *trans;
2809         int ret;
2810
2811         ret = -EPERM;
2812         if (!capable(CAP_SYS_ADMIN))
2813                 goto out;
2814
2815         ret = -EINPROGRESS;
2816         if (file->private_data)
2817                 goto out;
2818
2819         ret = -EROFS;
2820         if (btrfs_root_readonly(root))
2821                 goto out;
2822
2823         ret = mnt_want_write_file(file);
2824         if (ret)
2825                 goto out;
2826
2827         atomic_inc(&root->fs_info->open_ioctl_trans);
2828
2829         ret = -ENOMEM;
2830         trans = btrfs_start_ioctl_transaction(root);
2831         if (IS_ERR(trans))
2832                 goto out_drop;
2833
2834         file->private_data = trans;
2835         return 0;
2836
2837 out_drop:
2838         atomic_dec(&root->fs_info->open_ioctl_trans);
2839         mnt_drop_write_file(file);
2840 out:
2841         return ret;
2842 }
2843
2844 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
2845 {
2846         struct inode *inode = fdentry(file)->d_inode;
2847         struct btrfs_root *root = BTRFS_I(inode)->root;
2848         struct btrfs_root *new_root;
2849         struct btrfs_dir_item *di;
2850         struct btrfs_trans_handle *trans;
2851         struct btrfs_path *path;
2852         struct btrfs_key location;
2853         struct btrfs_disk_key disk_key;
2854         u64 objectid = 0;
2855         u64 dir_id;
2856         int ret;
2857
2858         if (!capable(CAP_SYS_ADMIN))
2859                 return -EPERM;
2860
2861         ret = mnt_want_write_file(file);
2862         if (ret)
2863                 return ret;
2864
2865         if (copy_from_user(&objectid, argp, sizeof(objectid))) {
2866                 ret = -EFAULT;
2867                 goto out;
2868         }
2869
2870         if (!objectid)
2871                 objectid = root->root_key.objectid;
2872
2873         location.objectid = objectid;
2874         location.type = BTRFS_ROOT_ITEM_KEY;
2875         location.offset = (u64)-1;
2876
2877         new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
2878         if (IS_ERR(new_root)) {
2879                 ret = PTR_ERR(new_root);
2880                 goto out;
2881         }
2882
2883         if (btrfs_root_refs(&new_root->root_item) == 0) {
2884                 ret = -ENOENT;
2885                 goto out;
2886         }
2887
2888         path = btrfs_alloc_path();
2889         if (!path) {
2890                 ret = -ENOMEM;
2891                 goto out;
2892         }
2893         path->leave_spinning = 1;
2894
2895         trans = btrfs_start_transaction(root, 1);
2896         if (IS_ERR(trans)) {
2897                 btrfs_free_path(path);
2898                 ret = PTR_ERR(trans);
2899                 goto out;
2900         }
2901
2902         dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
2903         di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
2904                                    dir_id, "default", 7, 1);
2905         if (IS_ERR_OR_NULL(di)) {
2906                 btrfs_free_path(path);
2907                 btrfs_end_transaction(trans, root);
2908                 printk(KERN_ERR "Umm, you don't have the default dir item, "
2909                        "this isn't going to work\n");
2910                 ret = -ENOENT;
2911                 goto out;
2912         }
2913
2914         btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
2915         btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
2916         btrfs_mark_buffer_dirty(path->nodes[0]);
2917         btrfs_free_path(path);
2918
2919         btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
2920         btrfs_end_transaction(trans, root);
2921 out:
2922         mnt_drop_write_file(file);
2923         return ret;
2924 }
2925
2926 void btrfs_get_block_group_info(struct list_head *groups_list,
2927                                 struct btrfs_ioctl_space_info *space)
2928 {
2929         struct btrfs_block_group_cache *block_group;
2930
2931         space->total_bytes = 0;
2932         space->used_bytes = 0;
2933         space->flags = 0;
2934         list_for_each_entry(block_group, groups_list, list) {
2935                 space->flags = block_group->flags;
2936                 space->total_bytes += block_group->key.offset;
2937                 space->used_bytes +=
2938                         btrfs_block_group_used(&block_group->item);
2939         }
2940 }
2941
2942 long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
2943 {
2944         struct btrfs_ioctl_space_args space_args;
2945         struct btrfs_ioctl_space_info space;
2946         struct btrfs_ioctl_space_info *dest;
2947         struct btrfs_ioctl_space_info *dest_orig;
2948         struct btrfs_ioctl_space_info __user *user_dest;
2949         struct btrfs_space_info *info;
2950         u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
2951                        BTRFS_BLOCK_GROUP_SYSTEM,
2952                        BTRFS_BLOCK_GROUP_METADATA,
2953                        BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
2954         int num_types = 4;
2955         int alloc_size;
2956         int ret = 0;
2957         u64 slot_count = 0;
2958         int i, c;
2959
2960         if (copy_from_user(&space_args,
2961                            (struct btrfs_ioctl_space_args __user *)arg,
2962                            sizeof(space_args)))
2963                 return -EFAULT;
2964
2965         for (i = 0; i < num_types; i++) {
2966                 struct btrfs_space_info *tmp;
2967
2968                 info = NULL;
2969                 rcu_read_lock();
2970                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
2971                                         list) {
2972                         if (tmp->flags == types[i]) {
2973                                 info = tmp;
2974                                 break;
2975                         }
2976                 }
2977                 rcu_read_unlock();
2978
2979                 if (!info)
2980                         continue;
2981
2982                 down_read(&info->groups_sem);
2983                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
2984                         if (!list_empty(&info->block_groups[c]))
2985                                 slot_count++;
2986                 }
2987                 up_read(&info->groups_sem);
2988         }
2989
2990         /* space_slots == 0 means they are asking for a count */
2991         if (space_args.space_slots == 0) {
2992                 space_args.total_spaces = slot_count;
2993                 goto out;
2994         }
2995
2996         slot_count = min_t(u64, space_args.space_slots, slot_count);
2997
2998         alloc_size = sizeof(*dest) * slot_count;
2999
3000         /* we generally have at most 6 or so space infos, one for each raid
3001          * level.  So, a whole page should be more than enough for everyone
3002          */
3003         if (alloc_size > PAGE_CACHE_SIZE)
3004                 return -ENOMEM;
3005
3006         space_args.total_spaces = 0;
3007         dest = kmalloc(alloc_size, GFP_NOFS);
3008         if (!dest)
3009                 return -ENOMEM;
3010         dest_orig = dest;
3011
3012         /* now we have a buffer to copy into */
3013         for (i = 0; i < num_types; i++) {
3014                 struct btrfs_space_info *tmp;
3015
3016                 if (!slot_count)
3017                         break;
3018
3019                 info = NULL;
3020                 rcu_read_lock();
3021                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3022                                         list) {
3023                         if (tmp->flags == types[i]) {
3024                                 info = tmp;
3025                                 break;
3026                         }
3027                 }
3028                 rcu_read_unlock();
3029
3030                 if (!info)
3031                         continue;
3032                 down_read(&info->groups_sem);
3033                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3034                         if (!list_empty(&info->block_groups[c])) {
3035                                 btrfs_get_block_group_info(
3036                                         &info->block_groups[c], &space);
3037                                 memcpy(dest, &space, sizeof(space));
3038                                 dest++;
3039                                 space_args.total_spaces++;
3040                                 slot_count--;
3041                         }
3042                         if (!slot_count)
3043                                 break;
3044                 }
3045                 up_read(&info->groups_sem);
3046         }
3047
3048         user_dest = (struct btrfs_ioctl_space_info __user *)
3049                 (arg + sizeof(struct btrfs_ioctl_space_args));
3050
3051         if (copy_to_user(user_dest, dest_orig, alloc_size))
3052                 ret = -EFAULT;
3053
3054         kfree(dest_orig);
3055 out:
3056         if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3057                 ret = -EFAULT;
3058
3059         return ret;
3060 }
3061
3062 /*
3063  * there are many ways the trans_start and trans_end ioctls can lead
3064  * to deadlocks.  They should only be used by applications that
3065  * basically own the machine, and have a very in depth understanding
3066  * of all the possible deadlocks and enospc problems.
3067  */
3068 long btrfs_ioctl_trans_end(struct file *file)
3069 {
3070         struct inode *inode = fdentry(file)->d_inode;
3071         struct btrfs_root *root = BTRFS_I(inode)->root;
3072         struct btrfs_trans_handle *trans;
3073
3074         trans = file->private_data;
3075         if (!trans)
3076                 return -EINVAL;
3077         file->private_data = NULL;
3078
3079         btrfs_end_transaction(trans, root);
3080
3081         atomic_dec(&root->fs_info->open_ioctl_trans);
3082
3083         mnt_drop_write_file(file);
3084         return 0;
3085 }
3086
3087 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3088                                             void __user *argp)
3089 {
3090         struct btrfs_trans_handle *trans;
3091         u64 transid;
3092         int ret;
3093
3094         trans = btrfs_attach_transaction(root);
3095         if (IS_ERR(trans)) {
3096                 if (PTR_ERR(trans) != -ENOENT)
3097                         return PTR_ERR(trans);
3098
3099                 /* No running transaction, don't bother */
3100                 transid = root->fs_info->last_trans_committed;
3101                 goto out;
3102         }
3103         transid = trans->transid;
3104         ret = btrfs_commit_transaction_async(trans, root, 0);
3105         if (ret) {
3106                 btrfs_end_transaction(trans, root);
3107                 return ret;
3108         }
3109 out:
3110         if (argp)
3111                 if (copy_to_user(argp, &transid, sizeof(transid)))
3112                         return -EFAULT;
3113         return 0;
3114 }
3115
3116 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
3117                                            void __user *argp)
3118 {
3119         u64 transid;
3120
3121         if (argp) {
3122                 if (copy_from_user(&transid, argp, sizeof(transid)))
3123                         return -EFAULT;
3124         } else {
3125                 transid = 0;  /* current trans */
3126         }
3127         return btrfs_wait_for_commit(root, transid);
3128 }
3129
3130 static long btrfs_ioctl_scrub(struct btrfs_root *root, void __user *arg)
3131 {
3132         int ret;
3133         struct btrfs_ioctl_scrub_args *sa;
3134
3135         if (!capable(CAP_SYS_ADMIN))
3136                 return -EPERM;
3137
3138         sa = memdup_user(arg, sizeof(*sa));
3139         if (IS_ERR(sa))
3140                 return PTR_ERR(sa);
3141
3142         ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
3143                               &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3144                               0);
3145
3146         if (copy_to_user(arg, sa, sizeof(*sa)))
3147                 ret = -EFAULT;
3148
3149         kfree(sa);
3150         return ret;
3151 }
3152
3153 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
3154 {
3155         if (!capable(CAP_SYS_ADMIN))
3156                 return -EPERM;
3157
3158         return btrfs_scrub_cancel(root->fs_info);
3159 }
3160
3161 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
3162                                        void __user *arg)
3163 {
3164         struct btrfs_ioctl_scrub_args *sa;
3165         int ret;
3166
3167         if (!capable(CAP_SYS_ADMIN))
3168                 return -EPERM;
3169
3170         sa = memdup_user(arg, sizeof(*sa));
3171         if (IS_ERR(sa))
3172                 return PTR_ERR(sa);
3173
3174         ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
3175
3176         if (copy_to_user(arg, sa, sizeof(*sa)))
3177                 ret = -EFAULT;
3178
3179         kfree(sa);
3180         return ret;
3181 }
3182
3183 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
3184                                       void __user *arg)
3185 {
3186         struct btrfs_ioctl_get_dev_stats *sa;
3187         int ret;
3188
3189         sa = memdup_user(arg, sizeof(*sa));
3190         if (IS_ERR(sa))
3191                 return PTR_ERR(sa);
3192
3193         if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3194                 kfree(sa);
3195                 return -EPERM;
3196         }
3197
3198         ret = btrfs_get_dev_stats(root, sa);
3199
3200         if (copy_to_user(arg, sa, sizeof(*sa)))
3201                 ret = -EFAULT;
3202
3203         kfree(sa);
3204         return ret;
3205 }
3206
3207 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
3208 {
3209         struct btrfs_ioctl_dev_replace_args *p;
3210         int ret;
3211
3212         if (!capable(CAP_SYS_ADMIN))
3213                 return -EPERM;
3214
3215         p = memdup_user(arg, sizeof(*p));
3216         if (IS_ERR(p))
3217                 return PTR_ERR(p);
3218
3219         switch (p->cmd) {
3220         case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3221                 if (atomic_xchg(
3222                         &root->fs_info->mutually_exclusive_operation_running,
3223                         1)) {
3224                         pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n");
3225                         ret = -EINPROGRESS;
3226                 } else {
3227                         ret = btrfs_dev_replace_start(root, p);
3228                         atomic_set(
3229                          &root->fs_info->mutually_exclusive_operation_running,
3230                          0);
3231                 }
3232                 break;
3233         case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3234                 btrfs_dev_replace_status(root->fs_info, p);
3235                 ret = 0;
3236                 break;
3237         case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3238                 ret = btrfs_dev_replace_cancel(root->fs_info, p);
3239                 break;
3240         default:
3241                 ret = -EINVAL;
3242                 break;
3243         }
3244
3245         if (copy_to_user(arg, p, sizeof(*p)))
3246                 ret = -EFAULT;
3247
3248         kfree(p);
3249         return ret;
3250 }
3251
3252 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3253 {
3254         int ret = 0;
3255         int i;
3256         u64 rel_ptr;
3257         int size;
3258         struct btrfs_ioctl_ino_path_args *ipa = NULL;
3259         struct inode_fs_paths *ipath = NULL;
3260         struct btrfs_path *path;
3261
3262         if (!capable(CAP_SYS_ADMIN))
3263                 return -EPERM;
3264
3265         path = btrfs_alloc_path();
3266         if (!path) {
3267                 ret = -ENOMEM;
3268                 goto out;
3269         }
3270
3271         ipa = memdup_user(arg, sizeof(*ipa));
3272         if (IS_ERR(ipa)) {
3273                 ret = PTR_ERR(ipa);
3274                 ipa = NULL;
3275                 goto out;
3276         }
3277
3278         size = min_t(u32, ipa->size, 4096);
3279         ipath = init_ipath(size, root, path);
3280         if (IS_ERR(ipath)) {
3281                 ret = PTR_ERR(ipath);
3282                 ipath = NULL;
3283                 goto out;
3284         }
3285
3286         ret = paths_from_inode(ipa->inum, ipath);
3287         if (ret < 0)
3288                 goto out;
3289
3290         for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3291                 rel_ptr = ipath->fspath->val[i] -
3292                           (u64)(unsigned long)ipath->fspath->val;
3293                 ipath->fspath->val[i] = rel_ptr;
3294         }
3295
3296         ret = copy_to_user((void *)(unsigned long)ipa->fspath,
3297                            (void *)(unsigned long)ipath->fspath, size);
3298         if (ret) {
3299                 ret = -EFAULT;
3300                 goto out;
3301         }
3302
3303 out:
3304         btrfs_free_path(path);
3305         free_ipath(ipath);
3306         kfree(ipa);
3307
3308         return ret;
3309 }
3310
3311 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3312 {
3313         struct btrfs_data_container *inodes = ctx;
3314         const size_t c = 3 * sizeof(u64);
3315
3316         if (inodes->bytes_left >= c) {
3317                 inodes->bytes_left -= c;
3318                 inodes->val[inodes->elem_cnt] = inum;
3319                 inodes->val[inodes->elem_cnt + 1] = offset;
3320                 inodes->val[inodes->elem_cnt + 2] = root;
3321                 inodes->elem_cnt += 3;
3322         } else {
3323                 inodes->bytes_missing += c - inodes->bytes_left;
3324                 inodes->bytes_left = 0;
3325                 inodes->elem_missed += 3;
3326         }
3327
3328         return 0;
3329 }
3330
3331 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
3332                                         void __user *arg)
3333 {
3334         int ret = 0;
3335         int size;
3336         struct btrfs_ioctl_logical_ino_args *loi;
3337         struct btrfs_data_container *inodes = NULL;
3338         struct btrfs_path *path = NULL;
3339
3340         if (!capable(CAP_SYS_ADMIN))
3341                 return -EPERM;
3342
3343         loi = memdup_user(arg, sizeof(*loi));
3344         if (IS_ERR(loi)) {
3345                 ret = PTR_ERR(loi);
3346                 loi = NULL;
3347                 goto out;
3348         }
3349
3350         path = btrfs_alloc_path();
3351         if (!path) {
3352                 ret = -ENOMEM;
3353                 goto out;
3354         }
3355
3356         size = min_t(u32, loi->size, 64 * 1024);
3357         inodes = init_data_container(size);
3358         if (IS_ERR(inodes)) {
3359                 ret = PTR_ERR(inodes);
3360                 inodes = NULL;
3361                 goto out;
3362         }
3363
3364         ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
3365                                           build_ino_list, inodes);
3366         if (ret == -EINVAL)
3367                 ret = -ENOENT;
3368         if (ret < 0)
3369                 goto out;
3370
3371         ret = copy_to_user((void *)(unsigned long)loi->inodes,
3372                            (void *)(unsigned long)inodes, size);
3373         if (ret)
3374                 ret = -EFAULT;
3375
3376 out:
3377         btrfs_free_path(path);
3378         vfree(inodes);
3379         kfree(loi);
3380
3381         return ret;
3382 }
3383
3384 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
3385                                struct btrfs_ioctl_balance_args *bargs)
3386 {
3387         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3388
3389         bargs->flags = bctl->flags;
3390
3391         if (atomic_read(&fs_info->balance_running))
3392                 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3393         if (atomic_read(&fs_info->balance_pause_req))
3394                 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3395         if (atomic_read(&fs_info->balance_cancel_req))
3396                 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3397
3398         memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3399         memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3400         memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3401
3402         if (lock) {
3403                 spin_lock(&fs_info->balance_lock);
3404                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3405                 spin_unlock(&fs_info->balance_lock);
3406         } else {
3407                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3408         }
3409 }
3410
3411 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3412 {
3413         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
3414         struct btrfs_fs_info *fs_info = root->fs_info;
3415         struct btrfs_ioctl_balance_args *bargs;
3416         struct btrfs_balance_control *bctl;
3417         int ret;
3418         int need_to_clear_lock = 0;
3419
3420         if (!capable(CAP_SYS_ADMIN))
3421                 return -EPERM;
3422
3423         ret = mnt_want_write_file(file);
3424         if (ret)
3425                 return ret;
3426
3427         mutex_lock(&fs_info->volume_mutex);
3428         mutex_lock(&fs_info->balance_mutex);
3429
3430         if (arg) {
3431                 bargs = memdup_user(arg, sizeof(*bargs));
3432                 if (IS_ERR(bargs)) {
3433                         ret = PTR_ERR(bargs);
3434                         goto out;
3435                 }
3436
3437                 if (bargs->flags & BTRFS_BALANCE_RESUME) {
3438                         if (!fs_info->balance_ctl) {
3439                                 ret = -ENOTCONN;
3440                                 goto out_bargs;
3441                         }
3442
3443                         bctl = fs_info->balance_ctl;
3444                         spin_lock(&fs_info->balance_lock);
3445                         bctl->flags |= BTRFS_BALANCE_RESUME;
3446                         spin_unlock(&fs_info->balance_lock);
3447
3448                         goto do_balance;
3449                 }
3450         } else {
3451                 bargs = NULL;
3452         }
3453
3454         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
3455                         1)) {
3456                 pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n");
3457                 ret = -EINPROGRESS;
3458                 goto out_bargs;
3459         }
3460         need_to_clear_lock = 1;
3461
3462         bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3463         if (!bctl) {
3464                 ret = -ENOMEM;
3465                 goto out_bargs;
3466         }
3467
3468         bctl->fs_info = fs_info;
3469         if (arg) {
3470                 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
3471                 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
3472                 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
3473
3474                 bctl->flags = bargs->flags;
3475         } else {
3476                 /* balance everything - no filters */
3477                 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
3478         }
3479
3480 do_balance:
3481         ret = btrfs_balance(bctl, bargs);
3482         /*
3483          * bctl is freed in __cancel_balance or in free_fs_info if
3484          * restriper was paused all the way until unmount
3485          */
3486         if (arg) {
3487                 if (copy_to_user(arg, bargs, sizeof(*bargs)))
3488                         ret = -EFAULT;
3489         }
3490
3491 out_bargs:
3492         kfree(bargs);
3493 out:
3494         if (need_to_clear_lock)
3495                 atomic_set(&root->fs_info->mutually_exclusive_operation_running,
3496                            0);
3497         mutex_unlock(&fs_info->balance_mutex);
3498         mutex_unlock(&fs_info->volume_mutex);
3499         mnt_drop_write_file(file);
3500         return ret;
3501 }
3502
3503 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
3504 {
3505         if (!capable(CAP_SYS_ADMIN))
3506                 return -EPERM;
3507
3508         switch (cmd) {
3509         case BTRFS_BALANCE_CTL_PAUSE:
3510                 return btrfs_pause_balance(root->fs_info);
3511         case BTRFS_BALANCE_CTL_CANCEL:
3512                 return btrfs_cancel_balance(root->fs_info);
3513         }
3514
3515         return -EINVAL;
3516 }
3517
3518 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
3519                                          void __user *arg)
3520 {
3521         struct btrfs_fs_info *fs_info = root->fs_info;
3522         struct btrfs_ioctl_balance_args *bargs;
3523         int ret = 0;
3524
3525         if (!capable(CAP_SYS_ADMIN))
3526                 return -EPERM;
3527
3528         mutex_lock(&fs_info->balance_mutex);
3529         if (!fs_info->balance_ctl) {
3530                 ret = -ENOTCONN;
3531                 goto out;
3532         }
3533
3534         bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
3535         if (!bargs) {
3536                 ret = -ENOMEM;
3537                 goto out;
3538         }
3539
3540         update_ioctl_balance_args(fs_info, 1, bargs);
3541
3542         if (copy_to_user(arg, bargs, sizeof(*bargs)))
3543                 ret = -EFAULT;
3544
3545         kfree(bargs);
3546 out:
3547         mutex_unlock(&fs_info->balance_mutex);
3548         return ret;
3549 }
3550
3551 static long btrfs_ioctl_quota_ctl(struct btrfs_root *root, void __user *arg)
3552 {
3553         struct btrfs_ioctl_quota_ctl_args *sa;
3554         struct btrfs_trans_handle *trans = NULL;
3555         int ret;
3556         int err;
3557
3558         if (!capable(CAP_SYS_ADMIN))
3559                 return -EPERM;
3560
3561         if (root->fs_info->sb->s_flags & MS_RDONLY)
3562                 return -EROFS;
3563
3564         sa = memdup_user(arg, sizeof(*sa));
3565         if (IS_ERR(sa))
3566                 return PTR_ERR(sa);
3567
3568         if (sa->cmd != BTRFS_QUOTA_CTL_RESCAN) {
3569                 trans = btrfs_start_transaction(root, 2);
3570                 if (IS_ERR(trans)) {
3571                         ret = PTR_ERR(trans);
3572                         goto out;
3573                 }
3574         }
3575
3576         switch (sa->cmd) {
3577         case BTRFS_QUOTA_CTL_ENABLE:
3578                 ret = btrfs_quota_enable(trans, root->fs_info);
3579                 break;
3580         case BTRFS_QUOTA_CTL_DISABLE:
3581                 ret = btrfs_quota_disable(trans, root->fs_info);
3582                 break;
3583         case BTRFS_QUOTA_CTL_RESCAN:
3584                 ret = btrfs_quota_rescan(root->fs_info);
3585                 break;
3586         default:
3587                 ret = -EINVAL;
3588                 break;
3589         }
3590
3591         if (copy_to_user(arg, sa, sizeof(*sa)))
3592                 ret = -EFAULT;
3593
3594         if (trans) {
3595                 err = btrfs_commit_transaction(trans, root);
3596                 if (err && !ret)
3597                         ret = err;
3598         }
3599
3600 out:
3601         kfree(sa);
3602         return ret;
3603 }
3604
3605 static long btrfs_ioctl_qgroup_assign(struct btrfs_root *root, void __user *arg)
3606 {
3607         struct btrfs_ioctl_qgroup_assign_args *sa;
3608         struct btrfs_trans_handle *trans;
3609         int ret;
3610         int err;
3611
3612         if (!capable(CAP_SYS_ADMIN))
3613                 return -EPERM;
3614
3615         if (root->fs_info->sb->s_flags & MS_RDONLY)
3616                 return -EROFS;
3617
3618         sa = memdup_user(arg, sizeof(*sa));
3619         if (IS_ERR(sa))
3620                 return PTR_ERR(sa);
3621
3622         trans = btrfs_join_transaction(root);
3623         if (IS_ERR(trans)) {
3624                 ret = PTR_ERR(trans);
3625                 goto out;
3626         }
3627
3628         /* FIXME: check if the IDs really exist */
3629         if (sa->assign) {
3630                 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
3631                                                 sa->src, sa->dst);
3632         } else {
3633                 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
3634                                                 sa->src, sa->dst);
3635         }
3636
3637         err = btrfs_end_transaction(trans, root);
3638         if (err && !ret)
3639                 ret = err;
3640
3641 out:
3642         kfree(sa);
3643         return ret;
3644 }
3645
3646 static long btrfs_ioctl_qgroup_create(struct btrfs_root *root, void __user *arg)
3647 {
3648         struct btrfs_ioctl_qgroup_create_args *sa;
3649         struct btrfs_trans_handle *trans;
3650         int ret;
3651         int err;
3652
3653         if (!capable(CAP_SYS_ADMIN))
3654                 return -EPERM;
3655
3656         if (root->fs_info->sb->s_flags & MS_RDONLY)
3657                 return -EROFS;
3658
3659         sa = memdup_user(arg, sizeof(*sa));
3660         if (IS_ERR(sa))
3661                 return PTR_ERR(sa);
3662
3663         trans = btrfs_join_transaction(root);
3664         if (IS_ERR(trans)) {
3665                 ret = PTR_ERR(trans);
3666                 goto out;
3667         }
3668
3669         /* FIXME: check if the IDs really exist */
3670         if (sa->create) {
3671                 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid,
3672                                           NULL);
3673         } else {
3674                 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
3675         }
3676
3677         err = btrfs_end_transaction(trans, root);
3678         if (err && !ret)
3679                 ret = err;
3680
3681 out:
3682         kfree(sa);
3683         return ret;
3684 }
3685
3686 static long btrfs_ioctl_qgroup_limit(struct btrfs_root *root, void __user *arg)
3687 {
3688         struct btrfs_ioctl_qgroup_limit_args *sa;
3689         struct btrfs_trans_handle *trans;
3690         int ret;
3691         int err;
3692         u64 qgroupid;
3693
3694         if (!capable(CAP_SYS_ADMIN))
3695                 return -EPERM;
3696
3697         if (root->fs_info->sb->s_flags & MS_RDONLY)
3698                 return -EROFS;
3699
3700         sa = memdup_user(arg, sizeof(*sa));
3701         if (IS_ERR(sa))
3702                 return PTR_ERR(sa);
3703
3704         trans = btrfs_join_transaction(root);
3705         if (IS_ERR(trans)) {
3706                 ret = PTR_ERR(trans);
3707                 goto out;
3708         }
3709
3710         qgroupid = sa->qgroupid;
3711         if (!qgroupid) {
3712                 /* take the current subvol as qgroup */
3713                 qgroupid = root->root_key.objectid;
3714         }
3715
3716         /* FIXME: check if the IDs really exist */
3717         ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
3718
3719         err = btrfs_end_transaction(trans, root);
3720         if (err && !ret)
3721                 ret = err;
3722
3723 out:
3724         kfree(sa);
3725         return ret;
3726 }
3727
3728 static long btrfs_ioctl_set_received_subvol(struct file *file,
3729                                             void __user *arg)
3730 {
3731         struct btrfs_ioctl_received_subvol_args *sa = NULL;
3732         struct inode *inode = fdentry(file)->d_inode;
3733         struct btrfs_root *root = BTRFS_I(inode)->root;
3734         struct btrfs_root_item *root_item = &root->root_item;
3735         struct btrfs_trans_handle *trans;
3736         struct timespec ct = CURRENT_TIME;
3737         int ret = 0;
3738
3739         ret = mnt_want_write_file(file);
3740         if (ret < 0)
3741                 return ret;
3742
3743         down_write(&root->fs_info->subvol_sem);
3744
3745         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
3746                 ret = -EINVAL;
3747                 goto out;
3748         }
3749
3750         if (btrfs_root_readonly(root)) {
3751                 ret = -EROFS;
3752                 goto out;
3753         }
3754
3755         if (!inode_owner_or_capable(inode)) {
3756                 ret = -EACCES;
3757                 goto out;
3758         }
3759
3760         sa = memdup_user(arg, sizeof(*sa));
3761         if (IS_ERR(sa)) {
3762                 ret = PTR_ERR(sa);
3763                 sa = NULL;
3764                 goto out;
3765         }
3766
3767         trans = btrfs_start_transaction(root, 1);
3768         if (IS_ERR(trans)) {
3769                 ret = PTR_ERR(trans);
3770                 trans = NULL;
3771                 goto out;
3772         }
3773
3774         sa->rtransid = trans->transid;
3775         sa->rtime.sec = ct.tv_sec;
3776         sa->rtime.nsec = ct.tv_nsec;
3777
3778         memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
3779         btrfs_set_root_stransid(root_item, sa->stransid);
3780         btrfs_set_root_rtransid(root_item, sa->rtransid);
3781         root_item->stime.sec = cpu_to_le64(sa->stime.sec);
3782         root_item->stime.nsec = cpu_to_le32(sa->stime.nsec);
3783         root_item->rtime.sec = cpu_to_le64(sa->rtime.sec);
3784         root_item->rtime.nsec = cpu_to_le32(sa->rtime.nsec);
3785
3786         ret = btrfs_update_root(trans, root->fs_info->tree_root,
3787                                 &root->root_key, &root->root_item);
3788         if (ret < 0) {
3789                 btrfs_end_transaction(trans, root);
3790                 trans = NULL;
3791                 goto out;
3792         } else {
3793                 ret = btrfs_commit_transaction(trans, root);
3794                 if (ret < 0)
3795                         goto out;
3796         }
3797
3798         ret = copy_to_user(arg, sa, sizeof(*sa));
3799         if (ret)
3800                 ret = -EFAULT;
3801
3802 out:
3803         kfree(sa);
3804         up_write(&root->fs_info->subvol_sem);
3805         mnt_drop_write_file(file);
3806         return ret;
3807 }
3808
3809 long btrfs_ioctl(struct file *file, unsigned int
3810                 cmd, unsigned long arg)
3811 {
3812         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
3813         void __user *argp = (void __user *)arg;
3814
3815         switch (cmd) {
3816         case FS_IOC_GETFLAGS:
3817                 return btrfs_ioctl_getflags(file, argp);
3818         case FS_IOC_SETFLAGS:
3819                 return btrfs_ioctl_setflags(file, argp);
3820         case FS_IOC_GETVERSION:
3821                 return btrfs_ioctl_getversion(file, argp);
3822         case FITRIM:
3823                 return btrfs_ioctl_fitrim(file, argp);
3824         case BTRFS_IOC_SNAP_CREATE:
3825                 return btrfs_ioctl_snap_create(file, argp, 0);
3826         case BTRFS_IOC_SNAP_CREATE_V2:
3827                 return btrfs_ioctl_snap_create_v2(file, argp, 0);
3828         case BTRFS_IOC_SUBVOL_CREATE:
3829                 return btrfs_ioctl_snap_create(file, argp, 1);
3830         case BTRFS_IOC_SUBVOL_CREATE_V2:
3831                 return btrfs_ioctl_snap_create_v2(file, argp, 1);
3832         case BTRFS_IOC_SNAP_DESTROY:
3833                 return btrfs_ioctl_snap_destroy(file, argp);
3834         case BTRFS_IOC_SUBVOL_GETFLAGS:
3835                 return btrfs_ioctl_subvol_getflags(file, argp);
3836         case BTRFS_IOC_SUBVOL_SETFLAGS:
3837                 return btrfs_ioctl_subvol_setflags(file, argp);
3838         case BTRFS_IOC_DEFAULT_SUBVOL:
3839                 return btrfs_ioctl_default_subvol(file, argp);
3840         case BTRFS_IOC_DEFRAG:
3841                 return btrfs_ioctl_defrag(file, NULL);
3842         case BTRFS_IOC_DEFRAG_RANGE:
3843                 return btrfs_ioctl_defrag(file, argp);
3844         case BTRFS_IOC_RESIZE:
3845                 return btrfs_ioctl_resize(file, argp);
3846         case BTRFS_IOC_ADD_DEV:
3847                 return btrfs_ioctl_add_dev(root, argp);
3848         case BTRFS_IOC_RM_DEV:
3849                 return btrfs_ioctl_rm_dev(file, argp);
3850         case BTRFS_IOC_FS_INFO:
3851                 return btrfs_ioctl_fs_info(root, argp);
3852         case BTRFS_IOC_DEV_INFO:
3853                 return btrfs_ioctl_dev_info(root, argp);
3854         case BTRFS_IOC_BALANCE:
3855                 return btrfs_ioctl_balance(file, NULL);
3856         case BTRFS_IOC_CLONE:
3857                 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
3858         case BTRFS_IOC_CLONE_RANGE:
3859                 return btrfs_ioctl_clone_range(file, argp);
3860         case BTRFS_IOC_TRANS_START:
3861                 return btrfs_ioctl_trans_start(file);
3862         case BTRFS_IOC_TRANS_END:
3863                 return btrfs_ioctl_trans_end(file);
3864         case BTRFS_IOC_TREE_SEARCH:
3865                 return btrfs_ioctl_tree_search(file, argp);
3866         case BTRFS_IOC_INO_LOOKUP:
3867                 return btrfs_ioctl_ino_lookup(file, argp);
3868         case BTRFS_IOC_INO_PATHS:
3869                 return btrfs_ioctl_ino_to_path(root, argp);
3870         case BTRFS_IOC_LOGICAL_INO:
3871                 return btrfs_ioctl_logical_to_ino(root, argp);
3872         case BTRFS_IOC_SPACE_INFO:
3873                 return btrfs_ioctl_space_info(root, argp);
3874         case BTRFS_IOC_SYNC:
3875                 btrfs_sync_fs(file->f_dentry->d_sb, 1);
3876                 return 0;
3877         case BTRFS_IOC_START_SYNC:
3878                 return btrfs_ioctl_start_sync(root, argp);
3879         case BTRFS_IOC_WAIT_SYNC:
3880                 return btrfs_ioctl_wait_sync(root, argp);
3881         case BTRFS_IOC_SCRUB:
3882                 return btrfs_ioctl_scrub(root, argp);
3883         case BTRFS_IOC_SCRUB_CANCEL:
3884                 return btrfs_ioctl_scrub_cancel(root, argp);
3885         case BTRFS_IOC_SCRUB_PROGRESS:
3886                 return btrfs_ioctl_scrub_progress(root, argp);
3887         case BTRFS_IOC_BALANCE_V2:
3888                 return btrfs_ioctl_balance(file, argp);
3889         case BTRFS_IOC_BALANCE_CTL:
3890                 return btrfs_ioctl_balance_ctl(root, arg);
3891         case BTRFS_IOC_BALANCE_PROGRESS:
3892                 return btrfs_ioctl_balance_progress(root, argp);
3893         case BTRFS_IOC_SET_RECEIVED_SUBVOL:
3894                 return btrfs_ioctl_set_received_subvol(file, argp);
3895         case BTRFS_IOC_SEND:
3896                 return btrfs_ioctl_send(file, argp);
3897         case BTRFS_IOC_GET_DEV_STATS:
3898                 return btrfs_ioctl_get_dev_stats(root, argp);
3899         case BTRFS_IOC_QUOTA_CTL:
3900                 return btrfs_ioctl_quota_ctl(root, argp);
3901         case BTRFS_IOC_QGROUP_ASSIGN:
3902                 return btrfs_ioctl_qgroup_assign(root, argp);
3903         case BTRFS_IOC_QGROUP_CREATE:
3904                 return btrfs_ioctl_qgroup_create(root, argp);
3905         case BTRFS_IOC_QGROUP_LIMIT:
3906                 return btrfs_ioctl_qgroup_limit(root, argp);
3907         case BTRFS_IOC_DEV_REPLACE:
3908                 return btrfs_ioctl_dev_replace(root, argp);
3909         }
3910
3911         return -ENOTTY;
3912 }