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