ec45b30861369083c7b52b20973e611b41be09d4
[safe/jmp/linux-2.6] / fs / btrfs / ioctl.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/fsnotify.h>
25 #include <linux/pagemap.h>
26 #include <linux/highmem.h>
27 #include <linux/time.h>
28 #include <linux/init.h>
29 #include <linux/string.h>
30 #include <linux/smp_lock.h>
31 #include <linux/backing-dev.h>
32 #include <linux/mount.h>
33 #include <linux/mpage.h>
34 #include <linux/namei.h>
35 #include <linux/swap.h>
36 #include <linux/writeback.h>
37 #include <linux/statfs.h>
38 #include <linux/compat.h>
39 #include <linux/bit_spinlock.h>
40 #include <linux/security.h>
41 #include <linux/version.h>
42 #include <linux/xattr.h>
43 #include <linux/vmalloc.h>
44 #include "ctree.h"
45 #include "disk-io.h"
46 #include "transaction.h"
47 #include "btrfs_inode.h"
48 #include "ioctl.h"
49 #include "print-tree.h"
50 #include "volumes.h"
51 #include "locking.h"
52
53
54
55 static noinline int create_subvol(struct btrfs_root *root,
56                                   struct dentry *dentry,
57                                   char *name, int namelen)
58 {
59         struct btrfs_trans_handle *trans;
60         struct btrfs_key key;
61         struct btrfs_root_item root_item;
62         struct btrfs_inode_item *inode_item;
63         struct extent_buffer *leaf;
64         struct btrfs_root *new_root = root;
65         struct inode *dir;
66         int ret;
67         int err;
68         u64 objectid;
69         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
70         u64 index = 0;
71         unsigned long nr = 1;
72
73         ret = btrfs_check_free_space(root, 1, 0);
74         if (ret)
75                 goto fail_commit;
76
77         trans = btrfs_start_transaction(root, 1);
78         BUG_ON(!trans);
79
80         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
81                                        0, &objectid);
82         if (ret)
83                 goto fail;
84
85         leaf = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
86                                       objectid, trans->transid, 0, 0, 0);
87         if (IS_ERR(leaf)) {
88                 ret = PTR_ERR(leaf);
89                 goto fail;
90         }
91
92         btrfs_set_header_nritems(leaf, 0);
93         btrfs_set_header_level(leaf, 0);
94         btrfs_set_header_bytenr(leaf, leaf->start);
95         btrfs_set_header_generation(leaf, trans->transid);
96         btrfs_set_header_owner(leaf, objectid);
97
98         write_extent_buffer(leaf, root->fs_info->fsid,
99                             (unsigned long)btrfs_header_fsid(leaf),
100                             BTRFS_FSID_SIZE);
101         btrfs_mark_buffer_dirty(leaf);
102
103         inode_item = &root_item.inode;
104         memset(inode_item, 0, sizeof(*inode_item));
105         inode_item->generation = cpu_to_le64(1);
106         inode_item->size = cpu_to_le64(3);
107         inode_item->nlink = cpu_to_le32(1);
108         inode_item->nbytes = cpu_to_le64(root->leafsize);
109         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
110
111         btrfs_set_root_bytenr(&root_item, leaf->start);
112         btrfs_set_root_generation(&root_item, trans->transid);
113         btrfs_set_root_level(&root_item, 0);
114         btrfs_set_root_refs(&root_item, 1);
115         btrfs_set_root_used(&root_item, 0);
116         btrfs_set_root_last_snapshot(&root_item, 0);
117
118         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
119         root_item.drop_level = 0;
120
121         btrfs_tree_unlock(leaf);
122         free_extent_buffer(leaf);
123         leaf = NULL;
124
125         btrfs_set_root_dirid(&root_item, new_dirid);
126
127         key.objectid = objectid;
128         key.offset = 1;
129         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
130 printk("inserting root objectid %Lu\n", objectid);
131         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
132                                 &root_item);
133         if (ret)
134                 goto fail;
135
136         /*
137          * insert the directory item
138          */
139         key.offset = (u64)-1;
140         dir = dentry->d_parent->d_inode;
141         ret = btrfs_set_inode_index(dir, &index);
142         BUG_ON(ret);
143
144         ret = btrfs_insert_dir_item(trans, root,
145                                     name, namelen, dir->i_ino, &key,
146                                     BTRFS_FT_DIR, index);
147         if (ret)
148                 goto fail;
149 #if 0
150         ret = btrfs_insert_inode_ref(trans, root->fs_info->tree_root,
151                              name, namelen, objectid,
152                              root->fs_info->sb->s_root->d_inode->i_ino, 0);
153         if (ret)
154                 goto fail;
155 #endif
156         ret = btrfs_commit_transaction(trans, root);
157         if (ret)
158                 goto fail_commit;
159
160         new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
161         BUG_ON(!new_root);
162
163         trans = btrfs_start_transaction(new_root, 1);
164         BUG_ON(!trans);
165
166         ret = btrfs_create_subvol_root(new_root, dentry, trans, new_dirid,
167                                        BTRFS_I(dir)->block_group);
168         if (ret)
169                 goto fail;
170
171 fail:
172         nr = trans->blocks_used;
173         err = btrfs_commit_transaction(trans, new_root);
174         if (err && !ret)
175                 ret = err;
176 fail_commit:
177         btrfs_btree_balance_dirty(root, nr);
178 printk("all done ret %d\n", ret);
179         return ret;
180 }
181
182 static int create_snapshot(struct btrfs_root *root, struct dentry *dentry,
183                            char *name, int namelen)
184 {
185         struct btrfs_pending_snapshot *pending_snapshot;
186         struct btrfs_trans_handle *trans;
187         int ret = 0;
188         int err;
189         unsigned long nr = 0;
190
191         if (!root->ref_cows)
192                 return -EINVAL;
193
194         ret = btrfs_check_free_space(root, 1, 0);
195         if (ret)
196                 goto fail_unlock;
197
198         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
199         if (!pending_snapshot) {
200                 ret = -ENOMEM;
201                 goto fail_unlock;
202         }
203         pending_snapshot->name = kmalloc(namelen + 1, GFP_NOFS);
204         if (!pending_snapshot->name) {
205                 ret = -ENOMEM;
206                 kfree(pending_snapshot);
207                 goto fail_unlock;
208         }
209         memcpy(pending_snapshot->name, name, namelen);
210         pending_snapshot->name[namelen] = '\0';
211         pending_snapshot->dentry = dentry;
212         trans = btrfs_start_transaction(root, 1);
213         BUG_ON(!trans);
214         pending_snapshot->root = root;
215         list_add(&pending_snapshot->list,
216                  &trans->transaction->pending_snapshots);
217         err = btrfs_commit_transaction(trans, root);
218
219 fail_unlock:
220         btrfs_btree_balance_dirty(root, nr);
221         return ret;
222 }
223
224 /* copy of may_create in fs/namei.c() */
225 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
226 {
227         if (child->d_inode)
228                 return -EEXIST;
229         if (IS_DEADDIR(dir))
230                 return -ENOENT;
231         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
232 }
233
234 /*
235  * Create a new subvolume below @parent.  This is largely modeled after
236  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
237  * inside this filesystem so it's quite a bit simpler.
238  */
239 static noinline int btrfs_mksubvol(struct path *parent, char *name,
240                                    int mode, int namelen,
241                                    struct btrfs_root *snap_src)
242 {
243         struct dentry *dentry;
244         int error;
245
246         mutex_lock_nested(&parent->dentry->d_inode->i_mutex, I_MUTEX_PARENT);
247
248         dentry = lookup_one_len(name, parent->dentry, namelen);
249         error = PTR_ERR(dentry);
250         if (IS_ERR(dentry))
251                 goto out_unlock;
252
253         error = -EEXIST;
254         if (dentry->d_inode)
255                 goto out_dput;
256
257         if (!IS_POSIXACL(parent->dentry->d_inode))
258                 mode &= ~current->fs->umask;
259
260         error = mnt_want_write(parent->mnt);
261         if (error)
262                 goto out_dput;
263
264         error = btrfs_may_create(parent->dentry->d_inode, dentry);
265         if (error)
266                 goto out_drop_write;
267
268         /*
269          * Actually perform the low-level subvolume creation after all
270          * this VFS fuzz.
271          *
272          * Eventually we want to pass in an inode under which we create this
273          * subvolume, but for now all are under the filesystem root.
274          *
275          * Also we should pass on the mode eventually to allow creating new
276          * subvolume with specific mode bits.
277          */
278         if (snap_src) {
279                 error = create_snapshot(snap_src, dentry, name, namelen);
280         } else {
281                 error = create_subvol(BTRFS_I(parent->dentry->d_inode)->root,
282                                       dentry, name, namelen);
283         }
284         if (error)
285                 goto out_drop_write;
286
287         fsnotify_mkdir(parent->dentry->d_inode, dentry);
288 out_drop_write:
289         mnt_drop_write(parent->mnt);
290 out_dput:
291         dput(dentry);
292 out_unlock:
293         mutex_unlock(&parent->dentry->d_inode->i_mutex);
294         return error;
295 }
296
297
298 int btrfs_defrag_file(struct file *file)
299 {
300         struct inode *inode = fdentry(file)->d_inode;
301         struct btrfs_root *root = BTRFS_I(inode)->root;
302         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
303         struct btrfs_ordered_extent *ordered;
304         struct page *page;
305         unsigned long last_index;
306         unsigned long ra_pages = root->fs_info->bdi.ra_pages;
307         unsigned long total_read = 0;
308         u64 page_start;
309         u64 page_end;
310         unsigned long i;
311         int ret;
312
313         ret = btrfs_check_free_space(root, inode->i_size, 0);
314         if (ret)
315                 return -ENOSPC;
316
317         mutex_lock(&inode->i_mutex);
318         last_index = inode->i_size >> PAGE_CACHE_SHIFT;
319         for (i = 0; i <= last_index; i++) {
320                 if (total_read % ra_pages == 0) {
321                         btrfs_force_ra(inode->i_mapping, &file->f_ra, file, i,
322                                        min(last_index, i + ra_pages - 1));
323                 }
324                 total_read++;
325 again:
326                 page = grab_cache_page(inode->i_mapping, i);
327                 if (!page)
328                         goto out_unlock;
329                 if (!PageUptodate(page)) {
330                         btrfs_readpage(NULL, page);
331                         lock_page(page);
332                         if (!PageUptodate(page)) {
333                                 unlock_page(page);
334                                 page_cache_release(page);
335                                 goto out_unlock;
336                         }
337                 }
338
339                 wait_on_page_writeback(page);
340
341                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
342                 page_end = page_start + PAGE_CACHE_SIZE - 1;
343                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
344
345                 ordered = btrfs_lookup_ordered_extent(inode, page_start);
346                 if (ordered) {
347                         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
348                         unlock_page(page);
349                         page_cache_release(page);
350                         btrfs_start_ordered_extent(inode, ordered, 1);
351                         btrfs_put_ordered_extent(ordered);
352                         goto again;
353                 }
354                 set_page_extent_mapped(page);
355
356                 /*
357                  * this makes sure page_mkwrite is called on the
358                  * page if it is dirtied again later
359                  */
360                 clear_page_dirty_for_io(page);
361
362                 btrfs_set_extent_delalloc(inode, page_start, page_end);
363
364                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
365                 set_page_dirty(page);
366                 unlock_page(page);
367                 page_cache_release(page);
368                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, 1);
369         }
370
371 out_unlock:
372         mutex_unlock(&inode->i_mutex);
373         return 0;
374 }
375
376 /*
377  * Called inside transaction, so use GFP_NOFS
378  */
379
380 static int btrfs_ioctl_resize(struct btrfs_root *root, void __user *arg)
381 {
382         u64 new_size;
383         u64 old_size;
384         u64 devid = 1;
385         struct btrfs_ioctl_vol_args *vol_args;
386         struct btrfs_trans_handle *trans;
387         struct btrfs_device *device = NULL;
388         char *sizestr;
389         char *devstr = NULL;
390         int ret = 0;
391         int namelen;
392         int mod = 0;
393
394         if (root->fs_info->sb->s_flags & MS_RDONLY)
395                 return -EROFS;
396
397         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
398
399         if (!vol_args)
400                 return -ENOMEM;
401
402         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
403                 ret = -EFAULT;
404                 goto out;
405         }
406
407         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
408         namelen = strlen(vol_args->name);
409
410         mutex_lock(&root->fs_info->volume_mutex);
411         sizestr = vol_args->name;
412         devstr = strchr(sizestr, ':');
413         if (devstr) {
414                 char *end;
415                 sizestr = devstr + 1;
416                 *devstr = '\0';
417                 devstr = vol_args->name;
418                 devid = simple_strtoull(devstr, &end, 10);
419                 printk(KERN_INFO "resizing devid %llu\n", devid);
420         }
421         device = btrfs_find_device(root, devid, NULL, NULL);
422         if (!device) {
423                 printk(KERN_INFO "resizer unable to find device %llu\n", devid);
424                 ret = -EINVAL;
425                 goto out_unlock;
426         }
427         if (!strcmp(sizestr, "max"))
428                 new_size = device->bdev->bd_inode->i_size;
429         else {
430                 if (sizestr[0] == '-') {
431                         mod = -1;
432                         sizestr++;
433                 } else if (sizestr[0] == '+') {
434                         mod = 1;
435                         sizestr++;
436                 }
437                 new_size = btrfs_parse_size(sizestr);
438                 if (new_size == 0) {
439                         ret = -EINVAL;
440                         goto out_unlock;
441                 }
442         }
443
444         old_size = device->total_bytes;
445
446         if (mod < 0) {
447                 if (new_size > old_size) {
448                         ret = -EINVAL;
449                         goto out_unlock;
450                 }
451                 new_size = old_size - new_size;
452         } else if (mod > 0) {
453                 new_size = old_size + new_size;
454         }
455
456         if (new_size < 256 * 1024 * 1024) {
457                 ret = -EINVAL;
458                 goto out_unlock;
459         }
460         if (new_size > device->bdev->bd_inode->i_size) {
461                 ret = -EFBIG;
462                 goto out_unlock;
463         }
464
465         do_div(new_size, root->sectorsize);
466         new_size *= root->sectorsize;
467
468         printk(KERN_INFO "new size for %s is %llu\n",
469                 device->name, (unsigned long long)new_size);
470
471         if (new_size > old_size) {
472                 trans = btrfs_start_transaction(root, 1);
473                 ret = btrfs_grow_device(trans, device, new_size);
474                 btrfs_commit_transaction(trans, root);
475         } else {
476                 ret = btrfs_shrink_device(device, new_size);
477         }
478
479 out_unlock:
480         mutex_unlock(&root->fs_info->volume_mutex);
481 out:
482         kfree(vol_args);
483         return ret;
484 }
485
486 static noinline int btrfs_ioctl_snap_create(struct file *file,
487                                             void __user *arg, int subvol)
488 {
489         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
490         struct btrfs_ioctl_vol_args *vol_args;
491         struct btrfs_dir_item *di;
492         struct btrfs_path *path;
493         struct file *src_file;
494         u64 root_dirid;
495         int namelen;
496         int ret = 0;
497
498         if (root->fs_info->sb->s_flags & MS_RDONLY)
499                 return -EROFS;
500
501         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
502
503         if (!vol_args)
504                 return -ENOMEM;
505
506         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
507                 ret = -EFAULT;
508                 goto out;
509         }
510
511         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
512         namelen = strlen(vol_args->name);
513         if (strchr(vol_args->name, '/')) {
514                 ret = -EINVAL;
515                 goto out;
516         }
517
518         path = btrfs_alloc_path();
519         if (!path) {
520                 ret = -ENOMEM;
521                 goto out;
522         }
523
524         root_dirid = root->fs_info->sb->s_root->d_inode->i_ino,
525         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root,
526                             path, root_dirid,
527                             vol_args->name, namelen, 0);
528         btrfs_free_path(path);
529
530         if (di && !IS_ERR(di)) {
531                 ret = -EEXIST;
532                 goto out;
533         }
534
535         if (IS_ERR(di)) {
536                 ret = PTR_ERR(di);
537                 goto out;
538         }
539
540         if (subvol) {
541                 ret = btrfs_mksubvol(&file->f_path, vol_args->name,
542                                      file->f_path.dentry->d_inode->i_mode,
543                                      namelen, NULL);
544         } else {
545                 struct inode *src_inode;
546                 src_file = fget(vol_args->fd);
547                 if (!src_file) {
548                         ret = -EINVAL;
549                         goto out;
550                 }
551
552                 src_inode = src_file->f_path.dentry->d_inode;
553                 if (src_inode->i_sb != file->f_path.dentry->d_inode->i_sb) {
554                         printk("btrfs: Snapshot src from another FS\n");
555                         ret = -EINVAL;
556                         fput(src_file);
557                         goto out;
558                 }
559                 ret = btrfs_mksubvol(&file->f_path, vol_args->name,
560                              file->f_path.dentry->d_inode->i_mode,
561                              namelen, BTRFS_I(src_inode)->root);
562                 fput(src_file);
563         }
564
565 out:
566         kfree(vol_args);
567         return ret;
568 }
569
570 static int btrfs_ioctl_defrag(struct file *file)
571 {
572         struct inode *inode = fdentry(file)->d_inode;
573         struct btrfs_root *root = BTRFS_I(inode)->root;
574         int ret;
575
576         ret = mnt_want_write(file->f_path.mnt);
577         if (ret)
578                 return ret;
579
580         switch (inode->i_mode & S_IFMT) {
581         case S_IFDIR:
582                 btrfs_defrag_root(root, 0);
583                 btrfs_defrag_root(root->fs_info->extent_root, 0);
584                 break;
585         case S_IFREG:
586                 btrfs_defrag_file(file);
587                 break;
588         }
589
590         return 0;
591 }
592
593 long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
594 {
595         struct btrfs_ioctl_vol_args *vol_args;
596         int ret;
597
598         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
599
600         if (!vol_args)
601                 return -ENOMEM;
602
603         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
604                 ret = -EFAULT;
605                 goto out;
606         }
607         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
608         ret = btrfs_init_new_device(root, vol_args->name);
609
610 out:
611         kfree(vol_args);
612         return ret;
613 }
614
615 long btrfs_ioctl_rm_dev(struct btrfs_root *root, void __user *arg)
616 {
617         struct btrfs_ioctl_vol_args *vol_args;
618         int ret;
619
620         if (root->fs_info->sb->s_flags & MS_RDONLY)
621                 return -EROFS;
622
623         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
624
625         if (!vol_args)
626                 return -ENOMEM;
627
628         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
629                 ret = -EFAULT;
630                 goto out;
631         }
632         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
633         ret = btrfs_rm_device(root, vol_args->name);
634
635 out:
636         kfree(vol_args);
637         return ret;
638 }
639
640 long btrfs_ioctl_clone(struct file *file, unsigned long srcfd, u64 off,
641                        u64 olen, u64 destoff)
642 {
643         struct inode *inode = fdentry(file)->d_inode;
644         struct btrfs_root *root = BTRFS_I(inode)->root;
645         struct file *src_file;
646         struct inode *src;
647         struct btrfs_trans_handle *trans;
648         struct btrfs_path *path;
649         struct extent_buffer *leaf;
650         char *buf;
651         struct btrfs_key key;
652         u32 nritems;
653         int slot;
654         int ret;
655         u64 len = olen;
656         u64 bs = root->fs_info->sb->s_blocksize;
657         u64 hint_byte;
658
659         /*
660          * TODO:
661          * - split compressed inline extents.  annoying: we need to
662          *   decompress into destination's address_space (the file offset
663          *   may change, so source mapping won't do), then recompress (or
664          *   otherwise reinsert) a subrange.
665          * - allow ranges within the same file to be cloned (provided
666          *   they don't overlap)?
667          */
668
669         ret = mnt_want_write(file->f_path.mnt);
670         if (ret)
671                 return ret;
672
673         src_file = fget(srcfd);
674         if (!src_file)
675                 return -EBADF;
676         src = src_file->f_dentry->d_inode;
677
678         ret = -EINVAL;
679         if (src == inode)
680                 goto out_fput;
681
682         ret = -EISDIR;
683         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
684                 goto out_fput;
685
686         ret = -EXDEV;
687         if (src->i_sb != inode->i_sb || BTRFS_I(src)->root != root)
688                 goto out_fput;
689
690         ret = -ENOMEM;
691         buf = vmalloc(btrfs_level_size(root, 0));
692         if (!buf)
693                 goto out_fput;
694
695         path = btrfs_alloc_path();
696         if (!path) {
697                 vfree(buf);
698                 goto out_fput;
699         }
700         path->reada = 2;
701
702         if (inode < src) {
703                 mutex_lock(&inode->i_mutex);
704                 mutex_lock(&src->i_mutex);
705         } else {
706                 mutex_lock(&src->i_mutex);
707                 mutex_lock(&inode->i_mutex);
708         }
709
710         /* determine range to clone */
711         ret = -EINVAL;
712         if (off >= src->i_size || off + len > src->i_size)
713                 goto out_unlock;
714         if (len == 0)
715                 olen = len = src->i_size - off;
716         /* if we extend to eof, continue to block boundary */
717         if (off + len == src->i_size)
718                 len = ((src->i_size + bs-1) & ~(bs-1))
719                         - off;
720
721         /* verify the end result is block aligned */
722         if ((off & (bs-1)) ||
723             ((off + len) & (bs-1)))
724                 goto out_unlock;
725
726         printk("final src extent is %llu~%llu\n", off, len);
727         printk("final dst extent is %llu~%llu\n", destoff, len);
728
729         /* do any pending delalloc/csum calc on src, one way or
730            another, and lock file content */
731         while (1) {
732                 struct btrfs_ordered_extent *ordered;
733                 lock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
734                 ordered = btrfs_lookup_first_ordered_extent(inode, off+len);
735                 if (BTRFS_I(src)->delalloc_bytes == 0 && !ordered)
736                         break;
737                 unlock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
738                 if (ordered)
739                         btrfs_put_ordered_extent(ordered);
740                 btrfs_wait_ordered_range(src, off, off+len);
741         }
742
743         trans = btrfs_start_transaction(root, 1);
744         BUG_ON(!trans);
745
746         /* punch hole in destination first */
747         btrfs_drop_extents(trans, root, inode, off, off+len, 0, &hint_byte);
748
749         /* clone data */
750         key.objectid = src->i_ino;
751         key.type = BTRFS_EXTENT_DATA_KEY;
752         key.offset = 0;
753
754         while (1) {
755                 /*
756                  * note the key will change type as we walk through the
757                  * tree.
758                  */
759                 ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
760                 if (ret < 0)
761                         goto out;
762
763                 nritems = btrfs_header_nritems(path->nodes[0]);
764                 if (path->slots[0] >= nritems) {
765                         ret = btrfs_next_leaf(root, path);
766                         if (ret < 0)
767                                 goto out;
768                         if (ret > 0)
769                                 break;
770                         nritems = btrfs_header_nritems(path->nodes[0]);
771                 }
772                 leaf = path->nodes[0];
773                 slot = path->slots[0];
774
775                 btrfs_item_key_to_cpu(leaf, &key, slot);
776                 if (btrfs_key_type(&key) > BTRFS_CSUM_ITEM_KEY ||
777                     key.objectid != src->i_ino)
778                         break;
779
780                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
781                         struct btrfs_file_extent_item *extent;
782                         int type;
783                         u32 size;
784                         struct btrfs_key new_key;
785                         u64 disko = 0, diskl = 0;
786                         u64 datao = 0, datal = 0;
787                         u8 comp;
788
789                         size = btrfs_item_size_nr(leaf, slot);
790                         read_extent_buffer(leaf, buf,
791                                            btrfs_item_ptr_offset(leaf, slot),
792                                            size);
793
794                         extent = btrfs_item_ptr(leaf, slot,
795                                                 struct btrfs_file_extent_item);
796                         comp = btrfs_file_extent_compression(leaf, extent);
797                         type = btrfs_file_extent_type(leaf, extent);
798                         if (type == BTRFS_FILE_EXTENT_REG) {
799                                 disko = btrfs_file_extent_disk_bytenr(leaf, extent);
800                                 diskl = btrfs_file_extent_disk_num_bytes(leaf, extent);
801                                 datao = btrfs_file_extent_offset(leaf, extent);
802                                 datal = btrfs_file_extent_num_bytes(leaf, extent);
803                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
804                                 /* take upper bound, may be compressed */
805                                 datal = btrfs_file_extent_ram_bytes(leaf,
806                                                                     extent);
807                         }
808                         btrfs_release_path(root, path);
809
810                         if (key.offset + datal < off ||
811                             key.offset >= off+len)
812                                 goto next;
813
814                         memcpy(&new_key, &key, sizeof(new_key));
815                         new_key.objectid = inode->i_ino;
816                         new_key.offset = key.offset + destoff - off;
817
818                         if (type == BTRFS_FILE_EXTENT_REG) {
819                                 ret = btrfs_insert_empty_item(trans, root, path,
820                                                               &new_key, size);
821                                 if (ret)
822                                         goto out;
823
824                                 leaf = path->nodes[0];
825                                 slot = path->slots[0];
826                                 write_extent_buffer(leaf, buf,
827                                             btrfs_item_ptr_offset(leaf, slot),
828                                             size);
829
830                                 extent = btrfs_item_ptr(leaf, slot,
831                                                 struct btrfs_file_extent_item);
832                                 printk("  orig disk %llu~%llu data %llu~%llu\n",
833                                        disko, diskl, datao, datal);
834
835                                 if (off > key.offset) {
836                                         datao += off - key.offset;
837                                         datal -= off - key.offset;
838                                 }
839                                 if (key.offset + datao + datal + key.offset >
840                                     off + len)
841                                         datal = off + len - key.offset - datao;
842                                 /* disko == 0 means it's a hole */
843                                 if (!disko)
844                                         datao = 0;
845                                 printk(" final disk %llu~%llu data %llu~%llu\n",
846                                        disko, diskl, datao, datal);
847
848                                 btrfs_set_file_extent_offset(leaf, extent,
849                                                              datao);
850                                 btrfs_set_file_extent_num_bytes(leaf, extent,
851                                                                 datal);
852                                 if (disko) {
853                                         inode_add_bytes(inode, datal);
854                                         ret = btrfs_inc_extent_ref(trans, root,
855                                                    disko, diskl, leaf->start,
856                                                    root->root_key.objectid,
857                                                    trans->transid,
858                                                    inode->i_ino);
859                                         BUG_ON(ret);
860                                 }
861                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
862                                 u64 skip = 0;
863                                 u64 trim = 0;
864                                 if (off > key.offset) {
865                                         skip = off - key.offset;
866                                         new_key.offset += skip;
867                                 }
868                                 if (key.offset + datal > off+len)
869                                         trim = key.offset + datal - (off+len);
870                                 printk("len %lld skip %lld trim %lld\n",
871                                        datal, skip, trim);
872                                 if (comp && (skip || trim)) {
873                                         printk("btrfs clone_range can't split compressed inline extents yet\n");
874                                         ret = -EINVAL;
875                                         goto out;
876                                 }
877                                 size -= skip + trim;
878                                 datal -= skip + trim;
879                                 ret = btrfs_insert_empty_item(trans, root, path,
880                                                               &new_key, size);
881                                 if (ret)
882                                         goto out;
883
884                                 if (skip) {
885                                         u32 start = btrfs_file_extent_calc_inline_size(0);
886                                         memmove(buf+start, buf+start+skip,
887                                                 datal);
888                                 }
889
890                                 leaf = path->nodes[0];
891                                 slot = path->slots[0];
892                                 write_extent_buffer(leaf, buf,
893                                             btrfs_item_ptr_offset(leaf, slot),
894                                             size);
895                                 inode_add_bytes(inode, datal);
896                         }
897
898                         btrfs_mark_buffer_dirty(leaf);
899                 }
900
901                 if (btrfs_key_type(&key) == BTRFS_CSUM_ITEM_KEY) {
902                         u32 size;
903                         struct btrfs_key new_key;
904                         u64 coverslen;
905                         int coff, clen;
906
907                         size = btrfs_item_size_nr(leaf, slot);
908                         coverslen = (size / BTRFS_CRC32_SIZE) <<
909                                 root->fs_info->sb->s_blocksize_bits;
910                         printk("csums for %llu~%llu\n",
911                                key.offset, coverslen);
912                         if (key.offset + coverslen < off ||
913                             key.offset >= off+len)
914                                 goto next;
915
916                         read_extent_buffer(leaf, buf,
917                                            btrfs_item_ptr_offset(leaf, slot),
918                                            size);
919                         btrfs_release_path(root, path);
920
921                         coff = 0;
922                         if (off > key.offset)
923                                 coff = ((off - key.offset) >>
924                                         root->fs_info->sb->s_blocksize_bits) *
925                                         BTRFS_CRC32_SIZE;
926                         clen = size - coff;
927                         if (key.offset + coverslen > off+len)
928                                 clen -= ((key.offset+coverslen-off-len) >>
929                                          root->fs_info->sb->s_blocksize_bits) *
930                                         BTRFS_CRC32_SIZE;
931                         printk(" will dup %d~%d of %d\n",
932                                coff, clen, size);
933
934                         memcpy(&new_key, &key, sizeof(new_key));
935                         new_key.objectid = inode->i_ino;
936                         new_key.offset = key.offset + destoff - off;
937
938                         ret = btrfs_insert_empty_item(trans, root, path,
939                                                       &new_key, clen);
940                         if (ret)
941                                 goto out;
942
943                         leaf = path->nodes[0];
944                         slot = path->slots[0];
945                         write_extent_buffer(leaf, buf + coff,
946                                             btrfs_item_ptr_offset(leaf, slot),
947                                             clen);
948                         btrfs_mark_buffer_dirty(leaf);
949                 }
950
951         next:
952                 btrfs_release_path(root, path);
953                 key.offset++;
954         }
955         ret = 0;
956 out:
957         btrfs_release_path(root, path);
958         if (ret == 0) {
959                 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
960                 if (destoff + olen > inode->i_size)
961                         btrfs_i_size_write(inode, destoff + olen);
962                 BTRFS_I(inode)->flags = BTRFS_I(src)->flags;
963                 ret = btrfs_update_inode(trans, root, inode);
964         }
965         btrfs_end_transaction(trans, root);
966         unlock_extent(&BTRFS_I(src)->io_tree, off, off+len, GFP_NOFS);
967         if (ret)
968                 vmtruncate(inode, 0);
969 out_unlock:
970         mutex_unlock(&src->i_mutex);
971         mutex_unlock(&inode->i_mutex);
972         vfree(buf);
973         btrfs_free_path(path);
974 out_fput:
975         fput(src_file);
976         return ret;
977 }
978
979 long btrfs_ioctl_clone_range(struct file *file, unsigned long argptr)
980 {
981         struct btrfs_ioctl_clone_range_args args;
982
983         if (copy_from_user(&args, (void *)argptr, sizeof(args)))
984                 return -EFAULT;
985         return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
986                                  args.src_length, args.dest_offset);
987 }
988
989 /*
990  * there are many ways the trans_start and trans_end ioctls can lead
991  * to deadlocks.  They should only be used by applications that
992  * basically own the machine, and have a very in depth understanding
993  * of all the possible deadlocks and enospc problems.
994  */
995 long btrfs_ioctl_trans_start(struct file *file)
996 {
997         struct inode *inode = fdentry(file)->d_inode;
998         struct btrfs_root *root = BTRFS_I(inode)->root;
999         struct btrfs_trans_handle *trans;
1000         int ret = 0;
1001
1002         if (!capable(CAP_SYS_ADMIN))
1003                 return -EPERM;
1004
1005         if (file->private_data) {
1006                 ret = -EINPROGRESS;
1007                 goto out;
1008         }
1009
1010         ret = mnt_want_write(file->f_path.mnt);
1011         if (ret)
1012                 goto out;
1013
1014         mutex_lock(&root->fs_info->trans_mutex);
1015         root->fs_info->open_ioctl_trans++;
1016         mutex_unlock(&root->fs_info->trans_mutex);
1017
1018         trans = btrfs_start_ioctl_transaction(root, 0);
1019         if (trans)
1020                 file->private_data = trans;
1021         else
1022                 ret = -ENOMEM;
1023         /*printk(KERN_INFO "btrfs_ioctl_trans_start on %p\n", file);*/
1024 out:
1025         return ret;
1026 }
1027
1028 /*
1029  * there are many ways the trans_start and trans_end ioctls can lead
1030  * to deadlocks.  They should only be used by applications that
1031  * basically own the machine, and have a very in depth understanding
1032  * of all the possible deadlocks and enospc problems.
1033  */
1034 long btrfs_ioctl_trans_end(struct file *file)
1035 {
1036         struct inode *inode = fdentry(file)->d_inode;
1037         struct btrfs_root *root = BTRFS_I(inode)->root;
1038         struct btrfs_trans_handle *trans;
1039         int ret = 0;
1040
1041         trans = file->private_data;
1042         if (!trans) {
1043                 ret = -EINVAL;
1044                 goto out;
1045         }
1046         btrfs_end_transaction(trans, root);
1047         file->private_data = NULL;
1048
1049         mutex_lock(&root->fs_info->trans_mutex);
1050         root->fs_info->open_ioctl_trans--;
1051         mutex_unlock(&root->fs_info->trans_mutex);
1052
1053 out:
1054         return ret;
1055 }
1056
1057 long btrfs_ioctl(struct file *file, unsigned int
1058                 cmd, unsigned long arg)
1059 {
1060         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
1061
1062         switch (cmd) {
1063         case BTRFS_IOC_SNAP_CREATE:
1064                 return btrfs_ioctl_snap_create(file, (void __user *)arg, 0);
1065         case BTRFS_IOC_SUBVOL_CREATE:
1066                 return btrfs_ioctl_snap_create(file, (void __user *)arg, 1);
1067         case BTRFS_IOC_DEFRAG:
1068                 return btrfs_ioctl_defrag(file);
1069         case BTRFS_IOC_RESIZE:
1070                 return btrfs_ioctl_resize(root, (void __user *)arg);
1071         case BTRFS_IOC_ADD_DEV:
1072                 return btrfs_ioctl_add_dev(root, (void __user *)arg);
1073         case BTRFS_IOC_RM_DEV:
1074                 return btrfs_ioctl_rm_dev(root, (void __user *)arg);
1075         case BTRFS_IOC_BALANCE:
1076                 return btrfs_balance(root->fs_info->dev_root);
1077         case BTRFS_IOC_CLONE:
1078                 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
1079         case BTRFS_IOC_CLONE_RANGE:
1080                 return btrfs_ioctl_clone_range(file, arg);
1081         case BTRFS_IOC_TRANS_START:
1082                 return btrfs_ioctl_trans_start(file);
1083         case BTRFS_IOC_TRANS_END:
1084                 return btrfs_ioctl_trans_end(file);
1085         case BTRFS_IOC_SYNC:
1086                 btrfs_start_delalloc_inodes(root);
1087                 btrfs_sync_fs(file->f_dentry->d_sb, 1);
1088                 return 0;
1089         }
1090
1091         return -ENOTTY;
1092 }