Btrfs: implement FS_IOC_GETFLAGS/SETFLAGS/GETVERSION
[linux-2.6] / 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/smp_lock.h>
31 #include <linux/backing-dev.h>
32 #include <linux/mount.h>
33 #include <linux/mpage.h>
34 #include <linux/namei.h>
35 #include <linux/swap.h>
36 #include <linux/writeback.h>
37 #include <linux/statfs.h>
38 #include <linux/compat.h>
39 #include <linux/bit_spinlock.h>
40 #include <linux/security.h>
41 #include <linux/xattr.h>
42 #include <linux/vmalloc.h>
43 #include "compat.h"
44 #include "ctree.h"
45 #include "disk-io.h"
46 #include "transaction.h"
47 #include "btrfs_inode.h"
48 #include "ioctl.h"
49 #include "print-tree.h"
50 #include "volumes.h"
51 #include "locking.h"
52
53 /* Mask out flags that are inappropriate for the given type of inode. */
54 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
55 {
56         if (S_ISDIR(mode))
57                 return flags;
58         else if (S_ISREG(mode))
59                 return flags & ~FS_DIRSYNC_FL;
60         else
61                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
62 }
63
64 /*
65  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
66  */
67 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
68 {
69         unsigned int iflags = 0;
70
71         if (flags & BTRFS_INODE_SYNC)
72                 iflags |= FS_SYNC_FL;
73         if (flags & BTRFS_INODE_IMMUTABLE)
74                 iflags |= FS_IMMUTABLE_FL;
75         if (flags & BTRFS_INODE_APPEND)
76                 iflags |= FS_APPEND_FL;
77         if (flags & BTRFS_INODE_NODUMP)
78                 iflags |= FS_NODUMP_FL;
79         if (flags & BTRFS_INODE_NOATIME)
80                 iflags |= FS_NOATIME_FL;
81         if (flags & BTRFS_INODE_DIRSYNC)
82                 iflags |= FS_DIRSYNC_FL;
83
84         return iflags;
85 }
86
87 /*
88  * Update inode->i_flags based on the btrfs internal flags.
89  */
90 void btrfs_update_iflags(struct inode *inode)
91 {
92         struct btrfs_inode *ip = BTRFS_I(inode);
93
94         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
95
96         if (ip->flags & BTRFS_INODE_SYNC)
97                 inode->i_flags |= S_SYNC;
98         if (ip->flags & BTRFS_INODE_IMMUTABLE)
99                 inode->i_flags |= S_IMMUTABLE;
100         if (ip->flags & BTRFS_INODE_APPEND)
101                 inode->i_flags |= S_APPEND;
102         if (ip->flags & BTRFS_INODE_NOATIME)
103                 inode->i_flags |= S_NOATIME;
104         if (ip->flags & BTRFS_INODE_DIRSYNC)
105                 inode->i_flags |= S_DIRSYNC;
106 }
107
108 /*
109  * Inherit flags from the parent inode.
110  *
111  * Unlike extN we don't have any flags we don't want to inherit currently.
112  */
113 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
114 {
115         unsigned int flags = BTRFS_I(dir)->flags;
116
117         if (S_ISREG(inode->i_mode))
118                 flags &= ~BTRFS_INODE_DIRSYNC;
119         else if (!S_ISDIR(inode->i_mode))
120                 flags &= (BTRFS_INODE_NODUMP | BTRFS_INODE_NOATIME);
121
122         BTRFS_I(inode)->flags = flags;
123         btrfs_update_iflags(inode);
124 }
125
126 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
127 {
128         struct btrfs_inode *ip = BTRFS_I(file->f_path.dentry->d_inode);
129         unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
130
131         if (copy_to_user(arg, &flags, sizeof(flags)))
132                 return -EFAULT;
133         return 0;
134 }
135
136 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
137 {
138         struct inode *inode = file->f_path.dentry->d_inode;
139         struct btrfs_inode *ip = BTRFS_I(inode);
140         struct btrfs_root *root = ip->root;
141         struct btrfs_trans_handle *trans;
142         unsigned int flags, oldflags;
143         int ret;
144
145         if (copy_from_user(&flags, arg, sizeof(flags)))
146                 return -EFAULT;
147
148         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
149                       FS_NOATIME_FL | FS_NODUMP_FL | \
150                       FS_SYNC_FL | FS_DIRSYNC_FL))
151                 return -EOPNOTSUPP;
152
153         if (!is_owner_or_cap(inode))
154                 return -EACCES;
155
156         mutex_lock(&inode->i_mutex);
157
158         flags = btrfs_mask_flags(inode->i_mode, flags);
159         oldflags = btrfs_flags_to_ioctl(ip->flags);
160         if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
161                 if (!capable(CAP_LINUX_IMMUTABLE)) {
162                         ret = -EPERM;
163                         goto out_unlock;
164                 }
165         }
166
167         ret = mnt_want_write(file->f_path.mnt);
168         if (ret)
169                 goto out_unlock;
170
171         if (flags & FS_SYNC_FL)
172                 ip->flags |= BTRFS_INODE_SYNC;
173         else
174                 ip->flags &= ~BTRFS_INODE_SYNC;
175         if (flags & FS_IMMUTABLE_FL)
176                 ip->flags |= BTRFS_INODE_IMMUTABLE;
177         else
178                 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
179         if (flags & FS_APPEND_FL)
180                 ip->flags |= BTRFS_INODE_APPEND;
181         else
182                 ip->flags &= ~BTRFS_INODE_APPEND;
183         if (flags & FS_NODUMP_FL)
184                 ip->flags |= BTRFS_INODE_NODUMP;
185         else
186                 ip->flags &= ~BTRFS_INODE_NODUMP;
187         if (flags & FS_NOATIME_FL)
188                 ip->flags |= BTRFS_INODE_NOATIME;
189         else
190                 ip->flags &= ~BTRFS_INODE_NOATIME;
191         if (flags & FS_DIRSYNC_FL)
192                 ip->flags |= BTRFS_INODE_DIRSYNC;
193         else
194                 ip->flags &= ~BTRFS_INODE_DIRSYNC;
195
196
197         trans = btrfs_join_transaction(root, 1);
198         BUG_ON(!trans);
199
200         ret = btrfs_update_inode(trans, root, inode);
201         BUG_ON(ret);
202
203         btrfs_update_iflags(inode);
204         inode->i_ctime = CURRENT_TIME;
205         btrfs_end_transaction(trans, root);
206
207         mnt_drop_write(file->f_path.mnt);
208  out_unlock:
209         mutex_unlock(&inode->i_mutex);
210         return 0;
211 }
212
213 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
214 {
215         struct inode *inode = file->f_path.dentry->d_inode;
216
217         return put_user(inode->i_generation, arg);
218 }
219
220 static noinline int create_subvol(struct btrfs_root *root,
221                                   struct dentry *dentry,
222                                   char *name, int namelen)
223 {
224         struct btrfs_trans_handle *trans;
225         struct btrfs_key key;
226         struct btrfs_root_item root_item;
227         struct btrfs_inode_item *inode_item;
228         struct extent_buffer *leaf;
229         struct btrfs_root *new_root = root;
230         struct inode *dir;
231         int ret;
232         int err;
233         u64 objectid;
234         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
235         u64 index = 0;
236         unsigned long nr = 1;
237
238         ret = btrfs_check_metadata_free_space(root);
239         if (ret)
240                 goto fail_commit;
241
242         trans = btrfs_start_transaction(root, 1);
243         BUG_ON(!trans);
244
245         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
246                                        0, &objectid);
247         if (ret)
248                 goto fail;
249
250         leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
251                                       0, objectid, NULL, 0, 0, 0);
252         if (IS_ERR(leaf)) {
253                 ret = PTR_ERR(leaf);
254                 goto fail;
255         }
256
257         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
258         btrfs_set_header_bytenr(leaf, leaf->start);
259         btrfs_set_header_generation(leaf, trans->transid);
260         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
261         btrfs_set_header_owner(leaf, objectid);
262
263         write_extent_buffer(leaf, root->fs_info->fsid,
264                             (unsigned long)btrfs_header_fsid(leaf),
265                             BTRFS_FSID_SIZE);
266         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
267                             (unsigned long)btrfs_header_chunk_tree_uuid(leaf),
268                             BTRFS_UUID_SIZE);
269         btrfs_mark_buffer_dirty(leaf);
270
271         inode_item = &root_item.inode;
272         memset(inode_item, 0, sizeof(*inode_item));
273         inode_item->generation = cpu_to_le64(1);
274         inode_item->size = cpu_to_le64(3);
275         inode_item->nlink = cpu_to_le32(1);
276         inode_item->nbytes = cpu_to_le64(root->leafsize);
277         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
278
279         btrfs_set_root_bytenr(&root_item, leaf->start);
280         btrfs_set_root_generation(&root_item, trans->transid);
281         btrfs_set_root_level(&root_item, 0);
282         btrfs_set_root_refs(&root_item, 1);
283         btrfs_set_root_used(&root_item, 0);
284         btrfs_set_root_last_snapshot(&root_item, 0);
285
286         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
287         root_item.drop_level = 0;
288
289         btrfs_tree_unlock(leaf);
290         free_extent_buffer(leaf);
291         leaf = NULL;
292
293         btrfs_set_root_dirid(&root_item, new_dirid);
294
295         key.objectid = objectid;
296         key.offset = 0;
297         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
298         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
299                                 &root_item);
300         if (ret)
301                 goto fail;
302
303         /*
304          * insert the directory item
305          */
306         key.offset = (u64)-1;
307         dir = dentry->d_parent->d_inode;
308         ret = btrfs_set_inode_index(dir, &index);
309         BUG_ON(ret);
310
311         ret = btrfs_insert_dir_item(trans, root,
312                                     name, namelen, dir->i_ino, &key,
313                                     BTRFS_FT_DIR, index);
314         if (ret)
315                 goto fail;
316
317         btrfs_i_size_write(dir, dir->i_size + namelen * 2);
318         ret = btrfs_update_inode(trans, root, dir);
319         BUG_ON(ret);
320
321         /* add the backref first */
322         ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
323                                  objectid, BTRFS_ROOT_BACKREF_KEY,
324                                  root->root_key.objectid,
325                                  dir->i_ino, index, name, namelen);
326
327         BUG_ON(ret);
328
329         /* now add the forward ref */
330         ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
331                                  root->root_key.objectid, BTRFS_ROOT_REF_KEY,
332                                  objectid,
333                                  dir->i_ino, index, name, namelen);
334
335         BUG_ON(ret);
336
337         ret = btrfs_commit_transaction(trans, root);
338         if (ret)
339                 goto fail_commit;
340
341         new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
342         BUG_ON(!new_root);
343
344         trans = btrfs_start_transaction(new_root, 1);
345         BUG_ON(!trans);
346
347         ret = btrfs_create_subvol_root(trans, new_root, dentry, new_dirid,
348                                        BTRFS_I(dir)->block_group);
349         if (ret)
350                 goto fail;
351
352 fail:
353         nr = trans->blocks_used;
354         err = btrfs_commit_transaction(trans, new_root);
355         if (err && !ret)
356                 ret = err;
357 fail_commit:
358         btrfs_btree_balance_dirty(root, nr);
359         return ret;
360 }
361
362 static int create_snapshot(struct btrfs_root *root, struct dentry *dentry,
363                            char *name, int namelen)
364 {
365         struct btrfs_pending_snapshot *pending_snapshot;
366         struct btrfs_trans_handle *trans;
367         int ret = 0;
368         int err;
369         unsigned long nr = 0;
370
371         if (!root->ref_cows)
372                 return -EINVAL;
373
374         ret = btrfs_check_metadata_free_space(root);
375         if (ret)
376                 goto fail_unlock;
377
378         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
379         if (!pending_snapshot) {
380                 ret = -ENOMEM;
381                 goto fail_unlock;
382         }
383         pending_snapshot->name = kmalloc(namelen + 1, GFP_NOFS);
384         if (!pending_snapshot->name) {
385                 ret = -ENOMEM;
386                 kfree(pending_snapshot);
387                 goto fail_unlock;
388         }
389         memcpy(pending_snapshot->name, name, namelen);
390         pending_snapshot->name[namelen] = '\0';
391         pending_snapshot->dentry = dentry;
392         trans = btrfs_start_transaction(root, 1);
393         BUG_ON(!trans);
394         pending_snapshot->root = root;
395         list_add(&pending_snapshot->list,
396                  &trans->transaction->pending_snapshots);
397         err = btrfs_commit_transaction(trans, root);
398
399 fail_unlock:
400         btrfs_btree_balance_dirty(root, nr);
401         return ret;
402 }
403
404 /* copy of may_create in fs/namei.c() */
405 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
406 {
407         if (child->d_inode)
408                 return -EEXIST;
409         if (IS_DEADDIR(dir))
410                 return -ENOENT;
411         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
412 }
413
414 /*
415  * Create a new subvolume below @parent.  This is largely modeled after
416  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
417  * inside this filesystem so it's quite a bit simpler.
418  */
419 static noinline int btrfs_mksubvol(struct path *parent, char *name,
420                                    int mode, int namelen,
421                                    struct btrfs_root *snap_src)
422 {
423         struct dentry *dentry;
424         int error;
425
426         mutex_lock_nested(&parent->dentry->d_inode->i_mutex, I_MUTEX_PARENT);
427
428         dentry = lookup_one_len(name, parent->dentry, namelen);
429         error = PTR_ERR(dentry);
430         if (IS_ERR(dentry))
431                 goto out_unlock;
432
433         error = -EEXIST;
434         if (dentry->d_inode)
435                 goto out_dput;
436
437         if (!IS_POSIXACL(parent->dentry->d_inode))
438                 mode &= ~current_umask();
439
440         error = mnt_want_write(parent->mnt);
441         if (error)
442                 goto out_dput;
443
444         error = btrfs_may_create(parent->dentry->d_inode, dentry);
445         if (error)
446                 goto out_drop_write;
447
448         /*
449          * Actually perform the low-level subvolume creation after all
450          * this VFS fuzz.
451          *
452          * Eventually we want to pass in an inode under which we create this
453          * subvolume, but for now all are under the filesystem root.
454          *
455          * Also we should pass on the mode eventually to allow creating new
456          * subvolume with specific mode bits.
457          */
458         if (snap_src) {
459                 struct dentry *dir = dentry->d_parent;
460                 struct dentry *test = dir->d_parent;
461                 struct btrfs_path *path = btrfs_alloc_path();
462                 int ret;
463                 u64 test_oid;
464                 u64 parent_oid = BTRFS_I(dir->d_inode)->root->root_key.objectid;
465
466                 test_oid = snap_src->root_key.objectid;
467
468                 ret = btrfs_find_root_ref(snap_src->fs_info->tree_root,
469                                           path, parent_oid, test_oid);
470                 if (ret == 0)
471                         goto create;
472                 btrfs_release_path(snap_src->fs_info->tree_root, path);
473
474                 /* we need to make sure we aren't creating a directory loop
475                  * by taking a snapshot of something that has our current
476                  * subvol in its directory tree.  So, this loops through
477                  * the dentries and checks the forward refs for each subvolume
478                  * to see if is references the subvolume where we are
479                  * placing this new snapshot.
480                  */
481                 while (1) {
482                         if (!test ||
483                             dir == snap_src->fs_info->sb->s_root ||
484                             test == snap_src->fs_info->sb->s_root ||
485                             test->d_inode->i_sb != snap_src->fs_info->sb) {
486                                 break;
487                         }
488                         if (S_ISLNK(test->d_inode->i_mode)) {
489                                 printk(KERN_INFO "Btrfs symlink in snapshot "
490                                        "path, failed\n");
491                                 error = -EMLINK;
492                                 btrfs_free_path(path);
493                                 goto out_drop_write;
494                         }
495                         test_oid =
496                                 BTRFS_I(test->d_inode)->root->root_key.objectid;
497                         ret = btrfs_find_root_ref(snap_src->fs_info->tree_root,
498                                   path, test_oid, parent_oid);
499                         if (ret == 0) {
500                                 printk(KERN_INFO "Btrfs snapshot creation "
501                                        "failed, looping\n");
502                                 error = -EMLINK;
503                                 btrfs_free_path(path);
504                                 goto out_drop_write;
505                         }
506                         btrfs_release_path(snap_src->fs_info->tree_root, path);
507                         test = test->d_parent;
508                 }
509 create:
510                 btrfs_free_path(path);
511                 error = create_snapshot(snap_src, dentry, name, namelen);
512         } else {
513                 error = create_subvol(BTRFS_I(parent->dentry->d_inode)->root,
514                                       dentry, name, namelen);
515         }
516         if (error)
517                 goto out_drop_write;
518
519         fsnotify_mkdir(parent->dentry->d_inode, dentry);
520 out_drop_write:
521         mnt_drop_write(parent->mnt);
522 out_dput:
523         dput(dentry);
524 out_unlock:
525         mutex_unlock(&parent->dentry->d_inode->i_mutex);
526         return error;
527 }
528
529
530 static int btrfs_defrag_file(struct file *file)
531 {
532         struct inode *inode = fdentry(file)->d_inode;
533         struct btrfs_root *root = BTRFS_I(inode)->root;
534         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
535         struct btrfs_ordered_extent *ordered;
536         struct page *page;
537         unsigned long last_index;
538         unsigned long ra_pages = root->fs_info->bdi.ra_pages;
539         unsigned long total_read = 0;
540         u64 page_start;
541         u64 page_end;
542         unsigned long i;
543         int ret;
544
545         ret = btrfs_check_data_free_space(root, inode, inode->i_size);
546         if (ret)
547                 return -ENOSPC;
548
549         mutex_lock(&inode->i_mutex);
550         last_index = inode->i_size >> PAGE_CACHE_SHIFT;
551         for (i = 0; i <= last_index; i++) {
552                 if (total_read % ra_pages == 0) {
553                         btrfs_force_ra(inode->i_mapping, &file->f_ra, file, i,
554                                        min(last_index, i + ra_pages - 1));
555                 }
556                 total_read++;
557 again:
558                 page = grab_cache_page(inode->i_mapping, i);
559                 if (!page)
560                         goto out_unlock;
561                 if (!PageUptodate(page)) {
562                         btrfs_readpage(NULL, page);
563                         lock_page(page);
564                         if (!PageUptodate(page)) {
565                                 unlock_page(page);
566                                 page_cache_release(page);
567                                 goto out_unlock;
568                         }
569                 }
570
571                 wait_on_page_writeback(page);
572
573                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
574                 page_end = page_start + PAGE_CACHE_SIZE - 1;
575                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
576
577                 ordered = btrfs_lookup_ordered_extent(inode, page_start);
578                 if (ordered) {
579                         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
580                         unlock_page(page);
581                         page_cache_release(page);
582                         btrfs_start_ordered_extent(inode, ordered, 1);
583                         btrfs_put_ordered_extent(ordered);
584                         goto again;
585                 }
586                 set_page_extent_mapped(page);
587
588                 /*
589                  * this makes sure page_mkwrite is called on the
590                  * page if it is dirtied again later
591                  */
592                 clear_page_dirty_for_io(page);
593
594                 btrfs_set_extent_delalloc(inode, page_start, page_end);
595
596                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
597                 set_page_dirty(page);
598                 unlock_page(page);
599                 page_cache_release(page);
600                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, 1);
601         }
602
603 out_unlock:
604         mutex_unlock(&inode->i_mutex);
605         return 0;
606 }
607
608 static int btrfs_ioctl_resize(struct btrfs_root *root, void __user *arg)
609 {
610         u64 new_size;
611         u64 old_size;
612         u64 devid = 1;
613         struct btrfs_ioctl_vol_args *vol_args;
614         struct btrfs_trans_handle *trans;
615         struct btrfs_device *device = NULL;
616         char *sizestr;
617         char *devstr = NULL;
618         int ret = 0;
619         int namelen;
620         int mod = 0;
621
622         if (root->fs_info->sb->s_flags & MS_RDONLY)
623                 return -EROFS;
624
625         if (!capable(CAP_SYS_ADMIN))
626                 return -EPERM;
627
628         vol_args = memdup_user(arg, sizeof(*vol_args));
629         if (IS_ERR(vol_args))
630                 return PTR_ERR(vol_args);
631
632         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
633         namelen = strlen(vol_args->name);
634
635         mutex_lock(&root->fs_info->volume_mutex);
636         sizestr = vol_args->name;
637         devstr = strchr(sizestr, ':');
638         if (devstr) {
639                 char *end;
640                 sizestr = devstr + 1;
641                 *devstr = '\0';
642                 devstr = vol_args->name;
643                 devid = simple_strtoull(devstr, &end, 10);
644                 printk(KERN_INFO "resizing devid %llu\n",
645                        (unsigned long long)devid);
646         }
647         device = btrfs_find_device(root, devid, NULL, NULL);
648         if (!device) {
649                 printk(KERN_INFO "resizer unable to find device %llu\n",
650                        (unsigned long long)devid);
651                 ret = -EINVAL;
652                 goto out_unlock;
653         }
654         if (!strcmp(sizestr, "max"))
655                 new_size = device->bdev->bd_inode->i_size;
656         else {
657                 if (sizestr[0] == '-') {
658                         mod = -1;
659                         sizestr++;
660                 } else if (sizestr[0] == '+') {
661                         mod = 1;
662                         sizestr++;
663                 }
664                 new_size = btrfs_parse_size(sizestr);
665                 if (new_size == 0) {
666                         ret = -EINVAL;
667                         goto out_unlock;
668                 }
669         }
670
671         old_size = device->total_bytes;
672
673         if (mod < 0) {
674                 if (new_size > old_size) {
675                         ret = -EINVAL;
676                         goto out_unlock;
677                 }
678                 new_size = old_size - new_size;
679         } else if (mod > 0) {
680                 new_size = old_size + new_size;
681         }
682
683         if (new_size < 256 * 1024 * 1024) {
684                 ret = -EINVAL;
685                 goto out_unlock;
686         }
687         if (new_size > device->bdev->bd_inode->i_size) {
688                 ret = -EFBIG;
689                 goto out_unlock;
690         }
691
692         do_div(new_size, root->sectorsize);
693         new_size *= root->sectorsize;
694
695         printk(KERN_INFO "new size for %s is %llu\n",
696                 device->name, (unsigned long long)new_size);
697
698         if (new_size > old_size) {
699                 trans = btrfs_start_transaction(root, 1);
700                 ret = btrfs_grow_device(trans, device, new_size);
701                 btrfs_commit_transaction(trans, root);
702         } else {
703                 ret = btrfs_shrink_device(device, new_size);
704         }
705
706 out_unlock:
707         mutex_unlock(&root->fs_info->volume_mutex);
708         kfree(vol_args);
709         return ret;
710 }
711
712 static noinline int btrfs_ioctl_snap_create(struct file *file,
713                                             void __user *arg, int subvol)
714 {
715         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
716         struct btrfs_ioctl_vol_args *vol_args;
717         struct btrfs_dir_item *di;
718         struct btrfs_path *path;
719         struct file *src_file;
720         u64 root_dirid;
721         int namelen;
722         int ret = 0;
723
724         if (root->fs_info->sb->s_flags & MS_RDONLY)
725                 return -EROFS;
726
727         vol_args = memdup_user(arg, sizeof(*vol_args));
728         if (IS_ERR(vol_args))
729                 return PTR_ERR(vol_args);
730
731         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
732         namelen = strlen(vol_args->name);
733         if (strchr(vol_args->name, '/')) {
734                 ret = -EINVAL;
735                 goto out;
736         }
737
738         path = btrfs_alloc_path();
739         if (!path) {
740                 ret = -ENOMEM;
741                 goto out;
742         }
743
744         root_dirid = root->fs_info->sb->s_root->d_inode->i_ino,
745         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root,
746                             path, root_dirid,
747                             vol_args->name, namelen, 0);
748         btrfs_free_path(path);
749
750         if (di && !IS_ERR(di)) {
751                 ret = -EEXIST;
752                 goto out;
753         }
754
755         if (IS_ERR(di)) {
756                 ret = PTR_ERR(di);
757                 goto out;
758         }
759
760         if (subvol) {
761                 ret = btrfs_mksubvol(&file->f_path, vol_args->name,
762                                      file->f_path.dentry->d_inode->i_mode,
763                                      namelen, NULL);
764         } else {
765                 struct inode *src_inode;
766                 src_file = fget(vol_args->fd);
767                 if (!src_file) {
768                         ret = -EINVAL;
769                         goto out;
770                 }
771
772                 src_inode = src_file->f_path.dentry->d_inode;
773                 if (src_inode->i_sb != file->f_path.dentry->d_inode->i_sb) {
774                         printk(KERN_INFO "btrfs: Snapshot src from "
775                                "another FS\n");
776                         ret = -EINVAL;
777                         fput(src_file);
778                         goto out;
779                 }
780                 ret = btrfs_mksubvol(&file->f_path, vol_args->name,
781                              file->f_path.dentry->d_inode->i_mode,
782                              namelen, BTRFS_I(src_inode)->root);
783                 fput(src_file);
784         }
785
786 out:
787         kfree(vol_args);
788         return ret;
789 }
790
791 static int btrfs_ioctl_defrag(struct file *file)
792 {
793         struct inode *inode = fdentry(file)->d_inode;
794         struct btrfs_root *root = BTRFS_I(inode)->root;
795         int ret;
796
797         ret = mnt_want_write(file->f_path.mnt);
798         if (ret)
799                 return ret;
800
801         switch (inode->i_mode & S_IFMT) {
802         case S_IFDIR:
803                 if (!capable(CAP_SYS_ADMIN)) {
804                         ret = -EPERM;
805                         goto out;
806                 }
807                 btrfs_defrag_root(root, 0);
808                 btrfs_defrag_root(root->fs_info->extent_root, 0);
809                 break;
810         case S_IFREG:
811                 if (!(file->f_mode & FMODE_WRITE)) {
812                         ret = -EINVAL;
813                         goto out;
814                 }
815                 btrfs_defrag_file(file);
816                 break;
817         }
818 out:
819         mnt_drop_write(file->f_path.mnt);
820         return ret;
821 }
822
823 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
824 {
825         struct btrfs_ioctl_vol_args *vol_args;
826         int ret;
827
828         if (!capable(CAP_SYS_ADMIN))
829                 return -EPERM;
830
831         vol_args = memdup_user(arg, sizeof(*vol_args));
832         if (IS_ERR(vol_args))
833                 return PTR_ERR(vol_args);
834
835         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
836         ret = btrfs_init_new_device(root, vol_args->name);
837
838         kfree(vol_args);
839         return ret;
840 }
841
842 static long btrfs_ioctl_rm_dev(struct btrfs_root *root, void __user *arg)
843 {
844         struct btrfs_ioctl_vol_args *vol_args;
845         int ret;
846
847         if (!capable(CAP_SYS_ADMIN))
848                 return -EPERM;
849
850         if (root->fs_info->sb->s_flags & MS_RDONLY)
851                 return -EROFS;
852
853         vol_args = memdup_user(arg, sizeof(*vol_args));
854         if (IS_ERR(vol_args))
855                 return PTR_ERR(vol_args);
856
857         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
858         ret = btrfs_rm_device(root, vol_args->name);
859
860         kfree(vol_args);
861         return ret;
862 }
863
864 static long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
865                 u64 off, u64 olen, u64 destoff)
866 {
867         struct inode *inode = fdentry(file)->d_inode;
868         struct btrfs_root *root = BTRFS_I(inode)->root;
869         struct file *src_file;
870         struct inode *src;
871         struct btrfs_trans_handle *trans;
872         struct btrfs_path *path;
873         struct extent_buffer *leaf;
874         char *buf;
875         struct btrfs_key key;
876         u32 nritems;
877         int slot;
878         int ret;
879         u64 len = olen;
880         u64 bs = root->fs_info->sb->s_blocksize;
881         u64 hint_byte;
882
883         /*
884          * TODO:
885          * - split compressed inline extents.  annoying: we need to
886          *   decompress into destination's address_space (the file offset
887          *   may change, so source mapping won't do), then recompress (or
888          *   otherwise reinsert) a subrange.
889          * - allow ranges within the same file to be cloned (provided
890          *   they don't overlap)?
891          */
892
893         /* the destination must be opened for writing */
894         if (!(file->f_mode & FMODE_WRITE))
895                 return -EINVAL;
896
897         ret = mnt_want_write(file->f_path.mnt);
898         if (ret)
899                 return ret;
900
901         src_file = fget(srcfd);
902         if (!src_file) {
903                 ret = -EBADF;
904                 goto out_drop_write;
905         }
906         src = src_file->f_dentry->d_inode;
907
908         ret = -EINVAL;
909         if (src == inode)
910                 goto out_fput;
911
912         ret = -EISDIR;
913         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
914                 goto out_fput;
915
916         ret = -EXDEV;
917         if (src->i_sb != inode->i_sb || BTRFS_I(src)->root != root)
918                 goto out_fput;
919
920         ret = -ENOMEM;
921         buf = vmalloc(btrfs_level_size(root, 0));
922         if (!buf)
923                 goto out_fput;
924
925         path = btrfs_alloc_path();
926         if (!path) {
927                 vfree(buf);
928                 goto out_fput;
929         }
930         path->reada = 2;
931
932         if (inode < src) {
933                 mutex_lock(&inode->i_mutex);
934                 mutex_lock(&src->i_mutex);
935         } else {
936                 mutex_lock(&src->i_mutex);
937                 mutex_lock(&inode->i_mutex);
938         }
939
940         /* determine range to clone */
941         ret = -EINVAL;
942         if (off >= src->i_size || off + len > src->i_size)
943                 goto out_unlock;
944         if (len == 0)
945                 olen = len = src->i_size - off;
946         /* if we extend to eof, continue to block boundary */
947         if (off + len == src->i_size)
948                 len = ((src->i_size + bs-1) & ~(bs-1))
949                         - off;
950
951         /* verify the end result is block aligned */
952         if ((off & (bs-1)) ||
953             ((off + len) & (bs-1)))
954                 goto out_unlock;
955
956         /* do any pending delalloc/csum calc on src, one way or
957            another, and lock file content */
958         while (1) {
959                 struct btrfs_ordered_extent *ordered;
960                 lock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
961                 ordered = btrfs_lookup_first_ordered_extent(inode, off+len);
962                 if (BTRFS_I(src)->delalloc_bytes == 0 && !ordered)
963                         break;
964                 unlock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
965                 if (ordered)
966                         btrfs_put_ordered_extent(ordered);
967                 btrfs_wait_ordered_range(src, off, off+len);
968         }
969
970         trans = btrfs_start_transaction(root, 1);
971         BUG_ON(!trans);
972
973         /* punch hole in destination first */
974         btrfs_drop_extents(trans, root, inode, off, off + len,
975                            off + len, 0, &hint_byte);
976
977         /* clone data */
978         key.objectid = src->i_ino;
979         key.type = BTRFS_EXTENT_DATA_KEY;
980         key.offset = 0;
981
982         while (1) {
983                 /*
984                  * note the key will change type as we walk through the
985                  * tree.
986                  */
987                 ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
988                 if (ret < 0)
989                         goto out;
990
991                 nritems = btrfs_header_nritems(path->nodes[0]);
992                 if (path->slots[0] >= nritems) {
993                         ret = btrfs_next_leaf(root, path);
994                         if (ret < 0)
995                                 goto out;
996                         if (ret > 0)
997                                 break;
998                         nritems = btrfs_header_nritems(path->nodes[0]);
999                 }
1000                 leaf = path->nodes[0];
1001                 slot = path->slots[0];
1002
1003                 btrfs_item_key_to_cpu(leaf, &key, slot);
1004                 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
1005                     key.objectid != src->i_ino)
1006                         break;
1007
1008                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
1009                         struct btrfs_file_extent_item *extent;
1010                         int type;
1011                         u32 size;
1012                         struct btrfs_key new_key;
1013                         u64 disko = 0, diskl = 0;
1014                         u64 datao = 0, datal = 0;
1015                         u8 comp;
1016
1017                         size = btrfs_item_size_nr(leaf, slot);
1018                         read_extent_buffer(leaf, buf,
1019                                            btrfs_item_ptr_offset(leaf, slot),
1020                                            size);
1021
1022                         extent = btrfs_item_ptr(leaf, slot,
1023                                                 struct btrfs_file_extent_item);
1024                         comp = btrfs_file_extent_compression(leaf, extent);
1025                         type = btrfs_file_extent_type(leaf, extent);
1026                         if (type == BTRFS_FILE_EXTENT_REG) {
1027                                 disko = btrfs_file_extent_disk_bytenr(leaf,
1028                                                                       extent);
1029                                 diskl = btrfs_file_extent_disk_num_bytes(leaf,
1030                                                                  extent);
1031                                 datao = btrfs_file_extent_offset(leaf, extent);
1032                                 datal = btrfs_file_extent_num_bytes(leaf,
1033                                                                     extent);
1034                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
1035                                 /* take upper bound, may be compressed */
1036                                 datal = btrfs_file_extent_ram_bytes(leaf,
1037                                                                     extent);
1038                         }
1039                         btrfs_release_path(root, path);
1040
1041                         if (key.offset + datal < off ||
1042                             key.offset >= off+len)
1043                                 goto next;
1044
1045                         memcpy(&new_key, &key, sizeof(new_key));
1046                         new_key.objectid = inode->i_ino;
1047                         new_key.offset = key.offset + destoff - off;
1048
1049                         if (type == BTRFS_FILE_EXTENT_REG) {
1050                                 ret = btrfs_insert_empty_item(trans, root, path,
1051                                                               &new_key, size);
1052                                 if (ret)
1053                                         goto out;
1054
1055                                 leaf = path->nodes[0];
1056                                 slot = path->slots[0];
1057                                 write_extent_buffer(leaf, buf,
1058                                             btrfs_item_ptr_offset(leaf, slot),
1059                                             size);
1060
1061                                 extent = btrfs_item_ptr(leaf, slot,
1062                                                 struct btrfs_file_extent_item);
1063
1064                                 if (off > key.offset) {
1065                                         datao += off - key.offset;
1066                                         datal -= off - key.offset;
1067                                 }
1068                                 if (key.offset + datao + datal + key.offset >
1069                                     off + len)
1070                                         datal = off + len - key.offset - datao;
1071                                 /* disko == 0 means it's a hole */
1072                                 if (!disko)
1073                                         datao = 0;
1074
1075                                 btrfs_set_file_extent_offset(leaf, extent,
1076                                                              datao);
1077                                 btrfs_set_file_extent_num_bytes(leaf, extent,
1078                                                                 datal);
1079                                 if (disko) {
1080                                         inode_add_bytes(inode, datal);
1081                                         ret = btrfs_inc_extent_ref(trans, root,
1082                                                         disko, diskl, 0,
1083                                                         root->root_key.objectid,
1084                                                         inode->i_ino,
1085                                                         new_key.offset - datao);
1086                                         BUG_ON(ret);
1087                                 }
1088                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
1089                                 u64 skip = 0;
1090                                 u64 trim = 0;
1091                                 if (off > key.offset) {
1092                                         skip = off - key.offset;
1093                                         new_key.offset += skip;
1094                                 }
1095
1096                                 if (key.offset + datal > off+len)
1097                                         trim = key.offset + datal - (off+len);
1098
1099                                 if (comp && (skip || trim)) {
1100                                         ret = -EINVAL;
1101                                         goto out;
1102                                 }
1103                                 size -= skip + trim;
1104                                 datal -= skip + trim;
1105                                 ret = btrfs_insert_empty_item(trans, root, path,
1106                                                               &new_key, size);
1107                                 if (ret)
1108                                         goto out;
1109
1110                                 if (skip) {
1111                                         u32 start =
1112                                           btrfs_file_extent_calc_inline_size(0);
1113                                         memmove(buf+start, buf+start+skip,
1114                                                 datal);
1115                                 }
1116
1117                                 leaf = path->nodes[0];
1118                                 slot = path->slots[0];
1119                                 write_extent_buffer(leaf, buf,
1120                                             btrfs_item_ptr_offset(leaf, slot),
1121                                             size);
1122                                 inode_add_bytes(inode, datal);
1123                         }
1124
1125                         btrfs_mark_buffer_dirty(leaf);
1126                 }
1127
1128 next:
1129                 btrfs_release_path(root, path);
1130                 key.offset++;
1131         }
1132         ret = 0;
1133 out:
1134         btrfs_release_path(root, path);
1135         if (ret == 0) {
1136                 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1137                 if (destoff + olen > inode->i_size)
1138                         btrfs_i_size_write(inode, destoff + olen);
1139                 BTRFS_I(inode)->flags = BTRFS_I(src)->flags;
1140                 ret = btrfs_update_inode(trans, root, inode);
1141         }
1142         btrfs_end_transaction(trans, root);
1143         unlock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
1144         if (ret)
1145                 vmtruncate(inode, 0);
1146 out_unlock:
1147         mutex_unlock(&src->i_mutex);
1148         mutex_unlock(&inode->i_mutex);
1149         vfree(buf);
1150         btrfs_free_path(path);
1151 out_fput:
1152         fput(src_file);
1153 out_drop_write:
1154         mnt_drop_write(file->f_path.mnt);
1155         return ret;
1156 }
1157
1158 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
1159 {
1160         struct btrfs_ioctl_clone_range_args args;
1161
1162         if (copy_from_user(&args, argp, sizeof(args)))
1163                 return -EFAULT;
1164         return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
1165                                  args.src_length, args.dest_offset);
1166 }
1167
1168 /*
1169  * there are many ways the trans_start and trans_end ioctls can lead
1170  * to deadlocks.  They should only be used by applications that
1171  * basically own the machine, and have a very in depth understanding
1172  * of all the possible deadlocks and enospc problems.
1173  */
1174 static long btrfs_ioctl_trans_start(struct file *file)
1175 {
1176         struct inode *inode = fdentry(file)->d_inode;
1177         struct btrfs_root *root = BTRFS_I(inode)->root;
1178         struct btrfs_trans_handle *trans;
1179         int ret = 0;
1180
1181         if (!capable(CAP_SYS_ADMIN))
1182                 return -EPERM;
1183
1184         if (file->private_data) {
1185                 ret = -EINPROGRESS;
1186                 goto out;
1187         }
1188
1189         ret = mnt_want_write(file->f_path.mnt);
1190         if (ret)
1191                 goto out;
1192
1193         mutex_lock(&root->fs_info->trans_mutex);
1194         root->fs_info->open_ioctl_trans++;
1195         mutex_unlock(&root->fs_info->trans_mutex);
1196
1197         trans = btrfs_start_ioctl_transaction(root, 0);
1198         if (trans)
1199                 file->private_data = trans;
1200         else
1201                 ret = -ENOMEM;
1202         /*printk(KERN_INFO "btrfs_ioctl_trans_start on %p\n", file);*/
1203 out:
1204         return ret;
1205 }
1206
1207 /*
1208  * there are many ways the trans_start and trans_end ioctls can lead
1209  * to deadlocks.  They should only be used by applications that
1210  * basically own the machine, and have a very in depth understanding
1211  * of all the possible deadlocks and enospc problems.
1212  */
1213 long btrfs_ioctl_trans_end(struct file *file)
1214 {
1215         struct inode *inode = fdentry(file)->d_inode;
1216         struct btrfs_root *root = BTRFS_I(inode)->root;
1217         struct btrfs_trans_handle *trans;
1218         int ret = 0;
1219
1220         trans = file->private_data;
1221         if (!trans) {
1222                 ret = -EINVAL;
1223                 goto out;
1224         }
1225         btrfs_end_transaction(trans, root);
1226         file->private_data = NULL;
1227
1228         mutex_lock(&root->fs_info->trans_mutex);
1229         root->fs_info->open_ioctl_trans--;
1230         mutex_unlock(&root->fs_info->trans_mutex);
1231
1232         mnt_drop_write(file->f_path.mnt);
1233
1234 out:
1235         return ret;
1236 }
1237
1238 long btrfs_ioctl(struct file *file, unsigned int
1239                 cmd, unsigned long arg)
1240 {
1241         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
1242         void __user *argp = (void __user *)arg;
1243
1244         switch (cmd) {
1245         case FS_IOC_GETFLAGS:
1246                 return btrfs_ioctl_getflags(file, argp);
1247         case FS_IOC_SETFLAGS:
1248                 return btrfs_ioctl_setflags(file, argp);
1249         case FS_IOC_GETVERSION:
1250                 return btrfs_ioctl_getversion(file, argp);
1251         case BTRFS_IOC_SNAP_CREATE:
1252                 return btrfs_ioctl_snap_create(file, argp, 0);
1253         case BTRFS_IOC_SUBVOL_CREATE:
1254                 return btrfs_ioctl_snap_create(file, argp, 1);
1255         case BTRFS_IOC_DEFRAG:
1256                 return btrfs_ioctl_defrag(file);
1257         case BTRFS_IOC_RESIZE:
1258                 return btrfs_ioctl_resize(root, argp);
1259         case BTRFS_IOC_ADD_DEV:
1260                 return btrfs_ioctl_add_dev(root, argp);
1261         case BTRFS_IOC_RM_DEV:
1262                 return btrfs_ioctl_rm_dev(root, argp);
1263         case BTRFS_IOC_BALANCE:
1264                 return btrfs_balance(root->fs_info->dev_root);
1265         case BTRFS_IOC_CLONE:
1266                 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
1267         case BTRFS_IOC_CLONE_RANGE:
1268                 return btrfs_ioctl_clone_range(file, argp);
1269         case BTRFS_IOC_TRANS_START:
1270                 return btrfs_ioctl_trans_start(file);
1271         case BTRFS_IOC_TRANS_END:
1272                 return btrfs_ioctl_trans_end(file);
1273         case BTRFS_IOC_SYNC:
1274                 btrfs_sync_fs(file->f_dentry->d_sb, 1);
1275                 return 0;
1276         }
1277
1278         return -ENOTTY;
1279 }