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