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