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