]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/btrfs/inode.c
Btrfs: Fix double free and off by one in inode.c
[karo-tx-linux.git] / fs / btrfs / inode.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/buffer_head.h>
20 #include <linux/fs.h>
21 #include <linux/pagemap.h>
22 #include <linux/highmem.h>
23 #include <linux/time.h>
24 #include <linux/init.h>
25 #include <linux/string.h>
26 #include <linux/smp_lock.h>
27 #include <linux/backing-dev.h>
28 #include <linux/mpage.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
31 #include <linux/statfs.h>
32 #include <linux/compat.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/version.h>
35 #include "ctree.h"
36 #include "disk-io.h"
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "ioctl.h"
40 #include "print-tree.h"
41
42 struct btrfs_iget_args {
43         u64 ino;
44         struct btrfs_root *root;
45 };
46
47 static struct inode_operations btrfs_dir_inode_operations;
48 static struct inode_operations btrfs_symlink_inode_operations;
49 static struct inode_operations btrfs_dir_ro_inode_operations;
50 static struct inode_operations btrfs_special_inode_operations;
51 static struct inode_operations btrfs_file_inode_operations;
52 static struct address_space_operations btrfs_aops;
53 static struct address_space_operations btrfs_symlink_aops;
54 static struct file_operations btrfs_dir_file_operations;
55 static struct extent_map_ops btrfs_extent_map_ops;
56
57 static struct kmem_cache *btrfs_inode_cachep;
58 struct kmem_cache *btrfs_trans_handle_cachep;
59 struct kmem_cache *btrfs_transaction_cachep;
60 struct kmem_cache *btrfs_bit_radix_cachep;
61 struct kmem_cache *btrfs_path_cachep;
62
63 #define S_SHIFT 12
64 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
65         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
66         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
67         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
68         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
69         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
70         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
71         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
72 };
73
74 static int run_delalloc_range(struct inode *inode, u64 start, u64 end)
75 {
76         struct btrfs_root *root = BTRFS_I(inode)->root;
77         struct btrfs_trans_handle *trans;
78         struct btrfs_key ins;
79         u64 alloc_hint = 0;
80         u64 num_blocks;
81         int ret;
82         u64 blocksize = 1 << inode->i_blkbits;
83
84         mutex_lock(&root->fs_info->fs_mutex);
85         trans = btrfs_start_transaction(root, 1);
86         btrfs_set_trans_block_group(trans, inode);
87         BUG_ON(!trans);
88         num_blocks = (end - start + blocksize) & ~(blocksize - 1);
89         ret = btrfs_drop_extents(trans, root, inode,
90                                  start, start + num_blocks, &alloc_hint);
91         num_blocks = num_blocks >> inode->i_blkbits;
92         ret = btrfs_alloc_extent(trans, root, inode->i_ino, num_blocks, 0,
93                                  alloc_hint, (u64)-1, &ins, 1);
94         if (ret) {
95                 WARN_ON(1);
96                 goto out;
97         }
98         ret = btrfs_insert_file_extent(trans, root, inode->i_ino,
99                                        start, ins.objectid, ins.offset,
100                                        ins.offset);
101 out:
102         btrfs_end_transaction(trans, root);
103         mutex_unlock(&root->fs_info->fs_mutex);
104         return ret;
105 }
106
107 int btrfs_writepage_io_hook(struct page *page, u64 start, u64 end)
108 {
109         struct inode *inode = page->mapping->host;
110         struct btrfs_root *root = BTRFS_I(inode)->root;
111         struct btrfs_trans_handle *trans;
112         char *kaddr;
113         int ret;
114         u64 page_start = page->index << PAGE_CACHE_SHIFT;
115         size_t offset = start - page_start;
116
117         mutex_lock(&root->fs_info->fs_mutex);
118         trans = btrfs_start_transaction(root, 1);
119         btrfs_set_trans_block_group(trans, inode);
120         kaddr = kmap(page);
121         btrfs_csum_file_block(trans, root, inode->i_ino,
122                               start, kaddr + offset, end - start + 1);
123         kunmap(page);
124         ret = btrfs_end_transaction(trans, root);
125         BUG_ON(ret);
126         mutex_unlock(&root->fs_info->fs_mutex);
127         return ret;
128 }
129
130 int btrfs_readpage_io_hook(struct page *page, u64 start, u64 end)
131 {
132         int ret = 0;
133         struct inode *inode = page->mapping->host;
134         struct btrfs_root *root = BTRFS_I(inode)->root;
135         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
136         struct btrfs_csum_item *item;
137         struct btrfs_path *path = NULL;
138         u64 private;
139
140         mutex_lock(&root->fs_info->fs_mutex);
141         path = btrfs_alloc_path();
142         item = btrfs_lookup_csum(NULL, root, path, inode->i_ino, start, 0);
143         if (IS_ERR(item)) {
144                 ret = PTR_ERR(item);
145                 /* a csum that isn't present is a preallocated region. */
146                 if (ret == -ENOENT || ret == -EFBIG)
147                         ret = 0;
148                 private = 0;
149                 goto out;
150         }
151         memcpy((char *)&private, &item->csum, BTRFS_CRC32_SIZE);
152         set_state_private(em_tree, start, private);
153 out:
154         if (path)
155                 btrfs_free_path(path);
156         mutex_unlock(&root->fs_info->fs_mutex);
157         return ret;
158 }
159
160 int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end)
161 {
162         char csum[BTRFS_CRC32_SIZE];
163         size_t offset = start - (page->index << PAGE_CACHE_SHIFT);
164         struct inode *inode = page->mapping->host;
165         struct btrfs_root *root = BTRFS_I(inode)->root;
166         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
167         char *kaddr;
168         u64 private;
169         int ret;
170
171         ret = get_state_private(em_tree, start, &private);
172         kaddr = kmap_atomic(page, KM_IRQ0);
173         if (ret) {
174                 goto zeroit;
175         }
176         ret = btrfs_csum_data(root, kaddr + offset, end - start + 1, csum);
177         BUG_ON(ret);
178         if (memcmp(csum, &private, BTRFS_CRC32_SIZE)) {
179                 goto zeroit;
180         }
181         kunmap_atomic(kaddr, KM_IRQ0);
182         return 0;
183
184 zeroit:
185         printk("btrfs csum failed ino %lu off %llu\n",
186                page->mapping->host->i_ino, (unsigned long long)start);
187         memset(kaddr + offset, 1, end - start + 1); flush_dcache_page(page);
188         kunmap_atomic(kaddr, KM_IRQ0);
189         return 0;
190 }
191
192 void btrfs_read_locked_inode(struct inode *inode)
193 {
194         struct btrfs_path *path;
195         struct btrfs_inode_item *inode_item;
196         struct btrfs_root *root = BTRFS_I(inode)->root;
197         struct btrfs_key location;
198         u64 alloc_group_block;
199         u32 rdev;
200         int ret;
201
202         path = btrfs_alloc_path();
203         BUG_ON(!path);
204         mutex_lock(&root->fs_info->fs_mutex);
205
206         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
207         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
208         if (ret) {
209                 goto make_bad;
210         }
211         inode_item = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
212                                   path->slots[0],
213                                   struct btrfs_inode_item);
214
215         inode->i_mode = btrfs_inode_mode(inode_item);
216         inode->i_nlink = btrfs_inode_nlink(inode_item);
217         inode->i_uid = btrfs_inode_uid(inode_item);
218         inode->i_gid = btrfs_inode_gid(inode_item);
219         inode->i_size = btrfs_inode_size(inode_item);
220         inode->i_atime.tv_sec = btrfs_timespec_sec(&inode_item->atime);
221         inode->i_atime.tv_nsec = btrfs_timespec_nsec(&inode_item->atime);
222         inode->i_mtime.tv_sec = btrfs_timespec_sec(&inode_item->mtime);
223         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(&inode_item->mtime);
224         inode->i_ctime.tv_sec = btrfs_timespec_sec(&inode_item->ctime);
225         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(&inode_item->ctime);
226         inode->i_blocks = btrfs_inode_nblocks(inode_item);
227         inode->i_generation = btrfs_inode_generation(inode_item);
228         inode->i_rdev = 0;
229         rdev = btrfs_inode_rdev(inode_item);
230         alloc_group_block = btrfs_inode_block_group(inode_item);
231         BTRFS_I(inode)->block_group = btrfs_lookup_block_group(root->fs_info,
232                                                        alloc_group_block);
233
234         btrfs_free_path(path);
235         inode_item = NULL;
236
237         mutex_unlock(&root->fs_info->fs_mutex);
238
239         switch (inode->i_mode & S_IFMT) {
240         case S_IFREG:
241                 inode->i_mapping->a_ops = &btrfs_aops;
242                 BTRFS_I(inode)->extent_tree.ops = &btrfs_extent_map_ops;
243                 inode->i_fop = &btrfs_file_operations;
244                 inode->i_op = &btrfs_file_inode_operations;
245                 break;
246         case S_IFDIR:
247                 inode->i_fop = &btrfs_dir_file_operations;
248                 if (root == root->fs_info->tree_root)
249                         inode->i_op = &btrfs_dir_ro_inode_operations;
250                 else
251                         inode->i_op = &btrfs_dir_inode_operations;
252                 break;
253         case S_IFLNK:
254                 inode->i_op = &btrfs_symlink_inode_operations;
255                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
256                 break;
257         default:
258                 init_special_inode(inode, inode->i_mode, rdev);
259                 break;
260         }
261         return;
262
263 make_bad:
264         btrfs_release_path(root, path);
265         btrfs_free_path(path);
266         mutex_unlock(&root->fs_info->fs_mutex);
267         make_bad_inode(inode);
268 }
269
270 static void fill_inode_item(struct btrfs_inode_item *item,
271                             struct inode *inode)
272 {
273         btrfs_set_inode_uid(item, inode->i_uid);
274         btrfs_set_inode_gid(item, inode->i_gid);
275         btrfs_set_inode_size(item, inode->i_size);
276         btrfs_set_inode_mode(item, inode->i_mode);
277         btrfs_set_inode_nlink(item, inode->i_nlink);
278         btrfs_set_timespec_sec(&item->atime, inode->i_atime.tv_sec);
279         btrfs_set_timespec_nsec(&item->atime, inode->i_atime.tv_nsec);
280         btrfs_set_timespec_sec(&item->mtime, inode->i_mtime.tv_sec);
281         btrfs_set_timespec_nsec(&item->mtime, inode->i_mtime.tv_nsec);
282         btrfs_set_timespec_sec(&item->ctime, inode->i_ctime.tv_sec);
283         btrfs_set_timespec_nsec(&item->ctime, inode->i_ctime.tv_nsec);
284         btrfs_set_inode_nblocks(item, inode->i_blocks);
285         btrfs_set_inode_generation(item, inode->i_generation);
286         btrfs_set_inode_rdev(item, inode->i_rdev);
287         btrfs_set_inode_block_group(item,
288                                     BTRFS_I(inode)->block_group->key.objectid);
289 }
290
291 int btrfs_update_inode(struct btrfs_trans_handle *trans,
292                               struct btrfs_root *root,
293                               struct inode *inode)
294 {
295         struct btrfs_inode_item *inode_item;
296         struct btrfs_path *path;
297         int ret;
298
299         path = btrfs_alloc_path();
300         BUG_ON(!path);
301         ret = btrfs_lookup_inode(trans, root, path,
302                                  &BTRFS_I(inode)->location, 1);
303         if (ret) {
304                 if (ret > 0)
305                         ret = -ENOENT;
306                 goto failed;
307         }
308
309         inode_item = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
310                                   path->slots[0],
311                                   struct btrfs_inode_item);
312
313         fill_inode_item(inode_item, inode);
314         btrfs_mark_buffer_dirty(path->nodes[0]);
315         btrfs_set_inode_last_trans(trans, inode);
316         ret = 0;
317 failed:
318         btrfs_release_path(root, path);
319         btrfs_free_path(path);
320         return ret;
321 }
322
323
324 static int btrfs_unlink_trans(struct btrfs_trans_handle *trans,
325                               struct btrfs_root *root,
326                               struct inode *dir,
327                               struct dentry *dentry)
328 {
329         struct btrfs_path *path;
330         const char *name = dentry->d_name.name;
331         int name_len = dentry->d_name.len;
332         int ret = 0;
333         u64 objectid;
334         struct btrfs_dir_item *di;
335
336         path = btrfs_alloc_path();
337         if (!path) {
338                 ret = -ENOMEM;
339                 goto err;
340         }
341
342         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
343                                     name, name_len, -1);
344         if (IS_ERR(di)) {
345                 ret = PTR_ERR(di);
346                 goto err;
347         }
348         if (!di) {
349                 ret = -ENOENT;
350                 goto err;
351         }
352         objectid = btrfs_disk_key_objectid(&di->location);
353         ret = btrfs_delete_one_dir_name(trans, root, path, di);
354         if (ret)
355                 goto err;
356         btrfs_release_path(root, path);
357
358         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
359                                          objectid, name, name_len, -1);
360         if (IS_ERR(di)) {
361                 ret = PTR_ERR(di);
362                 goto err;
363         }
364         if (!di) {
365                 ret = -ENOENT;
366                 goto err;
367         }
368         ret = btrfs_delete_one_dir_name(trans, root, path, di);
369
370         dentry->d_inode->i_ctime = dir->i_ctime;
371 err:
372         btrfs_free_path(path);
373         if (!ret) {
374                 dir->i_size -= name_len * 2;
375                 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
376                 btrfs_update_inode(trans, root, dir);
377                 drop_nlink(dentry->d_inode);
378                 ret = btrfs_update_inode(trans, root, dentry->d_inode);
379                 dir->i_sb->s_dirt = 1;
380         }
381         return ret;
382 }
383
384 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
385 {
386         struct btrfs_root *root;
387         struct btrfs_trans_handle *trans;
388         int ret;
389         unsigned long nr;
390
391         root = BTRFS_I(dir)->root;
392         mutex_lock(&root->fs_info->fs_mutex);
393         trans = btrfs_start_transaction(root, 1);
394         btrfs_set_trans_block_group(trans, dir);
395         ret = btrfs_unlink_trans(trans, root, dir, dentry);
396         nr = trans->blocks_used;
397         btrfs_end_transaction(trans, root);
398         mutex_unlock(&root->fs_info->fs_mutex);
399         btrfs_btree_balance_dirty(root, nr);
400         return ret;
401 }
402
403 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
404 {
405         struct inode *inode = dentry->d_inode;
406         int err;
407         int ret;
408         struct btrfs_root *root = BTRFS_I(dir)->root;
409         struct btrfs_path *path;
410         struct btrfs_key key;
411         struct btrfs_trans_handle *trans;
412         struct btrfs_key found_key;
413         int found_type;
414         struct btrfs_leaf *leaf;
415         char *goodnames = "..";
416         unsigned long nr;
417
418         path = btrfs_alloc_path();
419         BUG_ON(!path);
420         mutex_lock(&root->fs_info->fs_mutex);
421         trans = btrfs_start_transaction(root, 1);
422         btrfs_set_trans_block_group(trans, dir);
423         key.objectid = inode->i_ino;
424         key.offset = (u64)-1;
425         key.flags = (u32)-1;
426         while(1) {
427                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
428                 if (ret < 0) {
429                         err = ret;
430                         goto out;
431                 }
432                 BUG_ON(ret == 0);
433                 if (path->slots[0] == 0) {
434                         err = -ENOENT;
435                         goto out;
436                 }
437                 path->slots[0]--;
438                 leaf = btrfs_buffer_leaf(path->nodes[0]);
439                 btrfs_disk_key_to_cpu(&found_key,
440                                       &leaf->items[path->slots[0]].key);
441                 found_type = btrfs_key_type(&found_key);
442                 if (found_key.objectid != inode->i_ino) {
443                         err = -ENOENT;
444                         goto out;
445                 }
446                 if ((found_type != BTRFS_DIR_ITEM_KEY &&
447                      found_type != BTRFS_DIR_INDEX_KEY) ||
448                     (!btrfs_match_dir_item_name(root, path, goodnames, 2) &&
449                     !btrfs_match_dir_item_name(root, path, goodnames, 1))) {
450                         err = -ENOTEMPTY;
451                         goto out;
452                 }
453                 ret = btrfs_del_item(trans, root, path);
454                 BUG_ON(ret);
455
456                 if (found_type == BTRFS_DIR_ITEM_KEY && found_key.offset == 1)
457                         break;
458                 btrfs_release_path(root, path);
459         }
460         ret = 0;
461         btrfs_release_path(root, path);
462
463         /* now the directory is empty */
464         err = btrfs_unlink_trans(trans, root, dir, dentry);
465         if (!err) {
466                 inode->i_size = 0;
467         }
468 out:
469         btrfs_release_path(root, path);
470         btrfs_free_path(path);
471         mutex_unlock(&root->fs_info->fs_mutex);
472         nr = trans->blocks_used;
473         ret = btrfs_end_transaction(trans, root);
474         btrfs_btree_balance_dirty(root, nr);
475         if (ret && !err)
476                 err = ret;
477         return err;
478 }
479
480 static int btrfs_free_inode(struct btrfs_trans_handle *trans,
481                             struct btrfs_root *root,
482                             struct inode *inode)
483 {
484         struct btrfs_path *path;
485         int ret;
486
487         clear_inode(inode);
488
489         path = btrfs_alloc_path();
490         BUG_ON(!path);
491         ret = btrfs_lookup_inode(trans, root, path,
492                                  &BTRFS_I(inode)->location, -1);
493         if (ret > 0)
494                 ret = -ENOENT;
495         if (!ret)
496                 ret = btrfs_del_item(trans, root, path);
497         btrfs_free_path(path);
498         return ret;
499 }
500
501 /*
502  * this can truncate away extent items, csum items and directory items.
503  * It starts at a high offset and removes keys until it can't find
504  * any higher than i_size.
505  *
506  * csum items that cross the new i_size are truncated to the new size
507  * as well.
508  */
509 static int btrfs_truncate_in_trans(struct btrfs_trans_handle *trans,
510                                    struct btrfs_root *root,
511                                    struct inode *inode)
512 {
513         int ret;
514         struct btrfs_path *path;
515         struct btrfs_key key;
516         struct btrfs_disk_key *found_key;
517         u32 found_type;
518         struct btrfs_leaf *leaf;
519         struct btrfs_file_extent_item *fi;
520         u64 extent_start = 0;
521         u64 extent_num_blocks = 0;
522         u64 item_end = 0;
523         int found_extent;
524         int del_item;
525
526         btrfs_drop_extent_cache(inode, inode->i_size, (u64)-1);
527         path = btrfs_alloc_path();
528         path->reada = -1;
529         BUG_ON(!path);
530         /* FIXME, add redo link to tree so we don't leak on crash */
531         key.objectid = inode->i_ino;
532         key.offset = (u64)-1;
533         key.flags = (u32)-1;
534         while(1) {
535                 btrfs_init_path(path);
536                 fi = NULL;
537                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
538                 if (ret < 0) {
539                         goto error;
540                 }
541                 if (ret > 0) {
542                         BUG_ON(path->slots[0] == 0);
543                         path->slots[0]--;
544                 }
545                 leaf = btrfs_buffer_leaf(path->nodes[0]);
546                 found_key = &leaf->items[path->slots[0]].key;
547                 found_type = btrfs_disk_key_type(found_key);
548
549                 if (btrfs_disk_key_objectid(found_key) != inode->i_ino)
550                         break;
551                 if (found_type != BTRFS_CSUM_ITEM_KEY &&
552                     found_type != BTRFS_DIR_ITEM_KEY &&
553                     found_type != BTRFS_DIR_INDEX_KEY &&
554                     found_type != BTRFS_EXTENT_DATA_KEY)
555                         break;
556
557                 item_end = btrfs_disk_key_offset(found_key);
558                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
559                         fi = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
560                                             path->slots[0],
561                                             struct btrfs_file_extent_item);
562                         if (btrfs_file_extent_type(fi) !=
563                             BTRFS_FILE_EXTENT_INLINE) {
564                                 item_end += btrfs_file_extent_num_blocks(fi) <<
565                                                 inode->i_blkbits;
566                         }
567                 }
568                 if (found_type == BTRFS_CSUM_ITEM_KEY) {
569                         ret = btrfs_csum_truncate(trans, root, path,
570                                                   inode->i_size);
571                         BUG_ON(ret);
572                 }
573                 if (item_end < inode->i_size) {
574                         if (found_type == BTRFS_DIR_ITEM_KEY) {
575                                 found_type = BTRFS_INODE_ITEM_KEY;
576                         } else if (found_type == BTRFS_EXTENT_ITEM_KEY) {
577                                 found_type = BTRFS_CSUM_ITEM_KEY;
578                         } else if (found_type) {
579                                 found_type--;
580                         } else {
581                                 break;
582                         }
583                         btrfs_set_key_type(&key, found_type);
584                         continue;
585                 }
586                 if (btrfs_disk_key_offset(found_key) >= inode->i_size)
587                         del_item = 1;
588                 else
589                         del_item = 0;
590                 found_extent = 0;
591
592                 /* FIXME, shrink the extent if the ref count is only 1 */
593                 if (found_type == BTRFS_EXTENT_DATA_KEY &&
594                            btrfs_file_extent_type(fi) !=
595                            BTRFS_FILE_EXTENT_INLINE) {
596                         u64 num_dec;
597                         extent_start = btrfs_file_extent_disk_blocknr(fi);
598                         if (!del_item) {
599                                 u64 orig_num_blocks =
600                                         btrfs_file_extent_num_blocks(fi);
601                                 extent_num_blocks = inode->i_size -
602                                         btrfs_disk_key_offset(found_key) +
603                                         root->blocksize - 1;
604                                 extent_num_blocks >>= inode->i_blkbits;
605                                 btrfs_set_file_extent_num_blocks(fi,
606                                                          extent_num_blocks);
607                                 num_dec = (orig_num_blocks -
608                                            extent_num_blocks) << 3;
609                                 if (extent_start != 0) {
610                                         inode->i_blocks -= num_dec;
611                                 }
612                                 btrfs_mark_buffer_dirty(path->nodes[0]);
613                         } else {
614                                 extent_num_blocks =
615                                         btrfs_file_extent_disk_num_blocks(fi);
616                                 /* FIXME blocksize != 4096 */
617                                 num_dec = btrfs_file_extent_num_blocks(fi) << 3;
618                                 if (extent_start != 0) {
619                                         found_extent = 1;
620                                         inode->i_blocks -= num_dec;
621                                 }
622                         }
623                 }
624                 if (del_item) {
625                         ret = btrfs_del_item(trans, root, path);
626                         if (ret)
627                                 goto error;
628                 } else {
629                         break;
630                 }
631                 btrfs_release_path(root, path);
632                 if (found_extent) {
633                         ret = btrfs_free_extent(trans, root, extent_start,
634                                                 extent_num_blocks, 0);
635                         BUG_ON(ret);
636                 }
637         }
638         ret = 0;
639 error:
640         btrfs_release_path(root, path);
641         btrfs_free_path(path);
642         inode->i_sb->s_dirt = 1;
643         return ret;
644 }
645
646 static int btrfs_cow_one_page(struct inode *inode, struct page *page,
647                               size_t zero_start)
648 {
649         char *kaddr;
650         int ret = 0;
651         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
652         u64 page_start = page->index << PAGE_CACHE_SHIFT;
653         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
654
655         if (!PagePrivate(page)) {
656                 SetPagePrivate(page);
657                 set_page_private(page, 1);
658                 WARN_ON(!page->mapping->a_ops->invalidatepage);
659                 page_cache_get(page);
660         }
661
662         lock_extent(em_tree, page_start, page_end, GFP_NOFS);
663         set_extent_delalloc(&BTRFS_I(inode)->extent_tree, page_start,
664                             page_end, GFP_NOFS);
665         if (zero_start != PAGE_CACHE_SIZE) {
666                 kaddr = kmap(page);
667                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
668                 flush_dcache_page(page);
669                 kunmap(page);
670         }
671         set_page_dirty(page);
672         unlock_extent(em_tree, page_start, page_end, GFP_NOFS);
673
674         return ret;
675 }
676
677 /*
678  * taken from block_truncate_page, but does cow as it zeros out
679  * any bytes left in the last page in the file.
680  */
681 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
682 {
683         struct inode *inode = mapping->host;
684         unsigned blocksize = 1 << inode->i_blkbits;
685         pgoff_t index = from >> PAGE_CACHE_SHIFT;
686         unsigned offset = from & (PAGE_CACHE_SIZE-1);
687         struct page *page;
688         int ret = 0;
689         u64 page_start;
690
691         if ((offset & (blocksize - 1)) == 0)
692                 goto out;
693
694         down_read(&BTRFS_I(inode)->root->snap_sem);
695         ret = -ENOMEM;
696         page = grab_cache_page(mapping, index);
697         if (!page)
698                 goto out;
699         if (!PageUptodate(page)) {
700                 ret = btrfs_readpage(NULL, page);
701                 lock_page(page);
702                 if (!PageUptodate(page)) {
703                         ret = -EIO;
704                         goto out;
705                 }
706         }
707         page_start = page->index << PAGE_CACHE_SHIFT;
708
709         ret = btrfs_cow_one_page(inode, page, offset);
710
711         unlock_page(page);
712         page_cache_release(page);
713         up_read(&BTRFS_I(inode)->root->snap_sem);
714 out:
715         return ret;
716 }
717
718 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
719 {
720         struct inode *inode = dentry->d_inode;
721         int err;
722
723         err = inode_change_ok(inode, attr);
724         if (err)
725                 return err;
726
727         if (S_ISREG(inode->i_mode) &&
728             attr->ia_valid & ATTR_SIZE && attr->ia_size > inode->i_size) {
729                 struct btrfs_trans_handle *trans;
730                 struct btrfs_root *root = BTRFS_I(inode)->root;
731                 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
732
733                 u64 mask = root->blocksize - 1;
734                 u64 pos = (inode->i_size + mask) & ~mask;
735                 u64 block_end = attr->ia_size | mask;
736                 u64 hole_size;
737                 u64 alloc_hint;
738
739                 if (attr->ia_size <= pos)
740                         goto out;
741
742                 btrfs_truncate_page(inode->i_mapping, inode->i_size);
743
744                 lock_extent(em_tree, pos, block_end, GFP_NOFS);
745                 hole_size = (attr->ia_size - pos + mask) & ~mask;
746
747                 mutex_lock(&root->fs_info->fs_mutex);
748                 trans = btrfs_start_transaction(root, 1);
749                 btrfs_set_trans_block_group(trans, inode);
750                 err = btrfs_drop_extents(trans, root, inode,
751                                          pos, pos + hole_size, &alloc_hint);
752
753                 hole_size >>= inode->i_blkbits;
754
755                 err = btrfs_insert_file_extent(trans, root, inode->i_ino,
756                                                pos, 0, 0, hole_size);
757                 btrfs_end_transaction(trans, root);
758                 mutex_unlock(&root->fs_info->fs_mutex);
759                 unlock_extent(em_tree, pos, block_end, GFP_NOFS);
760                 if (err)
761                         return err;
762         }
763 out:
764         err = inode_setattr(inode, attr);
765
766         return err;
767 }
768 void btrfs_delete_inode(struct inode *inode)
769 {
770         struct btrfs_trans_handle *trans;
771         struct btrfs_root *root = BTRFS_I(inode)->root;
772         unsigned long nr;
773         int ret;
774
775         truncate_inode_pages(&inode->i_data, 0);
776         if (is_bad_inode(inode)) {
777                 goto no_delete;
778         }
779         inode->i_size = 0;
780         mutex_lock(&root->fs_info->fs_mutex);
781         trans = btrfs_start_transaction(root, 1);
782         btrfs_set_trans_block_group(trans, inode);
783         ret = btrfs_truncate_in_trans(trans, root, inode);
784         if (ret)
785                 goto no_delete_lock;
786         ret = btrfs_free_inode(trans, root, inode);
787         if (ret)
788                 goto no_delete_lock;
789         nr = trans->blocks_used;
790         btrfs_end_transaction(trans, root);
791         mutex_unlock(&root->fs_info->fs_mutex);
792         btrfs_btree_balance_dirty(root, nr);
793         return;
794
795 no_delete_lock:
796         nr = trans->blocks_used;
797         btrfs_end_transaction(trans, root);
798         mutex_unlock(&root->fs_info->fs_mutex);
799         btrfs_btree_balance_dirty(root, nr);
800 no_delete:
801         clear_inode(inode);
802 }
803
804 /*
805  * this returns the key found in the dir entry in the location pointer.
806  * If no dir entries were found, location->objectid is 0.
807  */
808 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
809                                struct btrfs_key *location)
810 {
811         const char *name = dentry->d_name.name;
812         int namelen = dentry->d_name.len;
813         struct btrfs_dir_item *di;
814         struct btrfs_path *path;
815         struct btrfs_root *root = BTRFS_I(dir)->root;
816         int ret;
817
818         path = btrfs_alloc_path();
819         BUG_ON(!path);
820         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
821                                     namelen, 0);
822         if (!di || IS_ERR(di)) {
823                 location->objectid = 0;
824                 ret = 0;
825                 goto out;
826         }
827         btrfs_disk_key_to_cpu(location, &di->location);
828 out:
829         btrfs_release_path(root, path);
830         btrfs_free_path(path);
831         return ret;
832 }
833
834 /*
835  * when we hit a tree root in a directory, the btrfs part of the inode
836  * needs to be changed to reflect the root directory of the tree root.  This
837  * is kind of like crossing a mount point.
838  */
839 static int fixup_tree_root_location(struct btrfs_root *root,
840                              struct btrfs_key *location,
841                              struct btrfs_root **sub_root,
842                              struct dentry *dentry)
843 {
844         struct btrfs_path *path;
845         struct btrfs_root_item *ri;
846
847         if (btrfs_key_type(location) != BTRFS_ROOT_ITEM_KEY)
848                 return 0;
849         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
850                 return 0;
851
852         path = btrfs_alloc_path();
853         BUG_ON(!path);
854         mutex_lock(&root->fs_info->fs_mutex);
855
856         *sub_root = btrfs_read_fs_root(root->fs_info, location,
857                                         dentry->d_name.name,
858                                         dentry->d_name.len);
859         if (IS_ERR(*sub_root))
860                 return PTR_ERR(*sub_root);
861
862         ri = &(*sub_root)->root_item;
863         location->objectid = btrfs_root_dirid(ri);
864         location->flags = 0;
865         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
866         location->offset = 0;
867
868         btrfs_free_path(path);
869         mutex_unlock(&root->fs_info->fs_mutex);
870         return 0;
871 }
872
873 static int btrfs_init_locked_inode(struct inode *inode, void *p)
874 {
875         struct btrfs_iget_args *args = p;
876         inode->i_ino = args->ino;
877         BTRFS_I(inode)->root = args->root;
878         extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
879                              inode->i_mapping, GFP_NOFS);
880         return 0;
881 }
882
883 static int btrfs_find_actor(struct inode *inode, void *opaque)
884 {
885         struct btrfs_iget_args *args = opaque;
886         return (args->ino == inode->i_ino &&
887                 args->root == BTRFS_I(inode)->root);
888 }
889
890 struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid,
891                                 struct btrfs_root *root)
892 {
893         struct inode *inode;
894         struct btrfs_iget_args args;
895         args.ino = objectid;
896         args.root = root;
897
898         inode = iget5_locked(s, objectid, btrfs_find_actor,
899                              btrfs_init_locked_inode,
900                              (void *)&args);
901         return inode;
902 }
903
904 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
905                                    struct nameidata *nd)
906 {
907         struct inode * inode;
908         struct btrfs_inode *bi = BTRFS_I(dir);
909         struct btrfs_root *root = bi->root;
910         struct btrfs_root *sub_root = root;
911         struct btrfs_key location;
912         int ret;
913
914         if (dentry->d_name.len > BTRFS_NAME_LEN)
915                 return ERR_PTR(-ENAMETOOLONG);
916         mutex_lock(&root->fs_info->fs_mutex);
917         ret = btrfs_inode_by_name(dir, dentry, &location);
918         mutex_unlock(&root->fs_info->fs_mutex);
919         if (ret < 0)
920                 return ERR_PTR(ret);
921         inode = NULL;
922         if (location.objectid) {
923                 ret = fixup_tree_root_location(root, &location, &sub_root,
924                                                 dentry);
925                 if (ret < 0)
926                         return ERR_PTR(ret);
927                 if (ret > 0)
928                         return ERR_PTR(-ENOENT);
929                 inode = btrfs_iget_locked(dir->i_sb, location.objectid,
930                                           sub_root);
931                 if (!inode)
932                         return ERR_PTR(-EACCES);
933                 if (inode->i_state & I_NEW) {
934                         /* the inode and parent dir are two different roots */
935                         if (sub_root != root) {
936                                 igrab(inode);
937                                 sub_root->inode = inode;
938                         }
939                         BTRFS_I(inode)->root = sub_root;
940                         memcpy(&BTRFS_I(inode)->location, &location,
941                                sizeof(location));
942                         btrfs_read_locked_inode(inode);
943                         unlock_new_inode(inode);
944                 }
945         }
946         return d_splice_alias(inode, dentry);
947 }
948
949 static unsigned char btrfs_filetype_table[] = {
950         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
951 };
952
953 static int btrfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
954 {
955         struct inode *inode = filp->f_path.dentry->d_inode;
956         struct btrfs_root *root = BTRFS_I(inode)->root;
957         struct btrfs_item *item;
958         struct btrfs_dir_item *di;
959         struct btrfs_key key;
960         struct btrfs_path *path;
961         int ret;
962         u32 nritems;
963         struct btrfs_leaf *leaf;
964         int slot;
965         int advance;
966         unsigned char d_type;
967         int over = 0;
968         u32 di_cur;
969         u32 di_total;
970         u32 di_len;
971         int key_type = BTRFS_DIR_INDEX_KEY;
972
973         /* FIXME, use a real flag for deciding about the key type */
974         if (root->fs_info->tree_root == root)
975                 key_type = BTRFS_DIR_ITEM_KEY;
976         mutex_lock(&root->fs_info->fs_mutex);
977         key.objectid = inode->i_ino;
978         key.flags = 0;
979         btrfs_set_key_type(&key, key_type);
980         key.offset = filp->f_pos;
981         path = btrfs_alloc_path();
982         path->reada = 2;
983         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
984         if (ret < 0)
985                 goto err;
986         advance = 0;
987         while(1) {
988                 leaf = btrfs_buffer_leaf(path->nodes[0]);
989                 nritems = btrfs_header_nritems(&leaf->header);
990                 slot = path->slots[0];
991                 if (advance || slot >= nritems) {
992                         if (slot >= nritems -1) {
993                                 ret = btrfs_next_leaf(root, path);
994                                 if (ret)
995                                         break;
996                                 leaf = btrfs_buffer_leaf(path->nodes[0]);
997                                 nritems = btrfs_header_nritems(&leaf->header);
998                                 slot = path->slots[0];
999                         } else {
1000                                 slot++;
1001                                 path->slots[0]++;
1002                         }
1003                 }
1004                 advance = 1;
1005                 item = leaf->items + slot;
1006                 if (btrfs_disk_key_objectid(&item->key) != key.objectid)
1007                         break;
1008                 if (btrfs_disk_key_type(&item->key) != key_type)
1009                         break;
1010                 if (btrfs_disk_key_offset(&item->key) < filp->f_pos)
1011                         continue;
1012                 filp->f_pos = btrfs_disk_key_offset(&item->key);
1013                 advance = 1;
1014                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
1015                 di_cur = 0;
1016                 di_total = btrfs_item_size(leaf->items + slot);
1017                 while(di_cur < di_total) {
1018                         d_type = btrfs_filetype_table[btrfs_dir_type(di)];
1019                         over = filldir(dirent, (const char *)(di + 1),
1020                                        btrfs_dir_name_len(di),
1021                                        btrfs_disk_key_offset(&item->key),
1022                                        btrfs_disk_key_objectid(&di->location),
1023                                        d_type);
1024                         if (over)
1025                                 goto nopos;
1026                         di_len = btrfs_dir_name_len(di) + sizeof(*di);
1027                         di_cur += di_len;
1028                         di = (struct btrfs_dir_item *)((char *)di + di_len);
1029                 }
1030         }
1031         filp->f_pos++;
1032 nopos:
1033         ret = 0;
1034 err:
1035         btrfs_release_path(root, path);
1036         btrfs_free_path(path);
1037         mutex_unlock(&root->fs_info->fs_mutex);
1038         return ret;
1039 }
1040
1041 int btrfs_write_inode(struct inode *inode, int wait)
1042 {
1043         struct btrfs_root *root = BTRFS_I(inode)->root;
1044         struct btrfs_trans_handle *trans;
1045         int ret = 0;
1046
1047         if (wait) {
1048                 mutex_lock(&root->fs_info->fs_mutex);
1049                 trans = btrfs_start_transaction(root, 1);
1050                 btrfs_set_trans_block_group(trans, inode);
1051                 ret = btrfs_commit_transaction(trans, root);
1052                 mutex_unlock(&root->fs_info->fs_mutex);
1053         }
1054         return ret;
1055 }
1056
1057 /*
1058  * This is somewhat expensive, updating the tree every time the
1059  * inode changes.  But, it is most likely to find the inode in cache.
1060  * FIXME, needs more benchmarking...there are no reasons other than performance
1061  * to keep or drop this code.
1062  */
1063 void btrfs_dirty_inode(struct inode *inode)
1064 {
1065         struct btrfs_root *root = BTRFS_I(inode)->root;
1066         struct btrfs_trans_handle *trans;
1067
1068         mutex_lock(&root->fs_info->fs_mutex);
1069         trans = btrfs_start_transaction(root, 1);
1070         btrfs_set_trans_block_group(trans, inode);
1071         btrfs_update_inode(trans, root, inode);
1072         btrfs_end_transaction(trans, root);
1073         mutex_unlock(&root->fs_info->fs_mutex);
1074 }
1075
1076 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
1077                                      struct btrfs_root *root,
1078                                      u64 objectid,
1079                                      struct btrfs_block_group_cache *group,
1080                                      int mode)
1081 {
1082         struct inode *inode;
1083         struct btrfs_inode_item inode_item;
1084         struct btrfs_key *location;
1085         int ret;
1086         int owner;
1087
1088         inode = new_inode(root->fs_info->sb);
1089         if (!inode)
1090                 return ERR_PTR(-ENOMEM);
1091
1092         extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
1093                              inode->i_mapping, GFP_NOFS);
1094         BTRFS_I(inode)->root = root;
1095
1096         if (mode & S_IFDIR)
1097                 owner = 0;
1098         else
1099                 owner = 1;
1100         group = btrfs_find_block_group(root, group, 0, 0, owner);
1101         BTRFS_I(inode)->block_group = group;
1102
1103         inode->i_uid = current->fsuid;
1104         inode->i_gid = current->fsgid;
1105         inode->i_mode = mode;
1106         inode->i_ino = objectid;
1107         inode->i_blocks = 0;
1108         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
1109         fill_inode_item(&inode_item, inode);
1110         location = &BTRFS_I(inode)->location;
1111         location->objectid = objectid;
1112         location->flags = 0;
1113         location->offset = 0;
1114         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
1115
1116         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
1117         if (ret)
1118                 return ERR_PTR(ret);
1119         insert_inode_hash(inode);
1120         return inode;
1121 }
1122
1123 static inline u8 btrfs_inode_type(struct inode *inode)
1124 {
1125         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
1126 }
1127
1128 static int btrfs_add_link(struct btrfs_trans_handle *trans,
1129                             struct dentry *dentry, struct inode *inode)
1130 {
1131         int ret;
1132         struct btrfs_key key;
1133         struct btrfs_root *root = BTRFS_I(dentry->d_parent->d_inode)->root;
1134         struct inode *parent_inode;
1135         key.objectid = inode->i_ino;
1136         key.flags = 0;
1137         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
1138         key.offset = 0;
1139
1140         ret = btrfs_insert_dir_item(trans, root,
1141                                     dentry->d_name.name, dentry->d_name.len,
1142                                     dentry->d_parent->d_inode->i_ino,
1143                                     &key, btrfs_inode_type(inode));
1144         if (ret == 0) {
1145                 parent_inode = dentry->d_parent->d_inode;
1146                 parent_inode->i_size += dentry->d_name.len * 2;
1147                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
1148                 ret = btrfs_update_inode(trans, root,
1149                                          dentry->d_parent->d_inode);
1150         }
1151         return ret;
1152 }
1153
1154 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
1155                             struct dentry *dentry, struct inode *inode)
1156 {
1157         int err = btrfs_add_link(trans, dentry, inode);
1158         if (!err) {
1159                 d_instantiate(dentry, inode);
1160                 return 0;
1161         }
1162         if (err > 0)
1163                 err = -EEXIST;
1164         return err;
1165 }
1166
1167 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1168                         int mode, dev_t rdev)
1169 {
1170         struct btrfs_trans_handle *trans;
1171         struct btrfs_root *root = BTRFS_I(dir)->root;
1172         struct inode *inode;
1173         int err;
1174         int drop_inode = 0;
1175         u64 objectid;
1176         unsigned long nr;
1177
1178         if (!new_valid_dev(rdev))
1179                 return -EINVAL;
1180
1181         mutex_lock(&root->fs_info->fs_mutex);
1182         trans = btrfs_start_transaction(root, 1);
1183         btrfs_set_trans_block_group(trans, dir);
1184
1185         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1186         if (err) {
1187                 err = -ENOSPC;
1188                 goto out_unlock;
1189         }
1190
1191         inode = btrfs_new_inode(trans, root, objectid,
1192                                 BTRFS_I(dir)->block_group, mode);
1193         err = PTR_ERR(inode);
1194         if (IS_ERR(inode))
1195                 goto out_unlock;
1196
1197         btrfs_set_trans_block_group(trans, inode);
1198         err = btrfs_add_nondir(trans, dentry, inode);
1199         if (err)
1200                 drop_inode = 1;
1201         else {
1202                 inode->i_op = &btrfs_special_inode_operations;
1203                 init_special_inode(inode, inode->i_mode, rdev);
1204                 btrfs_update_inode(trans, root, inode);
1205         }
1206         dir->i_sb->s_dirt = 1;
1207         btrfs_update_inode_block_group(trans, inode);
1208         btrfs_update_inode_block_group(trans, dir);
1209 out_unlock:
1210         nr = trans->blocks_used;
1211         btrfs_end_transaction(trans, root);
1212         mutex_unlock(&root->fs_info->fs_mutex);
1213
1214         if (drop_inode) {
1215                 inode_dec_link_count(inode);
1216                 iput(inode);
1217         }
1218         btrfs_btree_balance_dirty(root, nr);
1219         return err;
1220 }
1221
1222 static int btrfs_create(struct inode *dir, struct dentry *dentry,
1223                         int mode, struct nameidata *nd)
1224 {
1225         struct btrfs_trans_handle *trans;
1226         struct btrfs_root *root = BTRFS_I(dir)->root;
1227         struct inode *inode;
1228         int err;
1229         int drop_inode = 0;
1230         unsigned long nr;
1231         u64 objectid;
1232
1233         mutex_lock(&root->fs_info->fs_mutex);
1234         trans = btrfs_start_transaction(root, 1);
1235         btrfs_set_trans_block_group(trans, dir);
1236
1237         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1238         if (err) {
1239                 err = -ENOSPC;
1240                 goto out_unlock;
1241         }
1242
1243         inode = btrfs_new_inode(trans, root, objectid,
1244                                 BTRFS_I(dir)->block_group, mode);
1245         err = PTR_ERR(inode);
1246         if (IS_ERR(inode))
1247                 goto out_unlock;
1248
1249         btrfs_set_trans_block_group(trans, inode);
1250         err = btrfs_add_nondir(trans, dentry, inode);
1251         if (err)
1252                 drop_inode = 1;
1253         else {
1254                 inode->i_mapping->a_ops = &btrfs_aops;
1255                 inode->i_fop = &btrfs_file_operations;
1256                 inode->i_op = &btrfs_file_inode_operations;
1257                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
1258                                      inode->i_mapping, GFP_NOFS);
1259                 BTRFS_I(inode)->extent_tree.ops = &btrfs_extent_map_ops;
1260         }
1261         dir->i_sb->s_dirt = 1;
1262         btrfs_update_inode_block_group(trans, inode);
1263         btrfs_update_inode_block_group(trans, dir);
1264 out_unlock:
1265         nr = trans->blocks_used;
1266         btrfs_end_transaction(trans, root);
1267         mutex_unlock(&root->fs_info->fs_mutex);
1268
1269         if (drop_inode) {
1270                 inode_dec_link_count(inode);
1271                 iput(inode);
1272         }
1273         btrfs_btree_balance_dirty(root, nr);
1274         return err;
1275 }
1276
1277 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
1278                       struct dentry *dentry)
1279 {
1280         struct btrfs_trans_handle *trans;
1281         struct btrfs_root *root = BTRFS_I(dir)->root;
1282         struct inode *inode = old_dentry->d_inode;
1283         unsigned long nr;
1284         int err;
1285         int drop_inode = 0;
1286
1287         if (inode->i_nlink == 0)
1288                 return -ENOENT;
1289
1290         inc_nlink(inode);
1291         mutex_lock(&root->fs_info->fs_mutex);
1292         trans = btrfs_start_transaction(root, 1);
1293         btrfs_set_trans_block_group(trans, dir);
1294         atomic_inc(&inode->i_count);
1295         err = btrfs_add_nondir(trans, dentry, inode);
1296         if (err)
1297                 drop_inode = 1;
1298         dir->i_sb->s_dirt = 1;
1299         btrfs_update_inode_block_group(trans, dir);
1300         err = btrfs_update_inode(trans, root, inode);
1301         if (err)
1302                 drop_inode = 1;
1303
1304         nr = trans->blocks_used;
1305         btrfs_end_transaction(trans, root);
1306         mutex_unlock(&root->fs_info->fs_mutex);
1307
1308         if (drop_inode) {
1309                 inode_dec_link_count(inode);
1310                 iput(inode);
1311         }
1312         btrfs_btree_balance_dirty(root, nr);
1313         return err;
1314 }
1315
1316 static int btrfs_make_empty_dir(struct btrfs_trans_handle *trans,
1317                                 struct btrfs_root *root,
1318                                 u64 objectid, u64 dirid)
1319 {
1320         int ret;
1321         char buf[2];
1322         struct btrfs_key key;
1323
1324         buf[0] = '.';
1325         buf[1] = '.';
1326
1327         key.objectid = objectid;
1328         key.offset = 0;
1329         key.flags = 0;
1330         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
1331
1332         ret = btrfs_insert_dir_item(trans, root, buf, 1, objectid,
1333                                     &key, BTRFS_FT_DIR);
1334         if (ret)
1335                 goto error;
1336         key.objectid = dirid;
1337         ret = btrfs_insert_dir_item(trans, root, buf, 2, objectid,
1338                                     &key, BTRFS_FT_DIR);
1339         if (ret)
1340                 goto error;
1341 error:
1342         return ret;
1343 }
1344
1345 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1346 {
1347         struct inode *inode;
1348         struct btrfs_trans_handle *trans;
1349         struct btrfs_root *root = BTRFS_I(dir)->root;
1350         int err = 0;
1351         int drop_on_err = 0;
1352         u64 objectid;
1353         unsigned long nr = 1;
1354
1355         mutex_lock(&root->fs_info->fs_mutex);
1356         trans = btrfs_start_transaction(root, 1);
1357         btrfs_set_trans_block_group(trans, dir);
1358         if (IS_ERR(trans)) {
1359                 err = PTR_ERR(trans);
1360                 goto out_unlock;
1361         }
1362
1363         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1364         if (err) {
1365                 err = -ENOSPC;
1366                 goto out_unlock;
1367         }
1368
1369         inode = btrfs_new_inode(trans, root, objectid,
1370                                 BTRFS_I(dir)->block_group, S_IFDIR | mode);
1371         if (IS_ERR(inode)) {
1372                 err = PTR_ERR(inode);
1373                 goto out_fail;
1374         }
1375         drop_on_err = 1;
1376         inode->i_op = &btrfs_dir_inode_operations;
1377         inode->i_fop = &btrfs_dir_file_operations;
1378         btrfs_set_trans_block_group(trans, inode);
1379
1380         err = btrfs_make_empty_dir(trans, root, inode->i_ino, dir->i_ino);
1381         if (err)
1382                 goto out_fail;
1383
1384         inode->i_size = 6;
1385         err = btrfs_update_inode(trans, root, inode);
1386         if (err)
1387                 goto out_fail;
1388         err = btrfs_add_link(trans, dentry, inode);
1389         if (err)
1390                 goto out_fail;
1391         d_instantiate(dentry, inode);
1392         drop_on_err = 0;
1393         dir->i_sb->s_dirt = 1;
1394         btrfs_update_inode_block_group(trans, inode);
1395         btrfs_update_inode_block_group(trans, dir);
1396
1397 out_fail:
1398         nr = trans->blocks_used;
1399         btrfs_end_transaction(trans, root);
1400 out_unlock:
1401         mutex_unlock(&root->fs_info->fs_mutex);
1402         if (drop_on_err)
1403                 iput(inode);
1404         btrfs_btree_balance_dirty(root, nr);
1405         return err;
1406 }
1407
1408 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
1409                                     size_t page_offset, u64 start, u64 end,
1410                                     int create)
1411 {
1412         int ret;
1413         int err = 0;
1414         u64 blocknr;
1415         u64 extent_start = 0;
1416         u64 extent_end = 0;
1417         u64 objectid = inode->i_ino;
1418         u32 found_type;
1419         int failed_insert = 0;
1420         struct btrfs_path *path;
1421         struct btrfs_root *root = BTRFS_I(inode)->root;
1422         struct btrfs_file_extent_item *item;
1423         struct btrfs_leaf *leaf;
1424         struct btrfs_disk_key *found_key;
1425         struct extent_map *em = NULL;
1426         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1427         struct btrfs_trans_handle *trans = NULL;
1428
1429         path = btrfs_alloc_path();
1430         BUG_ON(!path);
1431         mutex_lock(&root->fs_info->fs_mutex);
1432
1433 again:
1434         em = lookup_extent_mapping(em_tree, start, end);
1435         if (em) {
1436                 goto out;
1437         }
1438         if (!em) {
1439                 em = alloc_extent_map(GFP_NOFS);
1440                 if (!em) {
1441                         err = -ENOMEM;
1442                         goto out;
1443                 }
1444                 em->start = 0;
1445                 em->end = 0;
1446         }
1447         em->bdev = inode->i_sb->s_bdev;
1448         ret = btrfs_lookup_file_extent(NULL, root, path,
1449                                        objectid, start, 0);
1450         if (ret < 0) {
1451                 err = ret;
1452                 goto out;
1453         }
1454
1455         if (ret != 0) {
1456                 if (path->slots[0] == 0)
1457                         goto not_found;
1458                 path->slots[0]--;
1459         }
1460
1461         item = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]), path->slots[0],
1462                               struct btrfs_file_extent_item);
1463         leaf = btrfs_buffer_leaf(path->nodes[0]);
1464         blocknr = btrfs_file_extent_disk_blocknr(item);
1465         blocknr += btrfs_file_extent_offset(item);
1466
1467         /* are we inside the extent that was found? */
1468         found_key = &leaf->items[path->slots[0]].key;
1469         found_type = btrfs_disk_key_type(found_key);
1470         if (btrfs_disk_key_objectid(found_key) != objectid ||
1471             found_type != BTRFS_EXTENT_DATA_KEY) {
1472                 goto not_found;
1473         }
1474
1475         found_type = btrfs_file_extent_type(item);
1476         extent_start = btrfs_disk_key_offset(&leaf->items[path->slots[0]].key);
1477         if (found_type == BTRFS_FILE_EXTENT_REG) {
1478                 extent_end = extent_start +
1479                        (btrfs_file_extent_num_blocks(item) << inode->i_blkbits);
1480                 err = 0;
1481                 if (start < extent_start || start >= extent_end) {
1482                         em->start = start;
1483                         if (start < extent_start) {
1484                                 if (end < extent_start)
1485                                         goto not_found;
1486                                 em->end = extent_end - 1;
1487                         } else {
1488                                 em->end = end;
1489                         }
1490                         goto not_found_em;
1491                 }
1492                 if (btrfs_file_extent_disk_blocknr(item) == 0) {
1493                         em->start = extent_start;
1494                         em->end = extent_end - 1;
1495                         em->block_start = 0;
1496                         em->block_end = 0;
1497                         goto insert;
1498                 }
1499                 em->block_start = blocknr << inode->i_blkbits;
1500                 em->block_end = em->block_start +
1501                         (btrfs_file_extent_num_blocks(item) <<
1502                          inode->i_blkbits) - 1;
1503                 em->start = extent_start;
1504                 em->end = extent_end - 1;
1505                 goto insert;
1506         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
1507                 char *ptr;
1508                 char *map;
1509                 u32 size;
1510
1511                 size = btrfs_file_extent_inline_len(leaf->items +
1512                                                     path->slots[0]);
1513                 extent_end = extent_start + size;
1514                 if (start < extent_start || start >= extent_end) {
1515                         em->start = start;
1516                         if (start < extent_start) {
1517                                 if (end < extent_start)
1518                                         goto not_found;
1519                                 em->end = extent_end - 1;
1520                         } else {
1521                                 em->end = end;
1522                         }
1523                         goto not_found_em;
1524                 }
1525                 em->block_start = EXTENT_MAP_INLINE;
1526                 em->block_end = EXTENT_MAP_INLINE;
1527                 em->start = extent_start;
1528                 em->end = extent_end - 1;
1529                 if (!page) {
1530                         goto insert;
1531                 }
1532                 ptr = btrfs_file_extent_inline_start(item);
1533                 map = kmap(page);
1534                 memcpy(map + page_offset, ptr, size);
1535                 flush_dcache_page(result->b_page);
1536                 kunmap(page);
1537                 set_extent_uptodate(em_tree, extent_start,
1538                                     extent_end - 1, GFP_NOFS);
1539                 goto insert;
1540         } else {
1541                 printk("unkknown found_type %d\n", found_type);
1542                 WARN_ON(1);
1543         }
1544 not_found:
1545         em->start = start;
1546         em->end = end;
1547 not_found_em:
1548         em->block_start = 0;
1549         em->block_end = 0;
1550 insert:
1551         btrfs_release_path(root, path);
1552         if (em->start > start || em->end < start) {
1553                 printk("bad extent! em: [%Lu %Lu] passed [%Lu %Lu]\n", em->start, em->end, start, end);
1554                 err = -EIO;
1555                 goto out;
1556         }
1557         ret = add_extent_mapping(em_tree, em);
1558         if (ret == -EEXIST) {
1559                 free_extent_map(em);
1560                 em = NULL;
1561                 failed_insert++;
1562                 if (failed_insert > 5) {
1563                         printk("failing to insert %Lu %Lu\n", start, end);
1564                         err = -EIO;
1565                         goto out;
1566                 }
1567                 goto again;
1568         }
1569         err = 0;
1570 out:
1571         btrfs_free_path(path);
1572         if (trans) {
1573                 ret = btrfs_end_transaction(trans, root);
1574                 if (!err)
1575                         err = ret;
1576         }
1577         mutex_unlock(&root->fs_info->fs_mutex);
1578         if (err) {
1579                 free_extent_map(em);
1580                 WARN_ON(1);
1581                 return ERR_PTR(err);
1582         }
1583         return em;
1584 }
1585
1586 static sector_t btrfs_bmap(struct address_space *mapping, sector_t iblock)
1587 {
1588         return extent_bmap(mapping, iblock, btrfs_get_extent);
1589 }
1590
1591 static int btrfs_prepare_write(struct file *file, struct page *page,
1592                                unsigned from, unsigned to)
1593 {
1594         return extent_prepare_write(&BTRFS_I(page->mapping->host)->extent_tree,
1595                                     page->mapping->host, page, from, to,
1596                                     btrfs_get_extent);
1597 }
1598
1599 int btrfs_readpage(struct file *file, struct page *page)
1600 {
1601         struct extent_map_tree *tree;
1602         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1603         return extent_read_full_page(tree, page, btrfs_get_extent);
1604 }
1605 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
1606 {
1607         struct extent_map_tree *tree;
1608
1609
1610         if (current->flags & PF_MEMALLOC) {
1611                 redirty_page_for_writepage(wbc, page);
1612                 unlock_page(page);
1613                 return 0;
1614         }
1615         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1616         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
1617 }
1618
1619 static int btrfs_releasepage(struct page *page, gfp_t unused_gfp_flags)
1620 {
1621         struct extent_map_tree *tree;
1622         int ret;
1623
1624         if (page->private != 1) {
1625                 WARN_ON(1);
1626                 return try_to_free_buffers(page);
1627         }
1628         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1629         ret = try_release_extent_mapping(tree, page);
1630         if (ret == 1) {
1631                 ClearPagePrivate(page);
1632                 set_page_private(page, 0);
1633                 page_cache_release(page);
1634         }
1635         return ret;
1636 }
1637
1638 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
1639 {
1640         struct extent_map_tree *tree;
1641
1642         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1643         extent_invalidatepage(tree, page, offset);
1644         btrfs_releasepage(page, GFP_NOFS);
1645 }
1646
1647 /*
1648  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
1649  * called from a page fault handler when a page is first dirtied. Hence we must
1650  * be careful to check for EOF conditions here. We set the page up correctly
1651  * for a written page which means we get ENOSPC checking when writing into
1652  * holes and correct delalloc and unwritten extent mapping on filesystems that
1653  * support these features.
1654  *
1655  * We are not allowed to take the i_mutex here so we have to play games to
1656  * protect against truncate races as the page could now be beyond EOF.  Because
1657  * vmtruncate() writes the inode size before removing pages, once we have the
1658  * page lock we can determine safely if the page is beyond EOF. If it is not
1659  * beyond EOF, then the page is guaranteed safe against truncation until we
1660  * unlock the page.
1661  */
1662 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct page *page)
1663 {
1664         struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
1665         unsigned long end;
1666         loff_t size;
1667         int ret = -EINVAL;
1668         u64 page_start;
1669
1670         down_read(&BTRFS_I(inode)->root->snap_sem);
1671         lock_page(page);
1672         wait_on_page_writeback(page);
1673         size = i_size_read(inode);
1674         page_start = page->index << PAGE_CACHE_SHIFT;
1675
1676         if ((page->mapping != inode->i_mapping) ||
1677             (page_start > size)) {
1678                 /* page got truncated out from underneath us */
1679                 goto out_unlock;
1680         }
1681
1682         /* page is wholly or partially inside EOF */
1683         if (page_start + PAGE_CACHE_SIZE > size)
1684                 end = size & ~PAGE_CACHE_MASK;
1685         else
1686                 end = PAGE_CACHE_SIZE;
1687
1688         ret = btrfs_cow_one_page(inode, page, end);
1689
1690 out_unlock:
1691         up_read(&BTRFS_I(inode)->root->snap_sem);
1692         unlock_page(page);
1693         return ret;
1694 }
1695
1696 static void btrfs_truncate(struct inode *inode)
1697 {
1698         struct btrfs_root *root = BTRFS_I(inode)->root;
1699         int ret;
1700         struct btrfs_trans_handle *trans;
1701         unsigned long nr;
1702
1703         if (!S_ISREG(inode->i_mode))
1704                 return;
1705         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
1706                 return;
1707
1708         btrfs_truncate_page(inode->i_mapping, inode->i_size);
1709
1710         mutex_lock(&root->fs_info->fs_mutex);
1711         trans = btrfs_start_transaction(root, 1);
1712         btrfs_set_trans_block_group(trans, inode);
1713
1714         /* FIXME, add redo link to tree so we don't leak on crash */
1715         ret = btrfs_truncate_in_trans(trans, root, inode);
1716         btrfs_update_inode(trans, root, inode);
1717         nr = trans->blocks_used;
1718         ret = btrfs_end_transaction(trans, root);
1719         BUG_ON(ret);
1720         mutex_unlock(&root->fs_info->fs_mutex);
1721         btrfs_btree_balance_dirty(root, nr);
1722 }
1723
1724 int btrfs_commit_write(struct file *file, struct page *page,
1725                        unsigned from, unsigned to)
1726 {
1727         return extent_commit_write(&BTRFS_I(page->mapping->host)->extent_tree,
1728                                    page->mapping->host, page, from, to);
1729 }
1730
1731 static int create_subvol(struct btrfs_root *root, char *name, int namelen)
1732 {
1733         struct btrfs_trans_handle *trans;
1734         struct btrfs_key key;
1735         struct btrfs_root_item root_item;
1736         struct btrfs_inode_item *inode_item;
1737         struct buffer_head *subvol;
1738         struct btrfs_leaf *leaf;
1739         struct btrfs_root *new_root;
1740         struct inode *inode;
1741         struct inode *dir;
1742         int ret;
1743         int err;
1744         u64 objectid;
1745         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
1746         unsigned long nr = 1;
1747
1748         mutex_lock(&root->fs_info->fs_mutex);
1749         trans = btrfs_start_transaction(root, 1);
1750         BUG_ON(!trans);
1751
1752         subvol = btrfs_alloc_free_block(trans, root, 0, 0);
1753         if (IS_ERR(subvol))
1754                 return PTR_ERR(subvol);
1755         leaf = btrfs_buffer_leaf(subvol);
1756         btrfs_set_header_nritems(&leaf->header, 0);
1757         btrfs_set_header_level(&leaf->header, 0);
1758         btrfs_set_header_blocknr(&leaf->header, bh_blocknr(subvol));
1759         btrfs_set_header_generation(&leaf->header, trans->transid);
1760         btrfs_set_header_owner(&leaf->header, root->root_key.objectid);
1761         memcpy(leaf->header.fsid, root->fs_info->disk_super->fsid,
1762                sizeof(leaf->header.fsid));
1763         btrfs_mark_buffer_dirty(subvol);
1764
1765         inode_item = &root_item.inode;
1766         memset(inode_item, 0, sizeof(*inode_item));
1767         btrfs_set_inode_generation(inode_item, 1);
1768         btrfs_set_inode_size(inode_item, 3);
1769         btrfs_set_inode_nlink(inode_item, 1);
1770         btrfs_set_inode_nblocks(inode_item, 1);
1771         btrfs_set_inode_mode(inode_item, S_IFDIR | 0755);
1772
1773         btrfs_set_root_blocknr(&root_item, bh_blocknr(subvol));
1774         btrfs_set_root_refs(&root_item, 1);
1775         btrfs_set_root_blocks_used(&root_item, 0);
1776         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
1777         root_item.drop_level = 0;
1778         brelse(subvol);
1779         subvol = NULL;
1780
1781         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
1782                                        0, &objectid);
1783         if (ret)
1784                 goto fail;
1785
1786         btrfs_set_root_dirid(&root_item, new_dirid);
1787
1788         key.objectid = objectid;
1789         key.offset = 1;
1790         key.flags = 0;
1791         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
1792         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
1793                                 &root_item);
1794         if (ret)
1795                 goto fail;
1796
1797         /*
1798          * insert the directory item
1799          */
1800         key.offset = (u64)-1;
1801         dir = root->fs_info->sb->s_root->d_inode;
1802         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
1803                                     name, namelen, dir->i_ino, &key,
1804                                     BTRFS_FT_DIR);
1805         if (ret)
1806                 goto fail;
1807
1808         ret = btrfs_commit_transaction(trans, root);
1809         if (ret)
1810                 goto fail_commit;
1811
1812         new_root = btrfs_read_fs_root(root->fs_info, &key, name, namelen);
1813         BUG_ON(!new_root);
1814
1815         trans = btrfs_start_transaction(new_root, 1);
1816         BUG_ON(!trans);
1817
1818         inode = btrfs_new_inode(trans, new_root, new_dirid,
1819                                 BTRFS_I(dir)->block_group, S_IFDIR | 0700);
1820         if (IS_ERR(inode))
1821                 goto fail;
1822         inode->i_op = &btrfs_dir_inode_operations;
1823         inode->i_fop = &btrfs_dir_file_operations;
1824         new_root->inode = inode;
1825
1826         ret = btrfs_make_empty_dir(trans, new_root, new_dirid, new_dirid);
1827         if (ret)
1828                 goto fail;
1829
1830         inode->i_nlink = 1;
1831         inode->i_size = 6;
1832         ret = btrfs_update_inode(trans, new_root, inode);
1833         if (ret)
1834                 goto fail;
1835 fail:
1836         nr = trans->blocks_used;
1837         err = btrfs_commit_transaction(trans, root);
1838         if (err && !ret)
1839                 ret = err;
1840 fail_commit:
1841         mutex_unlock(&root->fs_info->fs_mutex);
1842         btrfs_btree_balance_dirty(root, nr);
1843         return ret;
1844 }
1845
1846 static int create_snapshot(struct btrfs_root *root, char *name, int namelen)
1847 {
1848         struct btrfs_trans_handle *trans;
1849         struct btrfs_key key;
1850         struct btrfs_root_item new_root_item;
1851         struct buffer_head *tmp;
1852         int ret;
1853         int err;
1854         u64 objectid;
1855         unsigned long nr;
1856
1857         if (!root->ref_cows)
1858                 return -EINVAL;
1859
1860         down_write(&root->snap_sem);
1861         freeze_bdev(root->fs_info->sb->s_bdev);
1862         thaw_bdev(root->fs_info->sb->s_bdev, root->fs_info->sb);
1863
1864         mutex_lock(&root->fs_info->fs_mutex);
1865         trans = btrfs_start_transaction(root, 1);
1866         BUG_ON(!trans);
1867
1868         ret = btrfs_update_inode(trans, root, root->inode);
1869         if (ret)
1870                 goto fail;
1871
1872         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
1873                                        0, &objectid);
1874         if (ret)
1875                 goto fail;
1876
1877         memcpy(&new_root_item, &root->root_item,
1878                sizeof(new_root_item));
1879
1880         key.objectid = objectid;
1881         key.offset = 1;
1882         key.flags = 0;
1883         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
1884         btrfs_cow_block(trans, root, root->node, NULL, 0, &tmp);
1885         btrfs_set_root_blocknr(&new_root_item, bh_blocknr(root->node));
1886
1887         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
1888                                 &new_root_item);
1889         if (ret)
1890                 goto fail;
1891
1892         /*
1893          * insert the directory item
1894          */
1895         key.offset = (u64)-1;
1896         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
1897                                     name, namelen,
1898                                     root->fs_info->sb->s_root->d_inode->i_ino,
1899                                     &key, BTRFS_FT_DIR);
1900
1901         if (ret)
1902                 goto fail;
1903
1904         ret = btrfs_inc_root_ref(trans, root);
1905         if (ret)
1906                 goto fail;
1907 fail:
1908         nr = trans->blocks_used;
1909         err = btrfs_commit_transaction(trans, root);
1910         if (err && !ret)
1911                 ret = err;
1912         mutex_unlock(&root->fs_info->fs_mutex);
1913         up_write(&root->snap_sem);
1914         btrfs_btree_balance_dirty(root, nr);
1915         return ret;
1916 }
1917
1918 static unsigned long force_ra(struct address_space *mapping,
1919                               struct file_ra_state *ra, struct file *file,
1920                               pgoff_t offset, pgoff_t last_index)
1921 {
1922         pgoff_t req_size;
1923
1924 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
1925         req_size = last_index - offset + 1;
1926         offset = page_cache_readahead(mapping, ra, file, offset, req_size);
1927         return offset;
1928 #else
1929         req_size = min(last_index - offset + 1, (pgoff_t)128);
1930         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
1931         return offset + req_size;
1932 #endif
1933 }
1934
1935 int btrfs_defrag_file(struct file *file) {
1936         struct inode *inode = file->f_path.dentry->d_inode;
1937         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1938         struct page *page;
1939         unsigned long last_index;
1940         unsigned long ra_index = 0;
1941         u64 page_start;
1942         u64 page_end;
1943         unsigned long i;
1944
1945         mutex_lock(&inode->i_mutex);
1946         last_index = inode->i_size >> PAGE_CACHE_SHIFT;
1947         for (i = 0; i <= last_index; i++) {
1948                 if (i == ra_index) {
1949                         ra_index = force_ra(inode->i_mapping, &file->f_ra,
1950                                             file, ra_index, last_index);
1951                 }
1952                 page = grab_cache_page(inode->i_mapping, i);
1953                 if (!page)
1954                         goto out_unlock;
1955                 if (!PageUptodate(page)) {
1956                         btrfs_readpage(NULL, page);
1957                         lock_page(page);
1958                         if (!PageUptodate(page)) {
1959                                 unlock_page(page);
1960                                 page_cache_release(page);
1961                                 goto out_unlock;
1962                         }
1963                 }
1964                 page_start = page->index << PAGE_CACHE_SHIFT;
1965                 page_end = page_start + PAGE_CACHE_SIZE - 1;
1966
1967                 lock_extent(em_tree, page_start, page_end, GFP_NOFS);
1968                 set_extent_delalloc(em_tree, page_start,
1969                                     page_end, GFP_NOFS);
1970                 unlock_extent(em_tree, page_start, page_end, GFP_NOFS);
1971                 set_page_dirty(page);
1972                 unlock_page(page);
1973                 page_cache_release(page);
1974                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, 1);
1975         }
1976
1977 out_unlock:
1978         mutex_unlock(&inode->i_mutex);
1979         return 0;
1980 }
1981
1982 static int btrfs_ioctl_snap_create(struct btrfs_root *root, void __user *arg)
1983 {
1984         struct btrfs_ioctl_vol_args vol_args;
1985         struct btrfs_dir_item *di;
1986         struct btrfs_path *path;
1987         int namelen;
1988         u64 root_dirid;
1989
1990         if (copy_from_user(&vol_args, arg, sizeof(vol_args)))
1991                 return -EFAULT;
1992         
1993         namelen = strlen(vol_args.name);
1994         if (namelen > BTRFS_VOL_NAME_MAX)
1995                 return -EINVAL;
1996         if (strchr(vol_args.name, '/'))
1997                 return -EINVAL;
1998
1999         path = btrfs_alloc_path();
2000         if (!path)
2001                 return -ENOMEM;
2002
2003         root_dirid = root->fs_info->sb->s_root->d_inode->i_ino,
2004         mutex_lock(&root->fs_info->fs_mutex);
2005         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root,
2006                             path, root_dirid,
2007                             vol_args.name, namelen, 0);
2008         mutex_unlock(&root->fs_info->fs_mutex);
2009         btrfs_free_path(path);
2010         if (di && !IS_ERR(di))
2011                 return -EEXIST;
2012         if (IS_ERR(di))
2013                 return PTR_ERR(di);
2014
2015         if (root == root->fs_info->tree_root)
2016                 return create_subvol(root, vol_args.name, namelen);
2017         return create_snapshot(root, vol_args.name, namelen);
2018 }
2019
2020 static int btrfs_ioctl_defrag(struct file *file)
2021 {
2022         struct inode *inode = file->f_path.dentry->d_inode;
2023         struct btrfs_root *root = BTRFS_I(inode)->root;
2024
2025         switch (inode->i_mode & S_IFMT) {
2026         case S_IFDIR:
2027                 mutex_lock(&root->fs_info->fs_mutex);
2028                 btrfs_defrag_root(root, 0);
2029                 btrfs_defrag_root(root->fs_info->extent_root, 0);
2030                 mutex_unlock(&root->fs_info->fs_mutex);
2031                 break;
2032         case S_IFREG:
2033                 btrfs_defrag_file(file);
2034                 break;
2035         }
2036
2037         return 0;
2038 }
2039
2040 long btrfs_ioctl(struct file *file, unsigned int
2041                 cmd, unsigned long arg)
2042 {
2043         struct btrfs_root *root = BTRFS_I(file->f_path.dentry->d_inode)->root;
2044
2045         switch (cmd) {
2046         case BTRFS_IOC_SNAP_CREATE:
2047                 return btrfs_ioctl_snap_create(root, (void __user *)arg);
2048         case BTRFS_IOC_DEFRAG:
2049                 return btrfs_ioctl_defrag(file);
2050         }
2051
2052         return -ENOTTY;
2053 }
2054
2055 /*
2056  * Called inside transaction, so use GFP_NOFS
2057  */
2058 struct inode *btrfs_alloc_inode(struct super_block *sb)
2059 {
2060         struct btrfs_inode *ei;
2061
2062         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
2063         if (!ei)
2064                 return NULL;
2065         ei->last_trans = 0;
2066         return &ei->vfs_inode;
2067 }
2068
2069 void btrfs_destroy_inode(struct inode *inode)
2070 {
2071         WARN_ON(!list_empty(&inode->i_dentry));
2072         WARN_ON(inode->i_data.nrpages);
2073
2074         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
2075 }
2076
2077 static void init_once(void * foo, struct kmem_cache * cachep,
2078                       unsigned long flags)
2079 {
2080         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
2081
2082         inode_init_once(&ei->vfs_inode);
2083 }
2084
2085 void btrfs_destroy_cachep(void)
2086 {
2087         if (btrfs_inode_cachep)
2088                 kmem_cache_destroy(btrfs_inode_cachep);
2089         if (btrfs_trans_handle_cachep)
2090                 kmem_cache_destroy(btrfs_trans_handle_cachep);
2091         if (btrfs_transaction_cachep)
2092                 kmem_cache_destroy(btrfs_transaction_cachep);
2093         if (btrfs_bit_radix_cachep)
2094                 kmem_cache_destroy(btrfs_bit_radix_cachep);
2095         if (btrfs_path_cachep)
2096                 kmem_cache_destroy(btrfs_path_cachep);
2097 }
2098
2099 struct kmem_cache *btrfs_cache_create(const char *name, size_t size,
2100                                        unsigned long extra_flags,
2101                                        void (*ctor)(void *, struct kmem_cache *,
2102                                                     unsigned long))
2103 {
2104         return kmem_cache_create(name, size, 0, (SLAB_RECLAIM_ACCOUNT |
2105                                  SLAB_MEM_SPREAD | extra_flags), ctor
2106 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
2107                                  ,NULL
2108 #endif
2109                                 );
2110 }
2111
2112 int btrfs_init_cachep(void)
2113 {
2114         btrfs_inode_cachep = btrfs_cache_create("btrfs_inode_cache",
2115                                           sizeof(struct btrfs_inode),
2116                                           0, init_once);
2117         if (!btrfs_inode_cachep)
2118                 goto fail;
2119         btrfs_trans_handle_cachep =
2120                         btrfs_cache_create("btrfs_trans_handle_cache",
2121                                            sizeof(struct btrfs_trans_handle),
2122                                            0, NULL);
2123         if (!btrfs_trans_handle_cachep)
2124                 goto fail;
2125         btrfs_transaction_cachep = btrfs_cache_create("btrfs_transaction_cache",
2126                                              sizeof(struct btrfs_transaction),
2127                                              0, NULL);
2128         if (!btrfs_transaction_cachep)
2129                 goto fail;
2130         btrfs_path_cachep = btrfs_cache_create("btrfs_path_cache",
2131                                          sizeof(struct btrfs_path),
2132                                          0, NULL);
2133         if (!btrfs_path_cachep)
2134                 goto fail;
2135         btrfs_bit_radix_cachep = btrfs_cache_create("btrfs_radix", 256,
2136                                               SLAB_DESTROY_BY_RCU, NULL);
2137         if (!btrfs_bit_radix_cachep)
2138                 goto fail;
2139         return 0;
2140 fail:
2141         btrfs_destroy_cachep();
2142         return -ENOMEM;
2143 }
2144
2145 static int btrfs_getattr(struct vfsmount *mnt,
2146                          struct dentry *dentry, struct kstat *stat)
2147 {
2148         struct inode *inode = dentry->d_inode;
2149         generic_fillattr(inode, stat);
2150         stat->blksize = 256 * 1024;
2151         return 0;
2152 }
2153
2154 static int btrfs_rename(struct inode * old_dir, struct dentry *old_dentry,
2155                            struct inode * new_dir,struct dentry *new_dentry)
2156 {
2157         struct btrfs_trans_handle *trans;
2158         struct btrfs_root *root = BTRFS_I(old_dir)->root;
2159         struct inode *new_inode = new_dentry->d_inode;
2160         struct inode *old_inode = old_dentry->d_inode;
2161         struct timespec ctime = CURRENT_TIME;
2162         struct btrfs_path *path;
2163         struct btrfs_dir_item *di;
2164         int ret;
2165
2166         if (S_ISDIR(old_inode->i_mode) && new_inode &&
2167             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
2168                 return -ENOTEMPTY;
2169         }
2170         mutex_lock(&root->fs_info->fs_mutex);
2171         trans = btrfs_start_transaction(root, 1);
2172         btrfs_set_trans_block_group(trans, new_dir);
2173         path = btrfs_alloc_path();
2174         if (!path) {
2175                 ret = -ENOMEM;
2176                 goto out_fail;
2177         }
2178
2179         old_dentry->d_inode->i_nlink++;
2180         old_dir->i_ctime = old_dir->i_mtime = ctime;
2181         new_dir->i_ctime = new_dir->i_mtime = ctime;
2182         old_inode->i_ctime = ctime;
2183         if (S_ISDIR(old_inode->i_mode) && old_dir != new_dir) {
2184                 struct btrfs_key *location = &BTRFS_I(new_dir)->location;
2185                 u64 old_parent_oid;
2186                 di = btrfs_lookup_dir_item(trans, root, path, old_inode->i_ino,
2187                                            "..", 2, -1);
2188                 if (IS_ERR(di)) {
2189                         ret = PTR_ERR(di);
2190                         goto out_fail;
2191                 }
2192                 if (!di) {
2193                         ret = -ENOENT;
2194                         goto out_fail;
2195                 }
2196                 old_parent_oid = btrfs_disk_key_objectid(&di->location);
2197                 ret = btrfs_del_item(trans, root, path);
2198                 if (ret) {
2199                         goto out_fail;
2200                 }
2201                 btrfs_release_path(root, path);
2202
2203                 di = btrfs_lookup_dir_index_item(trans, root, path,
2204                                                  old_inode->i_ino,
2205                                                  old_parent_oid,
2206                                                  "..", 2, -1);
2207                 if (IS_ERR(di)) {
2208                         ret = PTR_ERR(di);
2209                         goto out_fail;
2210                 }
2211                 if (!di) {
2212                         ret = -ENOENT;
2213                         goto out_fail;
2214                 }
2215                 ret = btrfs_del_item(trans, root, path);
2216                 if (ret) {
2217                         goto out_fail;
2218                 }
2219                 btrfs_release_path(root, path);
2220
2221                 ret = btrfs_insert_dir_item(trans, root, "..", 2,
2222                                             old_inode->i_ino, location,
2223                                             BTRFS_FT_DIR);
2224                 if (ret)
2225                         goto out_fail;
2226         }
2227
2228
2229         ret = btrfs_unlink_trans(trans, root, old_dir, old_dentry);
2230         if (ret)
2231                 goto out_fail;
2232
2233         if (new_inode) {
2234                 new_inode->i_ctime = CURRENT_TIME;
2235                 ret = btrfs_unlink_trans(trans, root, new_dir, new_dentry);
2236                 if (ret)
2237                         goto out_fail;
2238         }
2239         ret = btrfs_add_link(trans, new_dentry, old_inode);
2240         if (ret)
2241                 goto out_fail;
2242
2243 out_fail:
2244         btrfs_free_path(path);
2245         btrfs_end_transaction(trans, root);
2246         mutex_unlock(&root->fs_info->fs_mutex);
2247         return ret;
2248 }
2249
2250 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
2251                          const char *symname)
2252 {
2253         struct btrfs_trans_handle *trans;
2254         struct btrfs_root *root = BTRFS_I(dir)->root;
2255         struct btrfs_path *path;
2256         struct btrfs_key key;
2257         struct inode *inode;
2258         int err;
2259         int drop_inode = 0;
2260         u64 objectid;
2261         int name_len;
2262         int datasize;
2263         char *ptr;
2264         struct btrfs_file_extent_item *ei;
2265         unsigned long nr;
2266
2267         name_len = strlen(symname) + 1;
2268         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
2269                 return -ENAMETOOLONG;
2270         mutex_lock(&root->fs_info->fs_mutex);
2271         trans = btrfs_start_transaction(root, 1);
2272         btrfs_set_trans_block_group(trans, dir);
2273
2274         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
2275         if (err) {
2276                 err = -ENOSPC;
2277                 goto out_unlock;
2278         }
2279
2280         inode = btrfs_new_inode(trans, root, objectid,
2281                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO);
2282         err = PTR_ERR(inode);
2283         if (IS_ERR(inode))
2284                 goto out_unlock;
2285
2286         btrfs_set_trans_block_group(trans, inode);
2287         err = btrfs_add_nondir(trans, dentry, inode);
2288         if (err)
2289                 drop_inode = 1;
2290         else {
2291                 inode->i_mapping->a_ops = &btrfs_aops;
2292                 inode->i_fop = &btrfs_file_operations;
2293                 inode->i_op = &btrfs_file_inode_operations;
2294                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
2295                                      inode->i_mapping, GFP_NOFS);
2296                 BTRFS_I(inode)->extent_tree.ops = &btrfs_extent_map_ops;
2297         }
2298         dir->i_sb->s_dirt = 1;
2299         btrfs_update_inode_block_group(trans, inode);
2300         btrfs_update_inode_block_group(trans, dir);
2301         if (drop_inode)
2302                 goto out_unlock;
2303
2304         path = btrfs_alloc_path();
2305         BUG_ON(!path);
2306         key.objectid = inode->i_ino;
2307         key.offset = 0;
2308         key.flags = 0;
2309         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
2310         datasize = btrfs_file_extent_calc_inline_size(name_len);
2311         err = btrfs_insert_empty_item(trans, root, path, &key,
2312                                       datasize);
2313         if (err) {
2314                 drop_inode = 1;
2315                 goto out_unlock;
2316         }
2317         ei = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
2318                path->slots[0], struct btrfs_file_extent_item);
2319         btrfs_set_file_extent_generation(ei, trans->transid);
2320         btrfs_set_file_extent_type(ei,
2321                                    BTRFS_FILE_EXTENT_INLINE);
2322         ptr = btrfs_file_extent_inline_start(ei);
2323         btrfs_memcpy(root, path->nodes[0]->b_data,
2324                      ptr, symname, name_len);
2325         btrfs_mark_buffer_dirty(path->nodes[0]);
2326         btrfs_free_path(path);
2327         inode->i_op = &btrfs_symlink_inode_operations;
2328         inode->i_mapping->a_ops = &btrfs_symlink_aops;
2329         inode->i_size = name_len - 1;
2330         err = btrfs_update_inode(trans, root, inode);
2331         if (err)
2332                 drop_inode = 1;
2333
2334 out_unlock:
2335         nr = trans->blocks_used;
2336         btrfs_end_transaction(trans, root);
2337         mutex_unlock(&root->fs_info->fs_mutex);
2338         if (drop_inode) {
2339                 inode_dec_link_count(inode);
2340                 iput(inode);
2341         }
2342         btrfs_btree_balance_dirty(root, nr);
2343         return err;
2344 }
2345
2346 static struct inode_operations btrfs_dir_inode_operations = {
2347         .lookup         = btrfs_lookup,
2348         .create         = btrfs_create,
2349         .unlink         = btrfs_unlink,
2350         .link           = btrfs_link,
2351         .mkdir          = btrfs_mkdir,
2352         .rmdir          = btrfs_rmdir,
2353         .rename         = btrfs_rename,
2354         .symlink        = btrfs_symlink,
2355         .setattr        = btrfs_setattr,
2356         .mknod          = btrfs_mknod,
2357 };
2358
2359 static struct inode_operations btrfs_dir_ro_inode_operations = {
2360         .lookup         = btrfs_lookup,
2361 };
2362
2363 static struct file_operations btrfs_dir_file_operations = {
2364         .llseek         = generic_file_llseek,
2365         .read           = generic_read_dir,
2366         .readdir        = btrfs_readdir,
2367         .unlocked_ioctl = btrfs_ioctl,
2368 #ifdef CONFIG_COMPAT
2369         .compat_ioctl   = btrfs_ioctl,
2370 #endif
2371 };
2372
2373 static struct extent_map_ops btrfs_extent_map_ops = {
2374         .fill_delalloc = run_delalloc_range,
2375         .writepage_io_hook = btrfs_writepage_io_hook,
2376         .readpage_io_hook = btrfs_readpage_io_hook,
2377         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
2378 };
2379
2380 static struct address_space_operations btrfs_aops = {
2381         .readpage       = btrfs_readpage,
2382         .writepage      = btrfs_writepage,
2383         .sync_page      = block_sync_page,
2384         .prepare_write  = btrfs_prepare_write,
2385         .commit_write   = btrfs_commit_write,
2386         .bmap           = btrfs_bmap,
2387         .invalidatepage = btrfs_invalidatepage,
2388         .releasepage    = btrfs_releasepage,
2389         .set_page_dirty = __set_page_dirty_nobuffers,
2390 };
2391
2392 static struct address_space_operations btrfs_symlink_aops = {
2393         .readpage       = btrfs_readpage,
2394         .writepage      = btrfs_writepage,
2395         .invalidatepage = btrfs_invalidatepage,
2396         .releasepage    = btrfs_releasepage,
2397 };
2398
2399 static struct inode_operations btrfs_file_inode_operations = {
2400         .truncate       = btrfs_truncate,
2401         .getattr        = btrfs_getattr,
2402         .setattr        = btrfs_setattr,
2403 };
2404
2405 static struct inode_operations btrfs_special_inode_operations = {
2406         .getattr        = btrfs_getattr,
2407         .setattr        = btrfs_setattr,
2408 };
2409
2410 static struct inode_operations btrfs_symlink_inode_operations = {
2411         .readlink       = generic_readlink,
2412         .follow_link    = page_follow_link_light,
2413         .put_link       = page_put_link,
2414 };