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