include cleanup: Update gfp.h and slab.h includes to prepare for breaking implicit...
[pandora-kernel.git] / fs / btrfs / ioctl.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/fsnotify.h>
25 #include <linux/pagemap.h>
26 #include <linux/highmem.h>
27 #include <linux/time.h>
28 #include <linux/init.h>
29 #include <linux/string.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mount.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/swap.h>
35 #include <linux/writeback.h>
36 #include <linux/statfs.h>
37 #include <linux/compat.h>
38 #include <linux/bit_spinlock.h>
39 #include <linux/security.h>
40 #include <linux/xattr.h>
41 #include <linux/vmalloc.h>
42 #include <linux/slab.h>
43 #include "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 #include "ctree.h"
53
54 /* Mask out flags that are inappropriate for the given type of inode. */
55 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
56 {
57         if (S_ISDIR(mode))
58                 return flags;
59         else if (S_ISREG(mode))
60                 return flags & ~FS_DIRSYNC_FL;
61         else
62                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
63 }
64
65 /*
66  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
67  */
68 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
69 {
70         unsigned int iflags = 0;
71
72         if (flags & BTRFS_INODE_SYNC)
73                 iflags |= FS_SYNC_FL;
74         if (flags & BTRFS_INODE_IMMUTABLE)
75                 iflags |= FS_IMMUTABLE_FL;
76         if (flags & BTRFS_INODE_APPEND)
77                 iflags |= FS_APPEND_FL;
78         if (flags & BTRFS_INODE_NODUMP)
79                 iflags |= FS_NODUMP_FL;
80         if (flags & BTRFS_INODE_NOATIME)
81                 iflags |= FS_NOATIME_FL;
82         if (flags & BTRFS_INODE_DIRSYNC)
83                 iflags |= FS_DIRSYNC_FL;
84
85         return iflags;
86 }
87
88 /*
89  * Update inode->i_flags based on the btrfs internal flags.
90  */
91 void btrfs_update_iflags(struct inode *inode)
92 {
93         struct btrfs_inode *ip = BTRFS_I(inode);
94
95         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
96
97         if (ip->flags & BTRFS_INODE_SYNC)
98                 inode->i_flags |= S_SYNC;
99         if (ip->flags & BTRFS_INODE_IMMUTABLE)
100                 inode->i_flags |= S_IMMUTABLE;
101         if (ip->flags & BTRFS_INODE_APPEND)
102                 inode->i_flags |= S_APPEND;
103         if (ip->flags & BTRFS_INODE_NOATIME)
104                 inode->i_flags |= S_NOATIME;
105         if (ip->flags & BTRFS_INODE_DIRSYNC)
106                 inode->i_flags |= S_DIRSYNC;
107 }
108
109 /*
110  * Inherit flags from the parent inode.
111  *
112  * Unlike extN we don't have any flags we don't want to inherit currently.
113  */
114 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
115 {
116         unsigned int flags;
117
118         if (!dir)
119                 return;
120
121         flags = BTRFS_I(dir)->flags;
122
123         if (S_ISREG(inode->i_mode))
124                 flags &= ~BTRFS_INODE_DIRSYNC;
125         else if (!S_ISDIR(inode->i_mode))
126                 flags &= (BTRFS_INODE_NODUMP | BTRFS_INODE_NOATIME);
127
128         BTRFS_I(inode)->flags = flags;
129         btrfs_update_iflags(inode);
130 }
131
132 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
133 {
134         struct btrfs_inode *ip = BTRFS_I(file->f_path.dentry->d_inode);
135         unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
136
137         if (copy_to_user(arg, &flags, sizeof(flags)))
138                 return -EFAULT;
139         return 0;
140 }
141
142 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
143 {
144         struct inode *inode = file->f_path.dentry->d_inode;
145         struct btrfs_inode *ip = BTRFS_I(inode);
146         struct btrfs_root *root = ip->root;
147         struct btrfs_trans_handle *trans;
148         unsigned int flags, oldflags;
149         int ret;
150
151         if (copy_from_user(&flags, arg, sizeof(flags)))
152                 return -EFAULT;
153
154         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
155                       FS_NOATIME_FL | FS_NODUMP_FL | \
156                       FS_SYNC_FL | FS_DIRSYNC_FL))
157                 return -EOPNOTSUPP;
158
159         if (!is_owner_or_cap(inode))
160                 return -EACCES;
161
162         mutex_lock(&inode->i_mutex);
163
164         flags = btrfs_mask_flags(inode->i_mode, flags);
165         oldflags = btrfs_flags_to_ioctl(ip->flags);
166         if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
167                 if (!capable(CAP_LINUX_IMMUTABLE)) {
168                         ret = -EPERM;
169                         goto out_unlock;
170                 }
171         }
172
173         ret = mnt_want_write(file->f_path.mnt);
174         if (ret)
175                 goto out_unlock;
176
177         if (flags & FS_SYNC_FL)
178                 ip->flags |= BTRFS_INODE_SYNC;
179         else
180                 ip->flags &= ~BTRFS_INODE_SYNC;
181         if (flags & FS_IMMUTABLE_FL)
182                 ip->flags |= BTRFS_INODE_IMMUTABLE;
183         else
184                 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
185         if (flags & FS_APPEND_FL)
186                 ip->flags |= BTRFS_INODE_APPEND;
187         else
188                 ip->flags &= ~BTRFS_INODE_APPEND;
189         if (flags & FS_NODUMP_FL)
190                 ip->flags |= BTRFS_INODE_NODUMP;
191         else
192                 ip->flags &= ~BTRFS_INODE_NODUMP;
193         if (flags & FS_NOATIME_FL)
194                 ip->flags |= BTRFS_INODE_NOATIME;
195         else
196                 ip->flags &= ~BTRFS_INODE_NOATIME;
197         if (flags & FS_DIRSYNC_FL)
198                 ip->flags |= BTRFS_INODE_DIRSYNC;
199         else
200                 ip->flags &= ~BTRFS_INODE_DIRSYNC;
201
202
203         trans = btrfs_join_transaction(root, 1);
204         BUG_ON(!trans);
205
206         ret = btrfs_update_inode(trans, root, inode);
207         BUG_ON(ret);
208
209         btrfs_update_iflags(inode);
210         inode->i_ctime = CURRENT_TIME;
211         btrfs_end_transaction(trans, root);
212
213         mnt_drop_write(file->f_path.mnt);
214  out_unlock:
215         mutex_unlock(&inode->i_mutex);
216         return 0;
217 }
218
219 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
220 {
221         struct inode *inode = file->f_path.dentry->d_inode;
222
223         return put_user(inode->i_generation, arg);
224 }
225
226 static noinline int create_subvol(struct btrfs_root *root,
227                                   struct dentry *dentry,
228                                   char *name, int namelen)
229 {
230         struct btrfs_trans_handle *trans;
231         struct btrfs_key key;
232         struct btrfs_root_item root_item;
233         struct btrfs_inode_item *inode_item;
234         struct extent_buffer *leaf;
235         struct btrfs_root *new_root;
236         struct inode *dir = dentry->d_parent->d_inode;
237         int ret;
238         int err;
239         u64 objectid;
240         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
241         u64 index = 0;
242
243         /*
244          * 1 - inode item
245          * 2 - refs
246          * 1 - root item
247          * 2 - dir items
248          */
249         ret = btrfs_reserve_metadata_space(root, 6);
250         if (ret)
251                 return ret;
252
253         trans = btrfs_start_transaction(root, 1);
254         BUG_ON(!trans);
255
256         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
257                                        0, &objectid);
258         if (ret)
259                 goto fail;
260
261         leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
262                                       0, objectid, NULL, 0, 0, 0);
263         if (IS_ERR(leaf)) {
264                 ret = PTR_ERR(leaf);
265                 goto fail;
266         }
267
268         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
269         btrfs_set_header_bytenr(leaf, leaf->start);
270         btrfs_set_header_generation(leaf, trans->transid);
271         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
272         btrfs_set_header_owner(leaf, objectid);
273
274         write_extent_buffer(leaf, root->fs_info->fsid,
275                             (unsigned long)btrfs_header_fsid(leaf),
276                             BTRFS_FSID_SIZE);
277         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
278                             (unsigned long)btrfs_header_chunk_tree_uuid(leaf),
279                             BTRFS_UUID_SIZE);
280         btrfs_mark_buffer_dirty(leaf);
281
282         inode_item = &root_item.inode;
283         memset(inode_item, 0, sizeof(*inode_item));
284         inode_item->generation = cpu_to_le64(1);
285         inode_item->size = cpu_to_le64(3);
286         inode_item->nlink = cpu_to_le32(1);
287         inode_item->nbytes = cpu_to_le64(root->leafsize);
288         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
289
290         btrfs_set_root_bytenr(&root_item, leaf->start);
291         btrfs_set_root_generation(&root_item, trans->transid);
292         btrfs_set_root_level(&root_item, 0);
293         btrfs_set_root_refs(&root_item, 1);
294         btrfs_set_root_used(&root_item, leaf->len);
295         btrfs_set_root_last_snapshot(&root_item, 0);
296
297         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
298         root_item.drop_level = 0;
299
300         btrfs_tree_unlock(leaf);
301         free_extent_buffer(leaf);
302         leaf = NULL;
303
304         btrfs_set_root_dirid(&root_item, new_dirid);
305
306         key.objectid = objectid;
307         key.offset = 0;
308         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
309         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
310                                 &root_item);
311         if (ret)
312                 goto fail;
313
314         key.offset = (u64)-1;
315         new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
316         BUG_ON(IS_ERR(new_root));
317
318         btrfs_record_root_in_trans(trans, new_root);
319
320         ret = btrfs_create_subvol_root(trans, new_root, new_dirid,
321                                        BTRFS_I(dir)->block_group);
322         /*
323          * insert the directory item
324          */
325         ret = btrfs_set_inode_index(dir, &index);
326         BUG_ON(ret);
327
328         ret = btrfs_insert_dir_item(trans, root,
329                                     name, namelen, dir->i_ino, &key,
330                                     BTRFS_FT_DIR, index);
331         if (ret)
332                 goto fail;
333
334         btrfs_i_size_write(dir, dir->i_size + namelen * 2);
335         ret = btrfs_update_inode(trans, root, dir);
336         BUG_ON(ret);
337
338         ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
339                                  objectid, root->root_key.objectid,
340                                  dir->i_ino, index, name, namelen);
341
342         BUG_ON(ret);
343
344         d_instantiate(dentry, btrfs_lookup_dentry(dir, dentry));
345 fail:
346         err = btrfs_commit_transaction(trans, root);
347         if (err && !ret)
348                 ret = err;
349
350         btrfs_unreserve_metadata_space(root, 6);
351         return ret;
352 }
353
354 static int create_snapshot(struct btrfs_root *root, struct dentry *dentry,
355                            char *name, int namelen)
356 {
357         struct inode *inode;
358         struct btrfs_pending_snapshot *pending_snapshot;
359         struct btrfs_trans_handle *trans;
360         int ret;
361
362         if (!root->ref_cows)
363                 return -EINVAL;
364
365         /*
366          * 1 - inode item
367          * 2 - refs
368          * 1 - root item
369          * 2 - dir items
370          */
371         ret = btrfs_reserve_metadata_space(root, 6);
372         if (ret)
373                 goto fail;
374
375         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
376         if (!pending_snapshot) {
377                 ret = -ENOMEM;
378                 btrfs_unreserve_metadata_space(root, 6);
379                 goto fail;
380         }
381         pending_snapshot->name = kmalloc(namelen + 1, GFP_NOFS);
382         if (!pending_snapshot->name) {
383                 ret = -ENOMEM;
384                 kfree(pending_snapshot);
385                 btrfs_unreserve_metadata_space(root, 6);
386                 goto fail;
387         }
388         memcpy(pending_snapshot->name, name, namelen);
389         pending_snapshot->name[namelen] = '\0';
390         pending_snapshot->dentry = dentry;
391         trans = btrfs_start_transaction(root, 1);
392         BUG_ON(!trans);
393         pending_snapshot->root = root;
394         list_add(&pending_snapshot->list,
395                  &trans->transaction->pending_snapshots);
396         ret = btrfs_commit_transaction(trans, root);
397         BUG_ON(ret);
398         btrfs_unreserve_metadata_space(root, 6);
399
400         inode = btrfs_lookup_dentry(dentry->d_parent->d_inode, dentry);
401         if (IS_ERR(inode)) {
402                 ret = PTR_ERR(inode);
403                 goto fail;
404         }
405         BUG_ON(!inode);
406         d_instantiate(dentry, inode);
407         ret = 0;
408 fail:
409         return ret;
410 }
411
412 /* copy of may_create in fs/namei.c() */
413 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
414 {
415         if (child->d_inode)
416                 return -EEXIST;
417         if (IS_DEADDIR(dir))
418                 return -ENOENT;
419         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
420 }
421
422 /*
423  * Create a new subvolume below @parent.  This is largely modeled after
424  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
425  * inside this filesystem so it's quite a bit simpler.
426  */
427 static noinline int btrfs_mksubvol(struct path *parent,
428                                    char *name, int namelen,
429                                    struct btrfs_root *snap_src)
430 {
431         struct inode *dir  = parent->dentry->d_inode;
432         struct dentry *dentry;
433         int error;
434
435         mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
436
437         dentry = lookup_one_len(name, parent->dentry, namelen);
438         error = PTR_ERR(dentry);
439         if (IS_ERR(dentry))
440                 goto out_unlock;
441
442         error = -EEXIST;
443         if (dentry->d_inode)
444                 goto out_dput;
445
446         error = mnt_want_write(parent->mnt);
447         if (error)
448                 goto out_dput;
449
450         error = btrfs_may_create(dir, dentry);
451         if (error)
452                 goto out_drop_write;
453
454         down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
455
456         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
457                 goto out_up_read;
458
459         if (snap_src) {
460                 error = create_snapshot(snap_src, dentry,
461                                         name, namelen);
462         } else {
463                 error = create_subvol(BTRFS_I(dir)->root, dentry,
464                                       name, namelen);
465         }
466         if (!error)
467                 fsnotify_mkdir(dir, dentry);
468 out_up_read:
469         up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
470 out_drop_write:
471         mnt_drop_write(parent->mnt);
472 out_dput:
473         dput(dentry);
474 out_unlock:
475         mutex_unlock(&dir->i_mutex);
476         return error;
477 }
478
479 static int should_defrag_range(struct inode *inode, u64 start, u64 len,
480                                int thresh, u64 *last_len, u64 *skip,
481                                u64 *defrag_end)
482 {
483         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
484         struct extent_map *em = NULL;
485         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
486         int ret = 1;
487
488
489         if (thresh == 0)
490                 thresh = 256 * 1024;
491
492         /*
493          * make sure that once we start defragging and extent, we keep on
494          * defragging it
495          */
496         if (start < *defrag_end)
497                 return 1;
498
499         *skip = 0;
500
501         /*
502          * hopefully we have this extent in the tree already, try without
503          * the full extent lock
504          */
505         read_lock(&em_tree->lock);
506         em = lookup_extent_mapping(em_tree, start, len);
507         read_unlock(&em_tree->lock);
508
509         if (!em) {
510                 /* get the big lock and read metadata off disk */
511                 lock_extent(io_tree, start, start + len - 1, GFP_NOFS);
512                 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
513                 unlock_extent(io_tree, start, start + len - 1, GFP_NOFS);
514
515                 if (!em)
516                         return 0;
517         }
518
519         /* this will cover holes, and inline extents */
520         if (em->block_start >= EXTENT_MAP_LAST_BYTE)
521                 ret = 0;
522
523         /*
524          * we hit a real extent, if it is big don't bother defragging it again
525          */
526         if ((*last_len == 0 || *last_len >= thresh) && em->len >= thresh)
527                 ret = 0;
528
529         /*
530          * last_len ends up being a counter of how many bytes we've defragged.
531          * every time we choose not to defrag an extent, we reset *last_len
532          * so that the next tiny extent will force a defrag.
533          *
534          * The end result of this is that tiny extents before a single big
535          * extent will force at least part of that big extent to be defragged.
536          */
537         if (ret) {
538                 *last_len += len;
539                 *defrag_end = extent_map_end(em);
540         } else {
541                 *last_len = 0;
542                 *skip = extent_map_end(em);
543                 *defrag_end = 0;
544         }
545
546         free_extent_map(em);
547         return ret;
548 }
549
550 static int btrfs_defrag_file(struct file *file,
551                              struct btrfs_ioctl_defrag_range_args *range)
552 {
553         struct inode *inode = fdentry(file)->d_inode;
554         struct btrfs_root *root = BTRFS_I(inode)->root;
555         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
556         struct btrfs_ordered_extent *ordered;
557         struct page *page;
558         unsigned long last_index;
559         unsigned long ra_pages = root->fs_info->bdi.ra_pages;
560         unsigned long total_read = 0;
561         u64 page_start;
562         u64 page_end;
563         u64 last_len = 0;
564         u64 skip = 0;
565         u64 defrag_end = 0;
566         unsigned long i;
567         int ret;
568
569         if (inode->i_size == 0)
570                 return 0;
571
572         if (range->start + range->len > range->start) {
573                 last_index = min_t(u64, inode->i_size - 1,
574                          range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
575         } else {
576                 last_index = (inode->i_size - 1) >> PAGE_CACHE_SHIFT;
577         }
578
579         i = range->start >> PAGE_CACHE_SHIFT;
580         while (i <= last_index) {
581                 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
582                                         PAGE_CACHE_SIZE,
583                                         range->extent_thresh,
584                                         &last_len, &skip,
585                                         &defrag_end)) {
586                         unsigned long next;
587                         /*
588                          * the should_defrag function tells us how much to skip
589                          * bump our counter by the suggested amount
590                          */
591                         next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
592                         i = max(i + 1, next);
593                         continue;
594                 }
595
596                 if (total_read % ra_pages == 0) {
597                         btrfs_force_ra(inode->i_mapping, &file->f_ra, file, i,
598                                        min(last_index, i + ra_pages - 1));
599                 }
600                 total_read++;
601                 mutex_lock(&inode->i_mutex);
602                 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
603                         BTRFS_I(inode)->force_compress = 1;
604
605                 ret = btrfs_check_data_free_space(root, inode, PAGE_CACHE_SIZE);
606                 if (ret) {
607                         ret = -ENOSPC;
608                         break;
609                 }
610
611                 ret = btrfs_reserve_metadata_for_delalloc(root, inode, 1);
612                 if (ret) {
613                         btrfs_free_reserved_data_space(root, inode,
614                                                        PAGE_CACHE_SIZE);
615                         ret = -ENOSPC;
616                         break;
617                 }
618 again:
619                 if (inode->i_size == 0 ||
620                     i > ((inode->i_size - 1) >> PAGE_CACHE_SHIFT)) {
621                         ret = 0;
622                         goto err_reservations;
623                 }
624
625                 page = grab_cache_page(inode->i_mapping, i);
626                 if (!page)
627                         goto err_reservations;
628
629                 if (!PageUptodate(page)) {
630                         btrfs_readpage(NULL, page);
631                         lock_page(page);
632                         if (!PageUptodate(page)) {
633                                 unlock_page(page);
634                                 page_cache_release(page);
635                                 goto err_reservations;
636                         }
637                 }
638
639                 if (page->mapping != inode->i_mapping) {
640                         unlock_page(page);
641                         page_cache_release(page);
642                         goto again;
643                 }
644
645                 wait_on_page_writeback(page);
646
647                 if (PageDirty(page)) {
648                         btrfs_free_reserved_data_space(root, inode,
649                                                        PAGE_CACHE_SIZE);
650                         goto loop_unlock;
651                 }
652
653                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
654                 page_end = page_start + PAGE_CACHE_SIZE - 1;
655                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
656
657                 ordered = btrfs_lookup_ordered_extent(inode, page_start);
658                 if (ordered) {
659                         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
660                         unlock_page(page);
661                         page_cache_release(page);
662                         btrfs_start_ordered_extent(inode, ordered, 1);
663                         btrfs_put_ordered_extent(ordered);
664                         goto again;
665                 }
666                 set_page_extent_mapped(page);
667
668                 /*
669                  * this makes sure page_mkwrite is called on the
670                  * page if it is dirtied again later
671                  */
672                 clear_page_dirty_for_io(page);
673                 clear_extent_bits(&BTRFS_I(inode)->io_tree, page_start,
674                                   page_end, EXTENT_DIRTY | EXTENT_DELALLOC |
675                                   EXTENT_DO_ACCOUNTING, GFP_NOFS);
676
677                 btrfs_set_extent_delalloc(inode, page_start, page_end, NULL);
678                 ClearPageChecked(page);
679                 set_page_dirty(page);
680                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
681
682 loop_unlock:
683                 unlock_page(page);
684                 page_cache_release(page);
685                 mutex_unlock(&inode->i_mutex);
686
687                 btrfs_unreserve_metadata_for_delalloc(root, inode, 1);
688                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, 1);
689                 i++;
690         }
691
692         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
693                 filemap_flush(inode->i_mapping);
694
695         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
696                 /* the filemap_flush will queue IO into the worker threads, but
697                  * we have to make sure the IO is actually started and that
698                  * ordered extents get created before we return
699                  */
700                 atomic_inc(&root->fs_info->async_submit_draining);
701                 while (atomic_read(&root->fs_info->nr_async_submits) ||
702                       atomic_read(&root->fs_info->async_delalloc_pages)) {
703                         wait_event(root->fs_info->async_submit_wait,
704                            (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
705                             atomic_read(&root->fs_info->async_delalloc_pages) == 0));
706                 }
707                 atomic_dec(&root->fs_info->async_submit_draining);
708
709                 mutex_lock(&inode->i_mutex);
710                 BTRFS_I(inode)->force_compress = 0;
711                 mutex_unlock(&inode->i_mutex);
712         }
713
714         return 0;
715
716 err_reservations:
717         mutex_unlock(&inode->i_mutex);
718         btrfs_free_reserved_data_space(root, inode, PAGE_CACHE_SIZE);
719         btrfs_unreserve_metadata_for_delalloc(root, inode, 1);
720         return ret;
721 }
722
723 static noinline int btrfs_ioctl_resize(struct btrfs_root *root,
724                                         void __user *arg)
725 {
726         u64 new_size;
727         u64 old_size;
728         u64 devid = 1;
729         struct btrfs_ioctl_vol_args *vol_args;
730         struct btrfs_trans_handle *trans;
731         struct btrfs_device *device = NULL;
732         char *sizestr;
733         char *devstr = NULL;
734         int ret = 0;
735         int namelen;
736         int mod = 0;
737
738         if (root->fs_info->sb->s_flags & MS_RDONLY)
739                 return -EROFS;
740
741         if (!capable(CAP_SYS_ADMIN))
742                 return -EPERM;
743
744         vol_args = memdup_user(arg, sizeof(*vol_args));
745         if (IS_ERR(vol_args))
746                 return PTR_ERR(vol_args);
747
748         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
749         namelen = strlen(vol_args->name);
750
751         mutex_lock(&root->fs_info->volume_mutex);
752         sizestr = vol_args->name;
753         devstr = strchr(sizestr, ':');
754         if (devstr) {
755                 char *end;
756                 sizestr = devstr + 1;
757                 *devstr = '\0';
758                 devstr = vol_args->name;
759                 devid = simple_strtoull(devstr, &end, 10);
760                 printk(KERN_INFO "resizing devid %llu\n",
761                        (unsigned long long)devid);
762         }
763         device = btrfs_find_device(root, devid, NULL, NULL);
764         if (!device) {
765                 printk(KERN_INFO "resizer unable to find device %llu\n",
766                        (unsigned long long)devid);
767                 ret = -EINVAL;
768                 goto out_unlock;
769         }
770         if (!strcmp(sizestr, "max"))
771                 new_size = device->bdev->bd_inode->i_size;
772         else {
773                 if (sizestr[0] == '-') {
774                         mod = -1;
775                         sizestr++;
776                 } else if (sizestr[0] == '+') {
777                         mod = 1;
778                         sizestr++;
779                 }
780                 new_size = memparse(sizestr, NULL);
781                 if (new_size == 0) {
782                         ret = -EINVAL;
783                         goto out_unlock;
784                 }
785         }
786
787         old_size = device->total_bytes;
788
789         if (mod < 0) {
790                 if (new_size > old_size) {
791                         ret = -EINVAL;
792                         goto out_unlock;
793                 }
794                 new_size = old_size - new_size;
795         } else if (mod > 0) {
796                 new_size = old_size + new_size;
797         }
798
799         if (new_size < 256 * 1024 * 1024) {
800                 ret = -EINVAL;
801                 goto out_unlock;
802         }
803         if (new_size > device->bdev->bd_inode->i_size) {
804                 ret = -EFBIG;
805                 goto out_unlock;
806         }
807
808         do_div(new_size, root->sectorsize);
809         new_size *= root->sectorsize;
810
811         printk(KERN_INFO "new size for %s is %llu\n",
812                 device->name, (unsigned long long)new_size);
813
814         if (new_size > old_size) {
815                 trans = btrfs_start_transaction(root, 1);
816                 ret = btrfs_grow_device(trans, device, new_size);
817                 btrfs_commit_transaction(trans, root);
818         } else {
819                 ret = btrfs_shrink_device(device, new_size);
820         }
821
822 out_unlock:
823         mutex_unlock(&root->fs_info->volume_mutex);
824         kfree(vol_args);
825         return ret;
826 }
827
828 static noinline int btrfs_ioctl_snap_create(struct file *file,
829                                             void __user *arg, int subvol)
830 {
831         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
832         struct btrfs_ioctl_vol_args *vol_args;
833         struct file *src_file;
834         int namelen;
835         int ret = 0;
836
837         if (root->fs_info->sb->s_flags & MS_RDONLY)
838                 return -EROFS;
839
840         vol_args = memdup_user(arg, sizeof(*vol_args));
841         if (IS_ERR(vol_args))
842                 return PTR_ERR(vol_args);
843
844         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
845         namelen = strlen(vol_args->name);
846         if (strchr(vol_args->name, '/')) {
847                 ret = -EINVAL;
848                 goto out;
849         }
850
851         if (subvol) {
852                 ret = btrfs_mksubvol(&file->f_path, vol_args->name, namelen,
853                                      NULL);
854         } else {
855                 struct inode *src_inode;
856                 src_file = fget(vol_args->fd);
857                 if (!src_file) {
858                         ret = -EINVAL;
859                         goto out;
860                 }
861
862                 src_inode = src_file->f_path.dentry->d_inode;
863                 if (src_inode->i_sb != file->f_path.dentry->d_inode->i_sb) {
864                         printk(KERN_INFO "btrfs: Snapshot src from "
865                                "another FS\n");
866                         ret = -EINVAL;
867                         fput(src_file);
868                         goto out;
869                 }
870                 ret = btrfs_mksubvol(&file->f_path, vol_args->name, namelen,
871                                      BTRFS_I(src_inode)->root);
872                 fput(src_file);
873         }
874 out:
875         kfree(vol_args);
876         return ret;
877 }
878
879 /*
880  * helper to check if the subvolume references other subvolumes
881  */
882 static noinline int may_destroy_subvol(struct btrfs_root *root)
883 {
884         struct btrfs_path *path;
885         struct btrfs_key key;
886         int ret;
887
888         path = btrfs_alloc_path();
889         if (!path)
890                 return -ENOMEM;
891
892         key.objectid = root->root_key.objectid;
893         key.type = BTRFS_ROOT_REF_KEY;
894         key.offset = (u64)-1;
895
896         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
897                                 &key, path, 0, 0);
898         if (ret < 0)
899                 goto out;
900         BUG_ON(ret == 0);
901
902         ret = 0;
903         if (path->slots[0] > 0) {
904                 path->slots[0]--;
905                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
906                 if (key.objectid == root->root_key.objectid &&
907                     key.type == BTRFS_ROOT_REF_KEY)
908                         ret = -ENOTEMPTY;
909         }
910 out:
911         btrfs_free_path(path);
912         return ret;
913 }
914
915 static noinline int key_in_sk(struct btrfs_key *key,
916                               struct btrfs_ioctl_search_key *sk)
917 {
918         struct btrfs_key test;
919         int ret;
920
921         test.objectid = sk->min_objectid;
922         test.type = sk->min_type;
923         test.offset = sk->min_offset;
924
925         ret = btrfs_comp_cpu_keys(key, &test);
926         if (ret < 0)
927                 return 0;
928
929         test.objectid = sk->max_objectid;
930         test.type = sk->max_type;
931         test.offset = sk->max_offset;
932
933         ret = btrfs_comp_cpu_keys(key, &test);
934         if (ret > 0)
935                 return 0;
936         return 1;
937 }
938
939 static noinline int copy_to_sk(struct btrfs_root *root,
940                                struct btrfs_path *path,
941                                struct btrfs_key *key,
942                                struct btrfs_ioctl_search_key *sk,
943                                char *buf,
944                                unsigned long *sk_offset,
945                                int *num_found)
946 {
947         u64 found_transid;
948         struct extent_buffer *leaf;
949         struct btrfs_ioctl_search_header sh;
950         unsigned long item_off;
951         unsigned long item_len;
952         int nritems;
953         int i;
954         int slot;
955         int found = 0;
956         int ret = 0;
957
958         leaf = path->nodes[0];
959         slot = path->slots[0];
960         nritems = btrfs_header_nritems(leaf);
961
962         if (btrfs_header_generation(leaf) > sk->max_transid) {
963                 i = nritems;
964                 goto advance_key;
965         }
966         found_transid = btrfs_header_generation(leaf);
967
968         for (i = slot; i < nritems; i++) {
969                 item_off = btrfs_item_ptr_offset(leaf, i);
970                 item_len = btrfs_item_size_nr(leaf, i);
971
972                 if (item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
973                         item_len = 0;
974
975                 if (sizeof(sh) + item_len + *sk_offset >
976                     BTRFS_SEARCH_ARGS_BUFSIZE) {
977                         ret = 1;
978                         goto overflow;
979                 }
980
981                 btrfs_item_key_to_cpu(leaf, key, i);
982                 if (!key_in_sk(key, sk))
983                         continue;
984
985                 sh.objectid = key->objectid;
986                 sh.offset = key->offset;
987                 sh.type = key->type;
988                 sh.len = item_len;
989                 sh.transid = found_transid;
990
991                 /* copy search result header */
992                 memcpy(buf + *sk_offset, &sh, sizeof(sh));
993                 *sk_offset += sizeof(sh);
994
995                 if (item_len) {
996                         char *p = buf + *sk_offset;
997                         /* copy the item */
998                         read_extent_buffer(leaf, p,
999                                            item_off, item_len);
1000                         *sk_offset += item_len;
1001                 }
1002                 found++;
1003
1004                 if (*num_found >= sk->nr_items)
1005                         break;
1006         }
1007 advance_key:
1008         ret = 0;
1009         if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1010                 key->offset++;
1011         else if (key->type < (u8)-1 && key->type < sk->max_type) {
1012                 key->offset = 0;
1013                 key->type++;
1014         } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1015                 key->offset = 0;
1016                 key->type = 0;
1017                 key->objectid++;
1018         } else
1019                 ret = 1;
1020 overflow:
1021         *num_found += found;
1022         return ret;
1023 }
1024
1025 static noinline int search_ioctl(struct inode *inode,
1026                                  struct btrfs_ioctl_search_args *args)
1027 {
1028         struct btrfs_root *root;
1029         struct btrfs_key key;
1030         struct btrfs_key max_key;
1031         struct btrfs_path *path;
1032         struct btrfs_ioctl_search_key *sk = &args->key;
1033         struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1034         int ret;
1035         int num_found = 0;
1036         unsigned long sk_offset = 0;
1037
1038         path = btrfs_alloc_path();
1039         if (!path)
1040                 return -ENOMEM;
1041
1042         if (sk->tree_id == 0) {
1043                 /* search the root of the inode that was passed */
1044                 root = BTRFS_I(inode)->root;
1045         } else {
1046                 key.objectid = sk->tree_id;
1047                 key.type = BTRFS_ROOT_ITEM_KEY;
1048                 key.offset = (u64)-1;
1049                 root = btrfs_read_fs_root_no_name(info, &key);
1050                 if (IS_ERR(root)) {
1051                         printk(KERN_ERR "could not find root %llu\n",
1052                                sk->tree_id);
1053                         btrfs_free_path(path);
1054                         return -ENOENT;
1055                 }
1056         }
1057
1058         key.objectid = sk->min_objectid;
1059         key.type = sk->min_type;
1060         key.offset = sk->min_offset;
1061
1062         max_key.objectid = sk->max_objectid;
1063         max_key.type = sk->max_type;
1064         max_key.offset = sk->max_offset;
1065
1066         path->keep_locks = 1;
1067
1068         while(1) {
1069                 ret = btrfs_search_forward(root, &key, &max_key, path, 0,
1070                                            sk->min_transid);
1071                 if (ret != 0) {
1072                         if (ret > 0)
1073                                 ret = 0;
1074                         goto err;
1075                 }
1076                 ret = copy_to_sk(root, path, &key, sk, args->buf,
1077                                  &sk_offset, &num_found);
1078                 btrfs_release_path(root, path);
1079                 if (ret || num_found >= sk->nr_items)
1080                         break;
1081
1082         }
1083         ret = 0;
1084 err:
1085         sk->nr_items = num_found;
1086         btrfs_free_path(path);
1087         return ret;
1088 }
1089
1090 static noinline int btrfs_ioctl_tree_search(struct file *file,
1091                                            void __user *argp)
1092 {
1093          struct btrfs_ioctl_search_args *args;
1094          struct inode *inode;
1095          int ret;
1096
1097         if (!capable(CAP_SYS_ADMIN))
1098                 return -EPERM;
1099
1100         args = kmalloc(sizeof(*args), GFP_KERNEL);
1101         if (!args)
1102                 return -ENOMEM;
1103
1104         if (copy_from_user(args, argp, sizeof(*args))) {
1105                 kfree(args);
1106                 return -EFAULT;
1107         }
1108         inode = fdentry(file)->d_inode;
1109         ret = search_ioctl(inode, args);
1110         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1111                 ret = -EFAULT;
1112         kfree(args);
1113         return ret;
1114 }
1115
1116 /*
1117  * Search INODE_REFs to identify path name of 'dirid' directory
1118  * in a 'tree_id' tree. and sets path name to 'name'.
1119  */
1120 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
1121                                 u64 tree_id, u64 dirid, char *name)
1122 {
1123         struct btrfs_root *root;
1124         struct btrfs_key key;
1125         char *ptr;
1126         int ret = -1;
1127         int slot;
1128         int len;
1129         int total_len = 0;
1130         struct btrfs_inode_ref *iref;
1131         struct extent_buffer *l;
1132         struct btrfs_path *path;
1133
1134         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
1135                 name[0]='\0';
1136                 return 0;
1137         }
1138
1139         path = btrfs_alloc_path();
1140         if (!path)
1141                 return -ENOMEM;
1142
1143         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
1144
1145         key.objectid = tree_id;
1146         key.type = BTRFS_ROOT_ITEM_KEY;
1147         key.offset = (u64)-1;
1148         root = btrfs_read_fs_root_no_name(info, &key);
1149         if (IS_ERR(root)) {
1150                 printk(KERN_ERR "could not find root %llu\n", tree_id);
1151                 ret = -ENOENT;
1152                 goto out;
1153         }
1154
1155         key.objectid = dirid;
1156         key.type = BTRFS_INODE_REF_KEY;
1157         key.offset = (u64)-1;
1158
1159         while(1) {
1160                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1161                 if (ret < 0)
1162                         goto out;
1163
1164                 l = path->nodes[0];
1165                 slot = path->slots[0];
1166                 if (ret > 0 && slot > 0)
1167                         slot--;
1168                 btrfs_item_key_to_cpu(l, &key, slot);
1169
1170                 if (ret > 0 && (key.objectid != dirid ||
1171                                 key.type != BTRFS_INODE_REF_KEY)) {
1172                         ret = -ENOENT;
1173                         goto out;
1174                 }
1175
1176                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
1177                 len = btrfs_inode_ref_name_len(l, iref);
1178                 ptr -= len + 1;
1179                 total_len += len + 1;
1180                 if (ptr < name)
1181                         goto out;
1182
1183                 *(ptr + len) = '/';
1184                 read_extent_buffer(l, ptr,(unsigned long)(iref + 1), len);
1185
1186                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
1187                         break;
1188
1189                 btrfs_release_path(root, path);
1190                 key.objectid = key.offset;
1191                 key.offset = (u64)-1;
1192                 dirid = key.objectid;
1193
1194         }
1195         if (ptr < name)
1196                 goto out;
1197         memcpy(name, ptr, total_len);
1198         name[total_len]='\0';
1199         ret = 0;
1200 out:
1201         btrfs_free_path(path);
1202         return ret;
1203 }
1204
1205 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
1206                                            void __user *argp)
1207 {
1208          struct btrfs_ioctl_ino_lookup_args *args;
1209          struct inode *inode;
1210          int ret;
1211
1212         if (!capable(CAP_SYS_ADMIN))
1213                 return -EPERM;
1214
1215         args = kmalloc(sizeof(*args), GFP_KERNEL);
1216         if (copy_from_user(args, argp, sizeof(*args))) {
1217                 kfree(args);
1218                 return -EFAULT;
1219         }
1220         inode = fdentry(file)->d_inode;
1221
1222         if (args->treeid == 0)
1223                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
1224
1225         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
1226                                         args->treeid, args->objectid,
1227                                         args->name);
1228
1229         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1230                 ret = -EFAULT;
1231
1232         kfree(args);
1233         return ret;
1234 }
1235
1236 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
1237                                              void __user *arg)
1238 {
1239         struct dentry *parent = fdentry(file);
1240         struct dentry *dentry;
1241         struct inode *dir = parent->d_inode;
1242         struct inode *inode;
1243         struct btrfs_root *root = BTRFS_I(dir)->root;
1244         struct btrfs_root *dest = NULL;
1245         struct btrfs_ioctl_vol_args *vol_args;
1246         struct btrfs_trans_handle *trans;
1247         int namelen;
1248         int ret;
1249         int err = 0;
1250
1251         if (!capable(CAP_SYS_ADMIN))
1252                 return -EPERM;
1253
1254         vol_args = memdup_user(arg, sizeof(*vol_args));
1255         if (IS_ERR(vol_args))
1256                 return PTR_ERR(vol_args);
1257
1258         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1259         namelen = strlen(vol_args->name);
1260         if (strchr(vol_args->name, '/') ||
1261             strncmp(vol_args->name, "..", namelen) == 0) {
1262                 err = -EINVAL;
1263                 goto out;
1264         }
1265
1266         err = mnt_want_write(file->f_path.mnt);
1267         if (err)
1268                 goto out;
1269
1270         mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
1271         dentry = lookup_one_len(vol_args->name, parent, namelen);
1272         if (IS_ERR(dentry)) {
1273                 err = PTR_ERR(dentry);
1274                 goto out_unlock_dir;
1275         }
1276
1277         if (!dentry->d_inode) {
1278                 err = -ENOENT;
1279                 goto out_dput;
1280         }
1281
1282         inode = dentry->d_inode;
1283         if (inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
1284                 err = -EINVAL;
1285                 goto out_dput;
1286         }
1287
1288         dest = BTRFS_I(inode)->root;
1289
1290         mutex_lock(&inode->i_mutex);
1291         err = d_invalidate(dentry);
1292         if (err)
1293                 goto out_unlock;
1294
1295         down_write(&root->fs_info->subvol_sem);
1296
1297         err = may_destroy_subvol(dest);
1298         if (err)
1299                 goto out_up_write;
1300
1301         trans = btrfs_start_transaction(root, 1);
1302         ret = btrfs_unlink_subvol(trans, root, dir,
1303                                 dest->root_key.objectid,
1304                                 dentry->d_name.name,
1305                                 dentry->d_name.len);
1306         BUG_ON(ret);
1307
1308         btrfs_record_root_in_trans(trans, dest);
1309
1310         memset(&dest->root_item.drop_progress, 0,
1311                 sizeof(dest->root_item.drop_progress));
1312         dest->root_item.drop_level = 0;
1313         btrfs_set_root_refs(&dest->root_item, 0);
1314
1315         ret = btrfs_insert_orphan_item(trans,
1316                                 root->fs_info->tree_root,
1317                                 dest->root_key.objectid);
1318         BUG_ON(ret);
1319
1320         ret = btrfs_commit_transaction(trans, root);
1321         BUG_ON(ret);
1322         inode->i_flags |= S_DEAD;
1323 out_up_write:
1324         up_write(&root->fs_info->subvol_sem);
1325 out_unlock:
1326         mutex_unlock(&inode->i_mutex);
1327         if (!err) {
1328                 shrink_dcache_sb(root->fs_info->sb);
1329                 btrfs_invalidate_inodes(dest);
1330                 d_delete(dentry);
1331         }
1332 out_dput:
1333         dput(dentry);
1334 out_unlock_dir:
1335         mutex_unlock(&dir->i_mutex);
1336         mnt_drop_write(file->f_path.mnt);
1337 out:
1338         kfree(vol_args);
1339         return err;
1340 }
1341
1342 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
1343 {
1344         struct inode *inode = fdentry(file)->d_inode;
1345         struct btrfs_root *root = BTRFS_I(inode)->root;
1346         struct btrfs_ioctl_defrag_range_args *range;
1347         int ret;
1348
1349         ret = mnt_want_write(file->f_path.mnt);
1350         if (ret)
1351                 return ret;
1352
1353         switch (inode->i_mode & S_IFMT) {
1354         case S_IFDIR:
1355                 if (!capable(CAP_SYS_ADMIN)) {
1356                         ret = -EPERM;
1357                         goto out;
1358                 }
1359                 btrfs_defrag_root(root, 0);
1360                 btrfs_defrag_root(root->fs_info->extent_root, 0);
1361                 break;
1362         case S_IFREG:
1363                 if (!(file->f_mode & FMODE_WRITE)) {
1364                         ret = -EINVAL;
1365                         goto out;
1366                 }
1367
1368                 range = kzalloc(sizeof(*range), GFP_KERNEL);
1369                 if (!range) {
1370                         ret = -ENOMEM;
1371                         goto out;
1372                 }
1373
1374                 if (argp) {
1375                         if (copy_from_user(range, argp,
1376                                            sizeof(*range))) {
1377                                 ret = -EFAULT;
1378                                 kfree(range);
1379                         }
1380                         /* compression requires us to start the IO */
1381                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1382                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
1383                                 range->extent_thresh = (u32)-1;
1384                         }
1385                 } else {
1386                         /* the rest are all set to zero by kzalloc */
1387                         range->len = (u64)-1;
1388                 }
1389                 btrfs_defrag_file(file, range);
1390                 kfree(range);
1391                 break;
1392         }
1393 out:
1394         mnt_drop_write(file->f_path.mnt);
1395         return ret;
1396 }
1397
1398 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
1399 {
1400         struct btrfs_ioctl_vol_args *vol_args;
1401         int ret;
1402
1403         if (!capable(CAP_SYS_ADMIN))
1404                 return -EPERM;
1405
1406         vol_args = memdup_user(arg, sizeof(*vol_args));
1407         if (IS_ERR(vol_args))
1408                 return PTR_ERR(vol_args);
1409
1410         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1411         ret = btrfs_init_new_device(root, vol_args->name);
1412
1413         kfree(vol_args);
1414         return ret;
1415 }
1416
1417 static long btrfs_ioctl_rm_dev(struct btrfs_root *root, void __user *arg)
1418 {
1419         struct btrfs_ioctl_vol_args *vol_args;
1420         int ret;
1421
1422         if (!capable(CAP_SYS_ADMIN))
1423                 return -EPERM;
1424
1425         if (root->fs_info->sb->s_flags & MS_RDONLY)
1426                 return -EROFS;
1427
1428         vol_args = memdup_user(arg, sizeof(*vol_args));
1429         if (IS_ERR(vol_args))
1430                 return PTR_ERR(vol_args);
1431
1432         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1433         ret = btrfs_rm_device(root, vol_args->name);
1434
1435         kfree(vol_args);
1436         return ret;
1437 }
1438
1439 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
1440                                        u64 off, u64 olen, u64 destoff)
1441 {
1442         struct inode *inode = fdentry(file)->d_inode;
1443         struct btrfs_root *root = BTRFS_I(inode)->root;
1444         struct file *src_file;
1445         struct inode *src;
1446         struct btrfs_trans_handle *trans;
1447         struct btrfs_path *path;
1448         struct extent_buffer *leaf;
1449         char *buf;
1450         struct btrfs_key key;
1451         u32 nritems;
1452         int slot;
1453         int ret;
1454         u64 len = olen;
1455         u64 bs = root->fs_info->sb->s_blocksize;
1456         u64 hint_byte;
1457
1458         /*
1459          * TODO:
1460          * - split compressed inline extents.  annoying: we need to
1461          *   decompress into destination's address_space (the file offset
1462          *   may change, so source mapping won't do), then recompress (or
1463          *   otherwise reinsert) a subrange.
1464          * - allow ranges within the same file to be cloned (provided
1465          *   they don't overlap)?
1466          */
1467
1468         /* the destination must be opened for writing */
1469         if (!(file->f_mode & FMODE_WRITE))
1470                 return -EINVAL;
1471
1472         ret = mnt_want_write(file->f_path.mnt);
1473         if (ret)
1474                 return ret;
1475
1476         src_file = fget(srcfd);
1477         if (!src_file) {
1478                 ret = -EBADF;
1479                 goto out_drop_write;
1480         }
1481         src = src_file->f_dentry->d_inode;
1482
1483         ret = -EINVAL;
1484         if (src == inode)
1485                 goto out_fput;
1486
1487         ret = -EISDIR;
1488         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
1489                 goto out_fput;
1490
1491         ret = -EXDEV;
1492         if (src->i_sb != inode->i_sb || BTRFS_I(src)->root != root)
1493                 goto out_fput;
1494
1495         ret = -ENOMEM;
1496         buf = vmalloc(btrfs_level_size(root, 0));
1497         if (!buf)
1498                 goto out_fput;
1499
1500         path = btrfs_alloc_path();
1501         if (!path) {
1502                 vfree(buf);
1503                 goto out_fput;
1504         }
1505         path->reada = 2;
1506
1507         if (inode < src) {
1508                 mutex_lock(&inode->i_mutex);
1509                 mutex_lock(&src->i_mutex);
1510         } else {
1511                 mutex_lock(&src->i_mutex);
1512                 mutex_lock(&inode->i_mutex);
1513         }
1514
1515         /* determine range to clone */
1516         ret = -EINVAL;
1517         if (off >= src->i_size || off + len > src->i_size)
1518                 goto out_unlock;
1519         if (len == 0)
1520                 olen = len = src->i_size - off;
1521         /* if we extend to eof, continue to block boundary */
1522         if (off + len == src->i_size)
1523                 len = ((src->i_size + bs-1) & ~(bs-1))
1524                         - off;
1525
1526         /* verify the end result is block aligned */
1527         if ((off & (bs-1)) ||
1528             ((off + len) & (bs-1)))
1529                 goto out_unlock;
1530
1531         /* do any pending delalloc/csum calc on src, one way or
1532            another, and lock file content */
1533         while (1) {
1534                 struct btrfs_ordered_extent *ordered;
1535                 lock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
1536                 ordered = btrfs_lookup_first_ordered_extent(inode, off+len);
1537                 if (BTRFS_I(src)->delalloc_bytes == 0 && !ordered)
1538                         break;
1539                 unlock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
1540                 if (ordered)
1541                         btrfs_put_ordered_extent(ordered);
1542                 btrfs_wait_ordered_range(src, off, off+len);
1543         }
1544
1545         trans = btrfs_start_transaction(root, 1);
1546         BUG_ON(!trans);
1547
1548         /* punch hole in destination first */
1549         btrfs_drop_extents(trans, inode, off, off + len, &hint_byte, 1);
1550
1551         /* clone data */
1552         key.objectid = src->i_ino;
1553         key.type = BTRFS_EXTENT_DATA_KEY;
1554         key.offset = 0;
1555
1556         while (1) {
1557                 /*
1558                  * note the key will change type as we walk through the
1559                  * tree.
1560                  */
1561                 ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
1562                 if (ret < 0)
1563                         goto out;
1564
1565                 nritems = btrfs_header_nritems(path->nodes[0]);
1566                 if (path->slots[0] >= nritems) {
1567                         ret = btrfs_next_leaf(root, path);
1568                         if (ret < 0)
1569                                 goto out;
1570                         if (ret > 0)
1571                                 break;
1572                         nritems = btrfs_header_nritems(path->nodes[0]);
1573                 }
1574                 leaf = path->nodes[0];
1575                 slot = path->slots[0];
1576
1577                 btrfs_item_key_to_cpu(leaf, &key, slot);
1578                 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
1579                     key.objectid != src->i_ino)
1580                         break;
1581
1582                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
1583                         struct btrfs_file_extent_item *extent;
1584                         int type;
1585                         u32 size;
1586                         struct btrfs_key new_key;
1587                         u64 disko = 0, diskl = 0;
1588                         u64 datao = 0, datal = 0;
1589                         u8 comp;
1590
1591                         size = btrfs_item_size_nr(leaf, slot);
1592                         read_extent_buffer(leaf, buf,
1593                                            btrfs_item_ptr_offset(leaf, slot),
1594                                            size);
1595
1596                         extent = btrfs_item_ptr(leaf, slot,
1597                                                 struct btrfs_file_extent_item);
1598                         comp = btrfs_file_extent_compression(leaf, extent);
1599                         type = btrfs_file_extent_type(leaf, extent);
1600                         if (type == BTRFS_FILE_EXTENT_REG ||
1601                             type == BTRFS_FILE_EXTENT_PREALLOC) {
1602                                 disko = btrfs_file_extent_disk_bytenr(leaf,
1603                                                                       extent);
1604                                 diskl = btrfs_file_extent_disk_num_bytes(leaf,
1605                                                                  extent);
1606                                 datao = btrfs_file_extent_offset(leaf, extent);
1607                                 datal = btrfs_file_extent_num_bytes(leaf,
1608                                                                     extent);
1609                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
1610                                 /* take upper bound, may be compressed */
1611                                 datal = btrfs_file_extent_ram_bytes(leaf,
1612                                                                     extent);
1613                         }
1614                         btrfs_release_path(root, path);
1615
1616                         if (key.offset + datal < off ||
1617                             key.offset >= off+len)
1618                                 goto next;
1619
1620                         memcpy(&new_key, &key, sizeof(new_key));
1621                         new_key.objectid = inode->i_ino;
1622                         new_key.offset = key.offset + destoff - off;
1623
1624                         if (type == BTRFS_FILE_EXTENT_REG ||
1625                             type == BTRFS_FILE_EXTENT_PREALLOC) {
1626                                 ret = btrfs_insert_empty_item(trans, root, path,
1627                                                               &new_key, size);
1628                                 if (ret)
1629                                         goto out;
1630
1631                                 leaf = path->nodes[0];
1632                                 slot = path->slots[0];
1633                                 write_extent_buffer(leaf, buf,
1634                                             btrfs_item_ptr_offset(leaf, slot),
1635                                             size);
1636
1637                                 extent = btrfs_item_ptr(leaf, slot,
1638                                                 struct btrfs_file_extent_item);
1639
1640                                 if (off > key.offset) {
1641                                         datao += off - key.offset;
1642                                         datal -= off - key.offset;
1643                                 }
1644
1645                                 if (key.offset + datal > off + len)
1646                                         datal = off + len - key.offset;
1647
1648                                 /* disko == 0 means it's a hole */
1649                                 if (!disko)
1650                                         datao = 0;
1651
1652                                 btrfs_set_file_extent_offset(leaf, extent,
1653                                                              datao);
1654                                 btrfs_set_file_extent_num_bytes(leaf, extent,
1655                                                                 datal);
1656                                 if (disko) {
1657                                         inode_add_bytes(inode, datal);
1658                                         ret = btrfs_inc_extent_ref(trans, root,
1659                                                         disko, diskl, 0,
1660                                                         root->root_key.objectid,
1661                                                         inode->i_ino,
1662                                                         new_key.offset - datao);
1663                                         BUG_ON(ret);
1664                                 }
1665                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
1666                                 u64 skip = 0;
1667                                 u64 trim = 0;
1668                                 if (off > key.offset) {
1669                                         skip = off - key.offset;
1670                                         new_key.offset += skip;
1671                                 }
1672
1673                                 if (key.offset + datal > off+len)
1674                                         trim = key.offset + datal - (off+len);
1675
1676                                 if (comp && (skip || trim)) {
1677                                         ret = -EINVAL;
1678                                         goto out;
1679                                 }
1680                                 size -= skip + trim;
1681                                 datal -= skip + trim;
1682                                 ret = btrfs_insert_empty_item(trans, root, path,
1683                                                               &new_key, size);
1684                                 if (ret)
1685                                         goto out;
1686
1687                                 if (skip) {
1688                                         u32 start =
1689                                           btrfs_file_extent_calc_inline_size(0);
1690                                         memmove(buf+start, buf+start+skip,
1691                                                 datal);
1692                                 }
1693
1694                                 leaf = path->nodes[0];
1695                                 slot = path->slots[0];
1696                                 write_extent_buffer(leaf, buf,
1697                                             btrfs_item_ptr_offset(leaf, slot),
1698                                             size);
1699                                 inode_add_bytes(inode, datal);
1700                         }
1701
1702                         btrfs_mark_buffer_dirty(leaf);
1703                 }
1704
1705 next:
1706                 btrfs_release_path(root, path);
1707                 key.offset++;
1708         }
1709         ret = 0;
1710 out:
1711         btrfs_release_path(root, path);
1712         if (ret == 0) {
1713                 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1714                 if (destoff + olen > inode->i_size)
1715                         btrfs_i_size_write(inode, destoff + olen);
1716                 BTRFS_I(inode)->flags = BTRFS_I(src)->flags;
1717                 ret = btrfs_update_inode(trans, root, inode);
1718         }
1719         btrfs_end_transaction(trans, root);
1720         unlock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
1721         if (ret)
1722                 vmtruncate(inode, 0);
1723 out_unlock:
1724         mutex_unlock(&src->i_mutex);
1725         mutex_unlock(&inode->i_mutex);
1726         vfree(buf);
1727         btrfs_free_path(path);
1728 out_fput:
1729         fput(src_file);
1730 out_drop_write:
1731         mnt_drop_write(file->f_path.mnt);
1732         return ret;
1733 }
1734
1735 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
1736 {
1737         struct btrfs_ioctl_clone_range_args args;
1738
1739         if (copy_from_user(&args, argp, sizeof(args)))
1740                 return -EFAULT;
1741         return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
1742                                  args.src_length, args.dest_offset);
1743 }
1744
1745 /*
1746  * there are many ways the trans_start and trans_end ioctls can lead
1747  * to deadlocks.  They should only be used by applications that
1748  * basically own the machine, and have a very in depth understanding
1749  * of all the possible deadlocks and enospc problems.
1750  */
1751 static long btrfs_ioctl_trans_start(struct file *file)
1752 {
1753         struct inode *inode = fdentry(file)->d_inode;
1754         struct btrfs_root *root = BTRFS_I(inode)->root;
1755         struct btrfs_trans_handle *trans;
1756         int ret;
1757
1758         ret = -EPERM;
1759         if (!capable(CAP_SYS_ADMIN))
1760                 goto out;
1761
1762         ret = -EINPROGRESS;
1763         if (file->private_data)
1764                 goto out;
1765
1766         ret = mnt_want_write(file->f_path.mnt);
1767         if (ret)
1768                 goto out;
1769
1770         mutex_lock(&root->fs_info->trans_mutex);
1771         root->fs_info->open_ioctl_trans++;
1772         mutex_unlock(&root->fs_info->trans_mutex);
1773
1774         ret = -ENOMEM;
1775         trans = btrfs_start_ioctl_transaction(root, 0);
1776         if (!trans)
1777                 goto out_drop;
1778
1779         file->private_data = trans;
1780         return 0;
1781
1782 out_drop:
1783         mutex_lock(&root->fs_info->trans_mutex);
1784         root->fs_info->open_ioctl_trans--;
1785         mutex_unlock(&root->fs_info->trans_mutex);
1786         mnt_drop_write(file->f_path.mnt);
1787 out:
1788         return ret;
1789 }
1790
1791 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
1792 {
1793         struct inode *inode = fdentry(file)->d_inode;
1794         struct btrfs_root *root = BTRFS_I(inode)->root;
1795         struct btrfs_root *new_root;
1796         struct btrfs_dir_item *di;
1797         struct btrfs_trans_handle *trans;
1798         struct btrfs_path *path;
1799         struct btrfs_key location;
1800         struct btrfs_disk_key disk_key;
1801         struct btrfs_super_block *disk_super;
1802         u64 features;
1803         u64 objectid = 0;
1804         u64 dir_id;
1805
1806         if (!capable(CAP_SYS_ADMIN))
1807                 return -EPERM;
1808
1809         if (copy_from_user(&objectid, argp, sizeof(objectid)))
1810                 return -EFAULT;
1811
1812         if (!objectid)
1813                 objectid = root->root_key.objectid;
1814
1815         location.objectid = objectid;
1816         location.type = BTRFS_ROOT_ITEM_KEY;
1817         location.offset = (u64)-1;
1818
1819         new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
1820         if (IS_ERR(new_root))
1821                 return PTR_ERR(new_root);
1822
1823         if (btrfs_root_refs(&new_root->root_item) == 0)
1824                 return -ENOENT;
1825
1826         path = btrfs_alloc_path();
1827         if (!path)
1828                 return -ENOMEM;
1829         path->leave_spinning = 1;
1830
1831         trans = btrfs_start_transaction(root, 1);
1832         if (!trans) {
1833                 btrfs_free_path(path);
1834                 return -ENOMEM;
1835         }
1836
1837         dir_id = btrfs_super_root_dir(&root->fs_info->super_copy);
1838         di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
1839                                    dir_id, "default", 7, 1);
1840         if (!di) {
1841                 btrfs_free_path(path);
1842                 btrfs_end_transaction(trans, root);
1843                 printk(KERN_ERR "Umm, you don't have the default dir item, "
1844                        "this isn't going to work\n");
1845                 return -ENOENT;
1846         }
1847
1848         btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
1849         btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
1850         btrfs_mark_buffer_dirty(path->nodes[0]);
1851         btrfs_free_path(path);
1852
1853         disk_super = &root->fs_info->super_copy;
1854         features = btrfs_super_incompat_flags(disk_super);
1855         if (!(features & BTRFS_FEATURE_INCOMPAT_DEFAULT_SUBVOL)) {
1856                 features |= BTRFS_FEATURE_INCOMPAT_DEFAULT_SUBVOL;
1857                 btrfs_set_super_incompat_flags(disk_super, features);
1858         }
1859         btrfs_end_transaction(trans, root);
1860
1861         return 0;
1862 }
1863
1864 long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
1865 {
1866         struct btrfs_ioctl_space_args space_args;
1867         struct btrfs_ioctl_space_info space;
1868         struct btrfs_ioctl_space_info *dest;
1869         struct btrfs_ioctl_space_info *dest_orig;
1870         struct btrfs_ioctl_space_info *user_dest;
1871         struct btrfs_space_info *info;
1872         int alloc_size;
1873         int ret = 0;
1874         int slot_count = 0;
1875
1876         if (copy_from_user(&space_args,
1877                            (struct btrfs_ioctl_space_args __user *)arg,
1878                            sizeof(space_args)))
1879                 return -EFAULT;
1880
1881         /* first we count slots */
1882         rcu_read_lock();
1883         list_for_each_entry_rcu(info, &root->fs_info->space_info, list)
1884                 slot_count++;
1885         rcu_read_unlock();
1886
1887         /* space_slots == 0 means they are asking for a count */
1888         if (space_args.space_slots == 0) {
1889                 space_args.total_spaces = slot_count;
1890                 goto out;
1891         }
1892         alloc_size = sizeof(*dest) * slot_count;
1893         /* we generally have at most 6 or so space infos, one for each raid
1894          * level.  So, a whole page should be more than enough for everyone
1895          */
1896         if (alloc_size > PAGE_CACHE_SIZE)
1897                 return -ENOMEM;
1898
1899         space_args.total_spaces = 0;
1900         dest = kmalloc(alloc_size, GFP_NOFS);
1901         if (!dest)
1902                 return -ENOMEM;
1903         dest_orig = dest;
1904
1905         /* now we have a buffer to copy into */
1906         rcu_read_lock();
1907         list_for_each_entry_rcu(info, &root->fs_info->space_info, list) {
1908                 /* make sure we don't copy more than we allocated
1909                  * in our buffer
1910                  */
1911                 if (slot_count == 0)
1912                         break;
1913                 slot_count--;
1914
1915                 /* make sure userland has enough room in their buffer */
1916                 if (space_args.total_spaces >= space_args.space_slots)
1917                         break;
1918
1919                 space.flags = info->flags;
1920                 space.total_bytes = info->total_bytes;
1921                 space.used_bytes = info->bytes_used;
1922                 memcpy(dest, &space, sizeof(space));
1923                 dest++;
1924                 space_args.total_spaces++;
1925         }
1926         rcu_read_unlock();
1927
1928         user_dest = (struct btrfs_ioctl_space_info *)
1929                 (arg + sizeof(struct btrfs_ioctl_space_args));
1930
1931         if (copy_to_user(user_dest, dest_orig, alloc_size))
1932                 ret = -EFAULT;
1933
1934         kfree(dest_orig);
1935 out:
1936         if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
1937                 ret = -EFAULT;
1938
1939         return ret;
1940 }
1941
1942 /*
1943  * there are many ways the trans_start and trans_end ioctls can lead
1944  * to deadlocks.  They should only be used by applications that
1945  * basically own the machine, and have a very in depth understanding
1946  * of all the possible deadlocks and enospc problems.
1947  */
1948 long btrfs_ioctl_trans_end(struct file *file)
1949 {
1950         struct inode *inode = fdentry(file)->d_inode;
1951         struct btrfs_root *root = BTRFS_I(inode)->root;
1952         struct btrfs_trans_handle *trans;
1953
1954         trans = file->private_data;
1955         if (!trans)
1956                 return -EINVAL;
1957         file->private_data = NULL;
1958
1959         btrfs_end_transaction(trans, root);
1960
1961         mutex_lock(&root->fs_info->trans_mutex);
1962         root->fs_info->open_ioctl_trans--;
1963         mutex_unlock(&root->fs_info->trans_mutex);
1964
1965         mnt_drop_write(file->f_path.mnt);
1966         return 0;
1967 }
1968
1969 long btrfs_ioctl(struct file *file, unsigned int
1970                 cmd, unsigned long arg)
1971 {
1972         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
1973         void __user *argp = (void __user *)arg;
1974
1975         switch (cmd) {
1976         case FS_IOC_GETFLAGS:
1977                 return btrfs_ioctl_getflags(file, argp);
1978         case FS_IOC_SETFLAGS:
1979                 return btrfs_ioctl_setflags(file, argp);
1980         case FS_IOC_GETVERSION:
1981                 return btrfs_ioctl_getversion(file, argp);
1982         case BTRFS_IOC_SNAP_CREATE:
1983                 return btrfs_ioctl_snap_create(file, argp, 0);
1984         case BTRFS_IOC_SUBVOL_CREATE:
1985                 return btrfs_ioctl_snap_create(file, argp, 1);
1986         case BTRFS_IOC_SNAP_DESTROY:
1987                 return btrfs_ioctl_snap_destroy(file, argp);
1988         case BTRFS_IOC_DEFAULT_SUBVOL:
1989                 return btrfs_ioctl_default_subvol(file, argp);
1990         case BTRFS_IOC_DEFRAG:
1991                 return btrfs_ioctl_defrag(file, NULL);
1992         case BTRFS_IOC_DEFRAG_RANGE:
1993                 return btrfs_ioctl_defrag(file, argp);
1994         case BTRFS_IOC_RESIZE:
1995                 return btrfs_ioctl_resize(root, argp);
1996         case BTRFS_IOC_ADD_DEV:
1997                 return btrfs_ioctl_add_dev(root, argp);
1998         case BTRFS_IOC_RM_DEV:
1999                 return btrfs_ioctl_rm_dev(root, argp);
2000         case BTRFS_IOC_BALANCE:
2001                 return btrfs_balance(root->fs_info->dev_root);
2002         case BTRFS_IOC_CLONE:
2003                 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
2004         case BTRFS_IOC_CLONE_RANGE:
2005                 return btrfs_ioctl_clone_range(file, argp);
2006         case BTRFS_IOC_TRANS_START:
2007                 return btrfs_ioctl_trans_start(file);
2008         case BTRFS_IOC_TRANS_END:
2009                 return btrfs_ioctl_trans_end(file);
2010         case BTRFS_IOC_TREE_SEARCH:
2011                 return btrfs_ioctl_tree_search(file, argp);
2012         case BTRFS_IOC_INO_LOOKUP:
2013                 return btrfs_ioctl_ino_lookup(file, argp);
2014         case BTRFS_IOC_SPACE_INFO:
2015                 return btrfs_ioctl_space_info(root, argp);
2016         case BTRFS_IOC_SYNC:
2017                 btrfs_sync_fs(file->f_dentry->d_sb, 1);
2018                 return 0;
2019         }
2020
2021         return -ENOTTY;
2022 }