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