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