]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - fs/btrfs/inode.c
0c9ec8aa304a02be7c02018f28271fa27031aeb5
[linux-2.6-omap-h63xx.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/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/smp_lock.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mpage.h>
32 #include <linux/swap.h>
33 #include <linux/writeback.h>
34 #include <linux/statfs.h>
35 #include <linux/compat.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/version.h>
38 #include <linux/xattr.h>
39 #include <linux/posix_acl.h>
40 #include "ctree.h"
41 #include "disk-io.h"
42 #include "transaction.h"
43 #include "btrfs_inode.h"
44 #include "ioctl.h"
45 #include "print-tree.h"
46 #include "volumes.h"
47 #include "ordered-data.h"
48
49 struct btrfs_iget_args {
50         u64 ino;
51         struct btrfs_root *root;
52 };
53
54 static struct inode_operations btrfs_dir_inode_operations;
55 static struct inode_operations btrfs_symlink_inode_operations;
56 static struct inode_operations btrfs_dir_ro_inode_operations;
57 static struct inode_operations btrfs_special_inode_operations;
58 static struct inode_operations btrfs_file_inode_operations;
59 static struct address_space_operations btrfs_aops;
60 static struct address_space_operations btrfs_symlink_aops;
61 static struct file_operations btrfs_dir_file_operations;
62 static struct extent_io_ops btrfs_extent_io_ops;
63
64 static struct kmem_cache *btrfs_inode_cachep;
65 struct kmem_cache *btrfs_trans_handle_cachep;
66 struct kmem_cache *btrfs_transaction_cachep;
67 struct kmem_cache *btrfs_bit_radix_cachep;
68 struct kmem_cache *btrfs_path_cachep;
69
70 #define S_SHIFT 12
71 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
72         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
73         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
74         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
75         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
76         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
77         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
78         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
79 };
80
81 static void btrfs_truncate(struct inode *inode);
82
83 int btrfs_check_free_space(struct btrfs_root *root, u64 num_required,
84                            int for_del)
85 {
86         u64 total;
87         u64 used;
88         u64 thresh;
89         unsigned long flags;
90         int ret = 0;
91
92         spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
93         total = btrfs_super_total_bytes(&root->fs_info->super_copy);
94         used = btrfs_super_bytes_used(&root->fs_info->super_copy);
95         if (for_del)
96                 thresh = total * 90;
97         else
98                 thresh = total * 85;
99
100         do_div(thresh, 100);
101
102         if (used + root->fs_info->delalloc_bytes + num_required > thresh)
103                 ret = -ENOSPC;
104         spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
105         return ret;
106 }
107
108 static int cow_file_range(struct inode *inode, u64 start, u64 end)
109 {
110         struct btrfs_root *root = BTRFS_I(inode)->root;
111         struct btrfs_trans_handle *trans;
112         u64 alloc_hint = 0;
113         u64 num_bytes;
114         u64 cur_alloc_size;
115         u64 blocksize = root->sectorsize;
116         u64 orig_num_bytes;
117         struct btrfs_key ins;
118         struct extent_map *em;
119         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
120         int ret = 0;
121
122         trans = btrfs_join_transaction(root, 1);
123         BUG_ON(!trans);
124         btrfs_set_trans_block_group(trans, inode);
125
126         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
127         num_bytes = max(blocksize,  num_bytes);
128         orig_num_bytes = num_bytes;
129
130         if (alloc_hint == EXTENT_MAP_INLINE)
131                 goto out;
132
133         BUG_ON(num_bytes > btrfs_super_total_bytes(&root->fs_info->super_copy));
134         mutex_lock(&BTRFS_I(inode)->extent_mutex);
135         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1);
136         mutex_unlock(&BTRFS_I(inode)->extent_mutex);
137
138         while(num_bytes > 0) {
139                 cur_alloc_size = min(num_bytes, root->fs_info->max_extent);
140                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
141                                            root->sectorsize, 0, 0,
142                                            (u64)-1, &ins, 1);
143                 if (ret) {
144                         WARN_ON(1);
145                         goto out;
146                 }
147                 em = alloc_extent_map(GFP_NOFS);
148                 em->start = start;
149                 em->len = ins.offset;
150                 em->block_start = ins.objectid;
151                 em->bdev = root->fs_info->fs_devices->latest_bdev;
152                 mutex_lock(&BTRFS_I(inode)->extent_mutex);
153                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
154                 while(1) {
155                         spin_lock(&em_tree->lock);
156                         ret = add_extent_mapping(em_tree, em);
157                         spin_unlock(&em_tree->lock);
158                         if (ret != -EEXIST) {
159                                 free_extent_map(em);
160                                 break;
161                         }
162                         btrfs_drop_extent_cache(inode, start,
163                                                 start + ins.offset - 1);
164                 }
165                 mutex_unlock(&BTRFS_I(inode)->extent_mutex);
166
167                 cur_alloc_size = ins.offset;
168                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
169                                                ins.offset);
170                 BUG_ON(ret);
171                 if (num_bytes < cur_alloc_size) {
172                         printk("num_bytes %Lu cur_alloc %Lu\n", num_bytes,
173                                cur_alloc_size);
174                         break;
175                 }
176                 num_bytes -= cur_alloc_size;
177                 alloc_hint = ins.objectid + ins.offset;
178                 start += cur_alloc_size;
179         }
180 out:
181         btrfs_end_transaction(trans, root);
182         return ret;
183 }
184
185 static int run_delalloc_nocow(struct inode *inode, u64 start, u64 end)
186 {
187         u64 extent_start;
188         u64 extent_end;
189         u64 bytenr;
190         u64 cow_end;
191         u64 loops = 0;
192         u64 total_fs_bytes;
193         struct btrfs_root *root = BTRFS_I(inode)->root;
194         struct btrfs_block_group_cache *block_group;
195         struct extent_buffer *leaf;
196         int found_type;
197         struct btrfs_path *path;
198         struct btrfs_file_extent_item *item;
199         int ret;
200         int err;
201         struct btrfs_key found_key;
202
203         total_fs_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
204         path = btrfs_alloc_path();
205         BUG_ON(!path);
206 again:
207         ret = btrfs_lookup_file_extent(NULL, root, path,
208                                        inode->i_ino, start, 0);
209         if (ret < 0) {
210                 btrfs_free_path(path);
211                 return ret;
212         }
213
214         cow_end = end;
215         if (ret != 0) {
216                 if (path->slots[0] == 0)
217                         goto not_found;
218                 path->slots[0]--;
219         }
220
221         leaf = path->nodes[0];
222         item = btrfs_item_ptr(leaf, path->slots[0],
223                               struct btrfs_file_extent_item);
224
225         /* are we inside the extent that was found? */
226         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
227         found_type = btrfs_key_type(&found_key);
228         if (found_key.objectid != inode->i_ino ||
229             found_type != BTRFS_EXTENT_DATA_KEY)
230                 goto not_found;
231
232         found_type = btrfs_file_extent_type(leaf, item);
233         extent_start = found_key.offset;
234         if (found_type == BTRFS_FILE_EXTENT_REG) {
235                 u64 extent_num_bytes;
236
237                 extent_num_bytes = btrfs_file_extent_num_bytes(leaf, item);
238                 extent_end = extent_start + extent_num_bytes;
239                 err = 0;
240
241                 if (loops && start != extent_start)
242                         goto not_found;
243
244                 if (start < extent_start || start >= extent_end)
245                         goto not_found;
246
247                 cow_end = min(end, extent_end - 1);
248                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
249                 if (bytenr == 0)
250                         goto not_found;
251
252                 if (btrfs_count_snapshots_in_path(root, path, inode->i_ino,
253                                                   bytenr) != 1) {
254                         goto not_found;
255                 }
256
257                 /*
258                  * we may be called by the resizer, make sure we're inside
259                  * the limits of the FS
260                  */
261                 block_group = btrfs_lookup_block_group(root->fs_info,
262                                                        bytenr);
263                 if (!block_group || block_group->ro)
264                         goto not_found;
265
266                 start = extent_end;
267         } else {
268                 goto not_found;
269         }
270 loop:
271         if (start > end) {
272                 btrfs_free_path(path);
273                 return 0;
274         }
275         btrfs_release_path(root, path);
276         loops++;
277         goto again;
278
279 not_found:
280         cow_file_range(inode, start, end);
281         start = end + 1;
282         goto loop;
283 }
284
285 static int run_delalloc_range(struct inode *inode, u64 start, u64 end)
286 {
287         struct btrfs_root *root = BTRFS_I(inode)->root;
288         int ret;
289
290         if (btrfs_test_opt(root, NODATACOW) ||
291             btrfs_test_flag(inode, NODATACOW))
292                 ret = run_delalloc_nocow(inode, start, end);
293         else
294                 ret = cow_file_range(inode, start, end);
295
296         return ret;
297 }
298
299 int btrfs_set_bit_hook(struct inode *inode, u64 start, u64 end,
300                        unsigned long old, unsigned long bits)
301 {
302         unsigned long flags;
303         if (!(old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
304                 struct btrfs_root *root = BTRFS_I(inode)->root;
305                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
306                 BTRFS_I(inode)->delalloc_bytes += end - start + 1;
307                 root->fs_info->delalloc_bytes += end - start + 1;
308                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
309         }
310         return 0;
311 }
312
313 int btrfs_clear_bit_hook(struct inode *inode, u64 start, u64 end,
314                          unsigned long old, unsigned long bits)
315 {
316         if ((old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
317                 struct btrfs_root *root = BTRFS_I(inode)->root;
318                 unsigned long flags;
319
320                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
321                 if (end - start + 1 > root->fs_info->delalloc_bytes) {
322                         printk("warning: delalloc account %Lu %Lu\n",
323                                end - start + 1, root->fs_info->delalloc_bytes);
324                         root->fs_info->delalloc_bytes = 0;
325                         BTRFS_I(inode)->delalloc_bytes = 0;
326                 } else {
327                         root->fs_info->delalloc_bytes -= end - start + 1;
328                         BTRFS_I(inode)->delalloc_bytes -= end - start + 1;
329                 }
330                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
331         }
332         return 0;
333 }
334
335 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
336                          size_t size, struct bio *bio)
337 {
338         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
339         struct btrfs_mapping_tree *map_tree;
340         u64 logical = bio->bi_sector << 9;
341         u64 length = 0;
342         u64 map_length;
343         int ret;
344
345         length = bio->bi_size;
346         map_tree = &root->fs_info->mapping_tree;
347         map_length = length;
348         ret = btrfs_map_block(map_tree, READ, logical,
349                               &map_length, NULL, 0);
350
351         if (map_length < length + size) {
352                 return 1;
353         }
354         return 0;
355 }
356
357 int __btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
358                           int mirror_num)
359 {
360         struct btrfs_root *root = BTRFS_I(inode)->root;
361         int ret = 0;
362
363         ret = btrfs_csum_one_bio(root, inode, bio);
364         BUG_ON(ret);
365
366         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
367 }
368
369 int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
370                           int mirror_num)
371 {
372         struct btrfs_root *root = BTRFS_I(inode)->root;
373         int ret = 0;
374
375         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
376         BUG_ON(ret);
377
378         if (!(rw & (1 << BIO_RW))) {
379                 goto mapit;
380         }
381
382         return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
383                                    inode, rw, bio, mirror_num,
384                                    __btrfs_submit_bio_hook);
385 mapit:
386         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
387 }
388
389 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
390                              struct inode *inode, u64 file_offset,
391                              struct list_head *list)
392 {
393         struct list_head *cur;
394         struct btrfs_ordered_sum *sum;
395
396         btrfs_set_trans_block_group(trans, inode);
397         list_for_each(cur, list) {
398                 sum = list_entry(cur, struct btrfs_ordered_sum, list);
399                 mutex_lock(&BTRFS_I(inode)->csum_mutex);
400                 btrfs_csum_file_blocks(trans, BTRFS_I(inode)->root,
401                                        inode, sum);
402                 mutex_unlock(&BTRFS_I(inode)->csum_mutex);
403         }
404         return 0;
405 }
406
407 struct btrfs_writepage_fixup {
408         struct page *page;
409         struct btrfs_work work;
410 };
411
412 /* see btrfs_writepage_start_hook for details on why this is required */
413 void btrfs_writepage_fixup_worker(struct btrfs_work *work)
414 {
415         struct btrfs_writepage_fixup *fixup;
416         struct btrfs_ordered_extent *ordered;
417         struct page *page;
418         struct inode *inode;
419         u64 page_start;
420         u64 page_end;
421
422         fixup = container_of(work, struct btrfs_writepage_fixup, work);
423         page = fixup->page;
424 again:
425         lock_page(page);
426         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
427                 ClearPageChecked(page);
428                 goto out_page;
429         }
430
431         inode = page->mapping->host;
432         page_start = page_offset(page);
433         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
434
435         lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
436
437         /* already ordered? We're done */
438         if (test_range_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
439                              EXTENT_ORDERED, 0)) {
440                 goto out;
441         }
442
443         ordered = btrfs_lookup_ordered_extent(inode, page_start);
444         if (ordered) {
445                 unlock_extent(&BTRFS_I(inode)->io_tree, page_start,
446                               page_end, GFP_NOFS);
447                 unlock_page(page);
448                 btrfs_start_ordered_extent(inode, ordered, 1);
449                 goto again;
450         }
451
452         set_extent_delalloc(&BTRFS_I(inode)->io_tree, page_start, page_end,
453                             GFP_NOFS);
454         ClearPageChecked(page);
455 out:
456         unlock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
457 out_page:
458         unlock_page(page);
459         page_cache_release(page);
460 }
461
462 /*
463  * There are a few paths in the higher layers of the kernel that directly
464  * set the page dirty bit without asking the filesystem if it is a
465  * good idea.  This causes problems because we want to make sure COW
466  * properly happens and the data=ordered rules are followed.
467  *
468  * In our case any range that doesn't have the EXTENT_ORDERED bit set
469  * hasn't been properly setup for IO.  We kick off an async process
470  * to fix it up.  The async helper will wait for ordered extents, set
471  * the delalloc bit and make it safe to write the page.
472  */
473 int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
474 {
475         struct inode *inode = page->mapping->host;
476         struct btrfs_writepage_fixup *fixup;
477         struct btrfs_root *root = BTRFS_I(inode)->root;
478         int ret;
479
480         ret = test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
481                              EXTENT_ORDERED, 0);
482         if (ret)
483                 return 0;
484
485         if (PageChecked(page))
486                 return -EAGAIN;
487
488         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
489         if (!fixup)
490                 return -EAGAIN;
491
492         SetPageChecked(page);
493         page_cache_get(page);
494         fixup->work.func = btrfs_writepage_fixup_worker;
495         fixup->page = page;
496         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
497         return -EAGAIN;
498 }
499
500 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
501 {
502         struct btrfs_root *root = BTRFS_I(inode)->root;
503         struct btrfs_trans_handle *trans;
504         struct btrfs_ordered_extent *ordered_extent;
505         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
506         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
507         struct extent_map *em;
508         struct extent_map *em_orig;
509         u64 alloc_hint = 0;
510         u64 clear_start;
511         u64 clear_end;
512         struct list_head list;
513         struct btrfs_key ins;
514         struct rb_node *rb;
515         int ret;
516
517         ret = btrfs_dec_test_ordered_pending(inode, start, end - start + 1);
518         if (!ret)
519                 return 0;
520
521         trans = btrfs_join_transaction(root, 1);
522
523         ordered_extent = btrfs_lookup_ordered_extent(inode, start);
524         BUG_ON(!ordered_extent);
525
526         lock_extent(io_tree, ordered_extent->file_offset,
527                     ordered_extent->file_offset + ordered_extent->len - 1,
528                     GFP_NOFS);
529
530         INIT_LIST_HEAD(&list);
531
532         ins.objectid = ordered_extent->start;
533         ins.offset = ordered_extent->len;
534         ins.type = BTRFS_EXTENT_ITEM_KEY;
535
536         ret = btrfs_alloc_reserved_extent(trans, root, root->root_key.objectid,
537                                           trans->transid, inode->i_ino,
538                                           ordered_extent->file_offset, &ins);
539         BUG_ON(ret);
540
541         mutex_lock(&BTRFS_I(inode)->extent_mutex);
542
543         spin_lock(&em_tree->lock);
544         clear_start = ordered_extent->file_offset;
545         clear_end = ordered_extent->file_offset + ordered_extent->len;
546         em = lookup_extent_mapping(em_tree, clear_start,
547                                    ordered_extent->len);
548         em_orig = em;
549         while(em && clear_start < extent_map_end(em) && clear_end > em->start) {
550                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
551                 rb = rb_next(&em->rb_node);
552                 if (!rb)
553                         break;
554                 em = rb_entry(rb, struct extent_map, rb_node);
555         }
556         free_extent_map(em_orig);
557         spin_unlock(&em_tree->lock);
558
559         ret = btrfs_drop_extents(trans, root, inode,
560                                  ordered_extent->file_offset,
561                                  ordered_extent->file_offset +
562                                  ordered_extent->len,
563                                  ordered_extent->file_offset, &alloc_hint);
564         BUG_ON(ret);
565         ret = btrfs_insert_file_extent(trans, root, inode->i_ino,
566                                        ordered_extent->file_offset,
567                                        ordered_extent->start,
568                                        ordered_extent->len,
569                                        ordered_extent->len, 0);
570         BUG_ON(ret);
571
572         btrfs_drop_extent_cache(inode, ordered_extent->file_offset,
573                                 ordered_extent->file_offset +
574                                 ordered_extent->len - 1);
575         mutex_unlock(&BTRFS_I(inode)->extent_mutex);
576
577         inode->i_blocks += ordered_extent->len >> 9;
578         unlock_extent(io_tree, ordered_extent->file_offset,
579                     ordered_extent->file_offset + ordered_extent->len - 1,
580                     GFP_NOFS);
581         add_pending_csums(trans, inode, ordered_extent->file_offset,
582                           &ordered_extent->list);
583
584         btrfs_ordered_update_i_size(inode, ordered_extent);
585         btrfs_remove_ordered_extent(inode, ordered_extent);
586
587         /* once for us */
588         btrfs_put_ordered_extent(ordered_extent);
589         /* once for the tree */
590         btrfs_put_ordered_extent(ordered_extent);
591
592         btrfs_update_inode(trans, root, inode);
593         btrfs_end_transaction(trans, root);
594         return 0;
595 }
596
597 int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
598                                 struct extent_state *state, int uptodate)
599 {
600         return btrfs_finish_ordered_io(page->mapping->host, start, end);
601 }
602
603 int btrfs_readpage_io_hook(struct page *page, u64 start, u64 end)
604 {
605         int ret = 0;
606         struct inode *inode = page->mapping->host;
607         struct btrfs_root *root = BTRFS_I(inode)->root;
608         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
609         struct btrfs_csum_item *item;
610         struct btrfs_path *path = NULL;
611         u32 csum;
612
613         if (btrfs_test_opt(root, NODATASUM) ||
614             btrfs_test_flag(inode, NODATASUM))
615                 return 0;
616
617         /*
618          * It is possible there is an ordered extent that has
619          * not yet finished for this range in the file.  If so,
620          * that extent will have a csum cached, and it will insert
621          * the sum after all the blocks in the extent are fully
622          * on disk.  So, look for an ordered extent and use the
623          * sum if found.  We have to do this before looking in the
624          * btree because csum items are pre-inserted based on
625          * the file size.  btrfs_lookup_csum might find an item
626          * that still hasn't been fully filled.
627          */
628         ret = btrfs_find_ordered_sum(inode, start, &csum);
629         if (ret == 0)
630                 goto found;
631
632         ret = 0;
633         path = btrfs_alloc_path();
634         item = btrfs_lookup_csum(NULL, root, path, inode->i_ino, start, 0);
635         if (IS_ERR(item)) {
636                 ret = PTR_ERR(item);
637                 /* a csum that isn't present is a preallocated region. */
638                 if (ret == -ENOENT || ret == -EFBIG)
639                         ret = 0;
640                 csum = 0;
641                 printk("no csum found for inode %lu start %Lu\n", inode->i_ino,
642                        start);
643                 goto out;
644         }
645         read_extent_buffer(path->nodes[0], &csum, (unsigned long)item,
646                            BTRFS_CRC32_SIZE);
647 found:
648         set_state_private(io_tree, start, csum);
649 out:
650         if (path)
651                 btrfs_free_path(path);
652         return ret;
653 }
654
655 struct io_failure_record {
656         struct page *page;
657         u64 start;
658         u64 len;
659         u64 logical;
660         int last_mirror;
661 };
662
663 int btrfs_io_failed_hook(struct bio *failed_bio,
664                          struct page *page, u64 start, u64 end,
665                          struct extent_state *state)
666 {
667         struct io_failure_record *failrec = NULL;
668         u64 private;
669         struct extent_map *em;
670         struct inode *inode = page->mapping->host;
671         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
672         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
673         struct bio *bio;
674         int num_copies;
675         int ret;
676         int rw;
677         u64 logical;
678
679         ret = get_state_private(failure_tree, start, &private);
680         if (ret) {
681                 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
682                 if (!failrec)
683                         return -ENOMEM;
684                 failrec->start = start;
685                 failrec->len = end - start + 1;
686                 failrec->last_mirror = 0;
687
688                 spin_lock(&em_tree->lock);
689                 em = lookup_extent_mapping(em_tree, start, failrec->len);
690                 if (em->start > start || em->start + em->len < start) {
691                         free_extent_map(em);
692                         em = NULL;
693                 }
694                 spin_unlock(&em_tree->lock);
695
696                 if (!em || IS_ERR(em)) {
697                         kfree(failrec);
698                         return -EIO;
699                 }
700                 logical = start - em->start;
701                 logical = em->block_start + logical;
702                 failrec->logical = logical;
703                 free_extent_map(em);
704                 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
705                                 EXTENT_DIRTY, GFP_NOFS);
706                 set_state_private(failure_tree, start,
707                                  (u64)(unsigned long)failrec);
708         } else {
709                 failrec = (struct io_failure_record *)(unsigned long)private;
710         }
711         num_copies = btrfs_num_copies(
712                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
713                               failrec->logical, failrec->len);
714         failrec->last_mirror++;
715         if (!state) {
716                 spin_lock_irq(&BTRFS_I(inode)->io_tree.lock);
717                 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
718                                                     failrec->start,
719                                                     EXTENT_LOCKED);
720                 if (state && state->start != failrec->start)
721                         state = NULL;
722                 spin_unlock_irq(&BTRFS_I(inode)->io_tree.lock);
723         }
724         if (!state || failrec->last_mirror > num_copies) {
725                 set_state_private(failure_tree, failrec->start, 0);
726                 clear_extent_bits(failure_tree, failrec->start,
727                                   failrec->start + failrec->len - 1,
728                                   EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
729                 kfree(failrec);
730                 return -EIO;
731         }
732         bio = bio_alloc(GFP_NOFS, 1);
733         bio->bi_private = state;
734         bio->bi_end_io = failed_bio->bi_end_io;
735         bio->bi_sector = failrec->logical >> 9;
736         bio->bi_bdev = failed_bio->bi_bdev;
737         bio->bi_size = 0;
738         bio_add_page(bio, page, failrec->len, start - page_offset(page));
739         if (failed_bio->bi_rw & (1 << BIO_RW))
740                 rw = WRITE;
741         else
742                 rw = READ;
743
744         BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
745                                                       failrec->last_mirror);
746         return 0;
747 }
748
749 int btrfs_clean_io_failures(struct inode *inode, u64 start)
750 {
751         u64 private;
752         u64 private_failure;
753         struct io_failure_record *failure;
754         int ret;
755
756         private = 0;
757         if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
758                              (u64)-1, 1, EXTENT_DIRTY)) {
759                 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
760                                         start, &private_failure);
761                 if (ret == 0) {
762                         failure = (struct io_failure_record *)(unsigned long)
763                                    private_failure;
764                         set_state_private(&BTRFS_I(inode)->io_failure_tree,
765                                           failure->start, 0);
766                         clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
767                                           failure->start,
768                                           failure->start + failure->len - 1,
769                                           EXTENT_DIRTY | EXTENT_LOCKED,
770                                           GFP_NOFS);
771                         kfree(failure);
772                 }
773         }
774         return 0;
775 }
776
777 int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
778                                struct extent_state *state)
779 {
780         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
781         struct inode *inode = page->mapping->host;
782         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
783         char *kaddr;
784         u64 private = ~(u32)0;
785         int ret;
786         struct btrfs_root *root = BTRFS_I(inode)->root;
787         u32 csum = ~(u32)0;
788         unsigned long flags;
789
790         if (btrfs_test_opt(root, NODATASUM) ||
791             btrfs_test_flag(inode, NODATASUM))
792                 return 0;
793         if (state && state->start == start) {
794                 private = state->private;
795                 ret = 0;
796         } else {
797                 ret = get_state_private(io_tree, start, &private);
798         }
799         local_irq_save(flags);
800         kaddr = kmap_atomic(page, KM_IRQ0);
801         if (ret) {
802                 goto zeroit;
803         }
804         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
805         btrfs_csum_final(csum, (char *)&csum);
806         if (csum != private) {
807                 goto zeroit;
808         }
809         kunmap_atomic(kaddr, KM_IRQ0);
810         local_irq_restore(flags);
811
812         /* if the io failure tree for this inode is non-empty,
813          * check to see if we've recovered from a failed IO
814          */
815         btrfs_clean_io_failures(inode, start);
816         return 0;
817
818 zeroit:
819         printk("btrfs csum failed ino %lu off %llu csum %u private %Lu\n",
820                page->mapping->host->i_ino, (unsigned long long)start, csum,
821                private);
822         memset(kaddr + offset, 1, end - start + 1);
823         flush_dcache_page(page);
824         kunmap_atomic(kaddr, KM_IRQ0);
825         local_irq_restore(flags);
826         if (private == 0)
827                 return 0;
828         return -EIO;
829 }
830
831 /*
832  * This creates an orphan entry for the given inode in case something goes
833  * wrong in the middle of an unlink/truncate.
834  */
835 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
836 {
837         struct btrfs_root *root = BTRFS_I(inode)->root;
838         int ret = 0;
839
840         spin_lock(&root->orphan_lock);
841
842         /* already on the orphan list, we're good */
843         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
844                 spin_unlock(&root->orphan_lock);
845                 return 0;
846         }
847
848         list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
849
850         spin_unlock(&root->orphan_lock);
851
852         /*
853          * insert an orphan item to track this unlinked/truncated file
854          */
855         ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
856
857         return ret;
858 }
859
860 /*
861  * We have done the truncate/delete so we can go ahead and remove the orphan
862  * item for this particular inode.
863  */
864 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
865 {
866         struct btrfs_root *root = BTRFS_I(inode)->root;
867         int ret = 0;
868
869         spin_lock(&root->orphan_lock);
870
871         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
872                 spin_unlock(&root->orphan_lock);
873                 return 0;
874         }
875
876         list_del_init(&BTRFS_I(inode)->i_orphan);
877         if (!trans) {
878                 spin_unlock(&root->orphan_lock);
879                 return 0;
880         }
881
882         spin_unlock(&root->orphan_lock);
883
884         ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
885
886         return ret;
887 }
888
889 /*
890  * this cleans up any orphans that may be left on the list from the last use
891  * of this root.
892  */
893 void btrfs_orphan_cleanup(struct btrfs_root *root)
894 {
895         struct btrfs_path *path;
896         struct extent_buffer *leaf;
897         struct btrfs_item *item;
898         struct btrfs_key key, found_key;
899         struct btrfs_trans_handle *trans;
900         struct inode *inode;
901         int ret = 0, nr_unlink = 0, nr_truncate = 0;
902
903         /* don't do orphan cleanup if the fs is readonly. */
904         if (root->inode->i_sb->s_flags & MS_RDONLY)
905                 return;
906
907         path = btrfs_alloc_path();
908         if (!path)
909                 return;
910         path->reada = -1;
911
912         key.objectid = BTRFS_ORPHAN_OBJECTID;
913         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
914         key.offset = (u64)-1;
915
916         trans = btrfs_start_transaction(root, 1);
917         btrfs_set_trans_block_group(trans, root->inode);
918
919         while (1) {
920                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
921                 if (ret < 0) {
922                         printk(KERN_ERR "Error searching slot for orphan: %d"
923                                "\n", ret);
924                         break;
925                 }
926
927                 /*
928                  * if ret == 0 means we found what we were searching for, which
929                  * is weird, but possible, so only screw with path if we didnt
930                  * find the key and see if we have stuff that matches
931                  */
932                 if (ret > 0) {
933                         if (path->slots[0] == 0)
934                                 break;
935                         path->slots[0]--;
936                 }
937
938                 /* pull out the item */
939                 leaf = path->nodes[0];
940                 item = btrfs_item_nr(leaf, path->slots[0]);
941                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
942
943                 /* make sure the item matches what we want */
944                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
945                         break;
946                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
947                         break;
948
949                 /* release the path since we're done with it */
950                 btrfs_release_path(root, path);
951
952                 /*
953                  * this is where we are basically btrfs_lookup, without the
954                  * crossing root thing.  we store the inode number in the
955                  * offset of the orphan item.
956                  */
957                 inode = btrfs_iget_locked(root->inode->i_sb,
958                                           found_key.offset, root);
959                 if (!inode)
960                         break;
961
962                 if (inode->i_state & I_NEW) {
963                         BTRFS_I(inode)->root = root;
964
965                         /* have to set the location manually */
966                         BTRFS_I(inode)->location.objectid = inode->i_ino;
967                         BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
968                         BTRFS_I(inode)->location.offset = 0;
969
970                         btrfs_read_locked_inode(inode);
971                         unlock_new_inode(inode);
972                 }
973
974                 /*
975                  * add this inode to the orphan list so btrfs_orphan_del does
976                  * the proper thing when we hit it
977                  */
978                 spin_lock(&root->orphan_lock);
979                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
980                 spin_unlock(&root->orphan_lock);
981
982                 /*
983                  * if this is a bad inode, means we actually succeeded in
984                  * removing the inode, but not the orphan record, which means
985                  * we need to manually delete the orphan since iput will just
986                  * do a destroy_inode
987                  */
988                 if (is_bad_inode(inode)) {
989                         btrfs_orphan_del(trans, inode);
990                         iput(inode);
991                         continue;
992                 }
993
994                 /* if we have links, this was a truncate, lets do that */
995                 if (inode->i_nlink) {
996                         nr_truncate++;
997                         btrfs_truncate(inode);
998                 } else {
999                         nr_unlink++;
1000                 }
1001
1002                 /* this will do delete_inode and everything for us */
1003                 iput(inode);
1004         }
1005
1006         if (nr_unlink)
1007                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
1008         if (nr_truncate)
1009                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
1010
1011         btrfs_free_path(path);
1012         btrfs_end_transaction(trans, root);
1013 }
1014
1015 void btrfs_read_locked_inode(struct inode *inode)
1016 {
1017         struct btrfs_path *path;
1018         struct extent_buffer *leaf;
1019         struct btrfs_inode_item *inode_item;
1020         struct btrfs_timespec *tspec;
1021         struct btrfs_root *root = BTRFS_I(inode)->root;
1022         struct btrfs_key location;
1023         u64 alloc_group_block;
1024         u32 rdev;
1025         int ret;
1026
1027         path = btrfs_alloc_path();
1028         BUG_ON(!path);
1029         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
1030
1031         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
1032         if (ret)
1033                 goto make_bad;
1034
1035         leaf = path->nodes[0];
1036         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1037                                     struct btrfs_inode_item);
1038
1039         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
1040         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
1041         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
1042         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
1043         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
1044
1045         tspec = btrfs_inode_atime(inode_item);
1046         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1047         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1048
1049         tspec = btrfs_inode_mtime(inode_item);
1050         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1051         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1052
1053         tspec = btrfs_inode_ctime(inode_item);
1054         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1055         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1056
1057         inode->i_blocks = btrfs_inode_nblocks(leaf, inode_item);
1058         inode->i_generation = btrfs_inode_generation(leaf, inode_item);
1059         inode->i_rdev = 0;
1060         rdev = btrfs_inode_rdev(leaf, inode_item);
1061
1062         BTRFS_I(inode)->index_cnt = (u64)-1;
1063
1064         alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
1065         BTRFS_I(inode)->block_group = btrfs_lookup_block_group(root->fs_info,
1066                                                        alloc_group_block);
1067         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
1068         if (!BTRFS_I(inode)->block_group) {
1069                 BTRFS_I(inode)->block_group = btrfs_find_block_group(root,
1070                                                  NULL, 0,
1071                                                  BTRFS_BLOCK_GROUP_METADATA, 0);
1072         }
1073         btrfs_free_path(path);
1074         inode_item = NULL;
1075
1076         switch (inode->i_mode & S_IFMT) {
1077         case S_IFREG:
1078                 inode->i_mapping->a_ops = &btrfs_aops;
1079                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
1080                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
1081                 inode->i_fop = &btrfs_file_operations;
1082                 inode->i_op = &btrfs_file_inode_operations;
1083                 break;
1084         case S_IFDIR:
1085                 inode->i_fop = &btrfs_dir_file_operations;
1086                 if (root == root->fs_info->tree_root)
1087                         inode->i_op = &btrfs_dir_ro_inode_operations;
1088                 else
1089                         inode->i_op = &btrfs_dir_inode_operations;
1090                 break;
1091         case S_IFLNK:
1092                 inode->i_op = &btrfs_symlink_inode_operations;
1093                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
1094                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
1095                 break;
1096         default:
1097                 init_special_inode(inode, inode->i_mode, rdev);
1098                 break;
1099         }
1100         return;
1101
1102 make_bad:
1103         btrfs_free_path(path);
1104         make_bad_inode(inode);
1105 }
1106
1107 static void fill_inode_item(struct extent_buffer *leaf,
1108                             struct btrfs_inode_item *item,
1109                             struct inode *inode)
1110 {
1111         btrfs_set_inode_uid(leaf, item, inode->i_uid);
1112         btrfs_set_inode_gid(leaf, item, inode->i_gid);
1113         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
1114         btrfs_set_inode_mode(leaf, item, inode->i_mode);
1115         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
1116
1117         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
1118                                inode->i_atime.tv_sec);
1119         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
1120                                 inode->i_atime.tv_nsec);
1121
1122         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
1123                                inode->i_mtime.tv_sec);
1124         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
1125                                 inode->i_mtime.tv_nsec);
1126
1127         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
1128                                inode->i_ctime.tv_sec);
1129         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
1130                                 inode->i_ctime.tv_nsec);
1131
1132         btrfs_set_inode_nblocks(leaf, item, inode->i_blocks);
1133         btrfs_set_inode_generation(leaf, item, inode->i_generation);
1134         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
1135         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
1136         btrfs_set_inode_block_group(leaf, item,
1137                                     BTRFS_I(inode)->block_group->key.objectid);
1138 }
1139
1140 int noinline btrfs_update_inode(struct btrfs_trans_handle *trans,
1141                               struct btrfs_root *root,
1142                               struct inode *inode)
1143 {
1144         struct btrfs_inode_item *inode_item;
1145         struct btrfs_path *path;
1146         struct extent_buffer *leaf;
1147         int ret;
1148
1149         path = btrfs_alloc_path();
1150         BUG_ON(!path);
1151         ret = btrfs_lookup_inode(trans, root, path,
1152                                  &BTRFS_I(inode)->location, 1);
1153         if (ret) {
1154                 if (ret > 0)
1155                         ret = -ENOENT;
1156                 goto failed;
1157         }
1158
1159         leaf = path->nodes[0];
1160         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1161                                   struct btrfs_inode_item);
1162
1163         fill_inode_item(leaf, inode_item, inode);
1164         btrfs_mark_buffer_dirty(leaf);
1165         btrfs_set_inode_last_trans(trans, inode);
1166         ret = 0;
1167 failed:
1168         btrfs_free_path(path);
1169         return ret;
1170 }
1171
1172
1173 static int btrfs_unlink_trans(struct btrfs_trans_handle *trans,
1174                               struct btrfs_root *root,
1175                               struct inode *dir,
1176                               struct dentry *dentry)
1177 {
1178         struct btrfs_path *path;
1179         const char *name = dentry->d_name.name;
1180         int name_len = dentry->d_name.len;
1181         int ret = 0;
1182         struct extent_buffer *leaf;
1183         struct btrfs_dir_item *di;
1184         struct btrfs_key key;
1185         u64 index;
1186
1187         path = btrfs_alloc_path();
1188         if (!path) {
1189                 ret = -ENOMEM;
1190                 goto err;
1191         }
1192
1193         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
1194                                     name, name_len, -1);
1195         if (IS_ERR(di)) {
1196                 ret = PTR_ERR(di);
1197                 goto err;
1198         }
1199         if (!di) {
1200                 ret = -ENOENT;
1201                 goto err;
1202         }
1203         leaf = path->nodes[0];
1204         btrfs_dir_item_key_to_cpu(leaf, di, &key);
1205         ret = btrfs_delete_one_dir_name(trans, root, path, di);
1206         if (ret)
1207                 goto err;
1208         btrfs_release_path(root, path);
1209
1210         ret = btrfs_del_inode_ref(trans, root, name, name_len,
1211                                   dentry->d_inode->i_ino,
1212                                   dentry->d_parent->d_inode->i_ino, &index);
1213         if (ret) {
1214                 printk("failed to delete reference to %.*s, "
1215                        "inode %lu parent %lu\n", name_len, name,
1216                        dentry->d_inode->i_ino,
1217                        dentry->d_parent->d_inode->i_ino);
1218                 goto err;
1219         }
1220
1221         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
1222                                          index, name, name_len, -1);
1223         if (IS_ERR(di)) {
1224                 ret = PTR_ERR(di);
1225                 goto err;
1226         }
1227         if (!di) {
1228                 ret = -ENOENT;
1229                 goto err;
1230         }
1231         ret = btrfs_delete_one_dir_name(trans, root, path, di);
1232         btrfs_release_path(root, path);
1233
1234         dentry->d_inode->i_ctime = dir->i_ctime;
1235 err:
1236         btrfs_free_path(path);
1237         if (!ret) {
1238                 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
1239                 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
1240                 btrfs_update_inode(trans, root, dir);
1241 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
1242                 dentry->d_inode->i_nlink--;
1243 #else
1244                 drop_nlink(dentry->d_inode);
1245 #endif
1246                 ret = btrfs_update_inode(trans, root, dentry->d_inode);
1247                 dir->i_sb->s_dirt = 1;
1248         }
1249         return ret;
1250 }
1251
1252 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
1253 {
1254         struct btrfs_root *root;
1255         struct btrfs_trans_handle *trans;
1256         struct inode *inode = dentry->d_inode;
1257         int ret;
1258         unsigned long nr = 0;
1259
1260         root = BTRFS_I(dir)->root;
1261
1262         ret = btrfs_check_free_space(root, 1, 1);
1263         if (ret)
1264                 goto fail;
1265
1266         trans = btrfs_start_transaction(root, 1);
1267
1268         btrfs_set_trans_block_group(trans, dir);
1269         ret = btrfs_unlink_trans(trans, root, dir, dentry);
1270
1271         if (inode->i_nlink == 0)
1272                 ret = btrfs_orphan_add(trans, inode);
1273
1274         nr = trans->blocks_used;
1275
1276         btrfs_end_transaction_throttle(trans, root);
1277 fail:
1278         btrfs_btree_balance_dirty(root, nr);
1279         return ret;
1280 }
1281
1282 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
1283 {
1284         struct inode *inode = dentry->d_inode;
1285         int err = 0;
1286         int ret;
1287         struct btrfs_root *root = BTRFS_I(dir)->root;
1288         struct btrfs_trans_handle *trans;
1289         unsigned long nr = 0;
1290
1291         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
1292                 return -ENOTEMPTY;
1293         }
1294
1295         ret = btrfs_check_free_space(root, 1, 1);
1296         if (ret)
1297                 goto fail;
1298
1299         trans = btrfs_start_transaction(root, 1);
1300         btrfs_set_trans_block_group(trans, dir);
1301
1302         err = btrfs_orphan_add(trans, inode);
1303         if (err)
1304                 goto fail_trans;
1305
1306         /* now the directory is empty */
1307         err = btrfs_unlink_trans(trans, root, dir, dentry);
1308         if (!err) {
1309                 btrfs_i_size_write(inode, 0);
1310         }
1311
1312 fail_trans:
1313         nr = trans->blocks_used;
1314         ret = btrfs_end_transaction_throttle(trans, root);
1315 fail:
1316         btrfs_btree_balance_dirty(root, nr);
1317
1318         if (ret && !err)
1319                 err = ret;
1320         return err;
1321 }
1322
1323 /*
1324  * this can truncate away extent items, csum items and directory items.
1325  * It starts at a high offset and removes keys until it can't find
1326  * any higher than i_size.
1327  *
1328  * csum items that cross the new i_size are truncated to the new size
1329  * as well.
1330  *
1331  * min_type is the minimum key type to truncate down to.  If set to 0, this
1332  * will kill all the items on this inode, including the INODE_ITEM_KEY.
1333  */
1334 static int btrfs_truncate_in_trans(struct btrfs_trans_handle *trans,
1335                                    struct btrfs_root *root,
1336                                    struct inode *inode,
1337                                    u32 min_type)
1338 {
1339         int ret;
1340         struct btrfs_path *path;
1341         struct btrfs_key key;
1342         struct btrfs_key found_key;
1343         u32 found_type;
1344         struct extent_buffer *leaf;
1345         struct btrfs_file_extent_item *fi;
1346         u64 extent_start = 0;
1347         u64 extent_num_bytes = 0;
1348         u64 item_end = 0;
1349         u64 root_gen = 0;
1350         u64 root_owner = 0;
1351         int found_extent;
1352         int del_item;
1353         int pending_del_nr = 0;
1354         int pending_del_slot = 0;
1355         int extent_type = -1;
1356         u64 mask = root->sectorsize - 1;
1357
1358         btrfs_drop_extent_cache(inode, inode->i_size & (~mask), (u64)-1);
1359         path = btrfs_alloc_path();
1360         path->reada = -1;
1361         BUG_ON(!path);
1362
1363         /* FIXME, add redo link to tree so we don't leak on crash */
1364         key.objectid = inode->i_ino;
1365         key.offset = (u64)-1;
1366         key.type = (u8)-1;
1367
1368         btrfs_init_path(path);
1369 search_again:
1370         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1371         if (ret < 0) {
1372                 goto error;
1373         }
1374         if (ret > 0) {
1375                 BUG_ON(path->slots[0] == 0);
1376                 path->slots[0]--;
1377         }
1378
1379         while(1) {
1380                 fi = NULL;
1381                 leaf = path->nodes[0];
1382                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1383                 found_type = btrfs_key_type(&found_key);
1384
1385                 if (found_key.objectid != inode->i_ino)
1386                         break;
1387
1388                 if (found_type < min_type)
1389                         break;
1390
1391                 item_end = found_key.offset;
1392                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
1393                         fi = btrfs_item_ptr(leaf, path->slots[0],
1394                                             struct btrfs_file_extent_item);
1395                         extent_type = btrfs_file_extent_type(leaf, fi);
1396                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
1397                                 item_end +=
1398                                     btrfs_file_extent_num_bytes(leaf, fi);
1399                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1400                                 struct btrfs_item *item = btrfs_item_nr(leaf,
1401                                                                 path->slots[0]);
1402                                 item_end += btrfs_file_extent_inline_len(leaf,
1403                                                                          item);
1404                         }
1405                         item_end--;
1406                 }
1407                 if (found_type == BTRFS_CSUM_ITEM_KEY) {
1408                         ret = btrfs_csum_truncate(trans, root, path,
1409                                                   inode->i_size);
1410                         BUG_ON(ret);
1411                 }
1412                 if (item_end < inode->i_size) {
1413                         if (found_type == BTRFS_DIR_ITEM_KEY) {
1414                                 found_type = BTRFS_INODE_ITEM_KEY;
1415                         } else if (found_type == BTRFS_EXTENT_ITEM_KEY) {
1416                                 found_type = BTRFS_CSUM_ITEM_KEY;
1417                         } else if (found_type == BTRFS_EXTENT_DATA_KEY) {
1418                                 found_type = BTRFS_XATTR_ITEM_KEY;
1419                         } else if (found_type == BTRFS_XATTR_ITEM_KEY) {
1420                                 found_type = BTRFS_INODE_REF_KEY;
1421                         } else if (found_type) {
1422                                 found_type--;
1423                         } else {
1424                                 break;
1425                         }
1426                         btrfs_set_key_type(&key, found_type);
1427                         goto next;
1428                 }
1429                 if (found_key.offset >= inode->i_size)
1430                         del_item = 1;
1431                 else
1432                         del_item = 0;
1433                 found_extent = 0;
1434
1435                 /* FIXME, shrink the extent if the ref count is only 1 */
1436                 if (found_type != BTRFS_EXTENT_DATA_KEY)
1437                         goto delete;
1438
1439                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
1440                         u64 num_dec;
1441                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
1442                         if (!del_item) {
1443                                 u64 orig_num_bytes =
1444                                         btrfs_file_extent_num_bytes(leaf, fi);
1445                                 extent_num_bytes = inode->i_size -
1446                                         found_key.offset + root->sectorsize - 1;
1447                                 extent_num_bytes = extent_num_bytes &
1448                                         ~((u64)root->sectorsize - 1);
1449                                 btrfs_set_file_extent_num_bytes(leaf, fi,
1450                                                          extent_num_bytes);
1451                                 num_dec = (orig_num_bytes -
1452                                            extent_num_bytes);
1453                                 if (extent_start != 0)
1454                                         dec_i_blocks(inode, num_dec);
1455                                 btrfs_mark_buffer_dirty(leaf);
1456                         } else {
1457                                 extent_num_bytes =
1458                                         btrfs_file_extent_disk_num_bytes(leaf,
1459                                                                          fi);
1460                                 /* FIXME blocksize != 4096 */
1461                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
1462                                 if (extent_start != 0) {
1463                                         found_extent = 1;
1464                                         dec_i_blocks(inode, num_dec);
1465                                 }
1466                                 root_gen = btrfs_header_generation(leaf);
1467                                 root_owner = btrfs_header_owner(leaf);
1468                         }
1469                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1470                         if (!del_item) {
1471                                 u32 newsize = inode->i_size - found_key.offset;
1472                                 dec_i_blocks(inode, item_end + 1 -
1473                                             found_key.offset - newsize);
1474                                 newsize =
1475                                     btrfs_file_extent_calc_inline_size(newsize);
1476                                 ret = btrfs_truncate_item(trans, root, path,
1477                                                           newsize, 1);
1478                                 BUG_ON(ret);
1479                         } else {
1480                                 dec_i_blocks(inode, item_end + 1 -
1481                                              found_key.offset);
1482                         }
1483                 }
1484 delete:
1485                 if (del_item) {
1486                         if (!pending_del_nr) {
1487                                 /* no pending yet, add ourselves */
1488                                 pending_del_slot = path->slots[0];
1489                                 pending_del_nr = 1;
1490                         } else if (pending_del_nr &&
1491                                    path->slots[0] + 1 == pending_del_slot) {
1492                                 /* hop on the pending chunk */
1493                                 pending_del_nr++;
1494                                 pending_del_slot = path->slots[0];
1495                         } else {
1496                                 printk("bad pending slot %d pending_del_nr %d pending_del_slot %d\n", path->slots[0], pending_del_nr, pending_del_slot);
1497                         }
1498                 } else {
1499                         break;
1500                 }
1501                 if (found_extent) {
1502                         ret = btrfs_free_extent(trans, root, extent_start,
1503                                                 extent_num_bytes,
1504                                                 root_owner,
1505                                                 root_gen, inode->i_ino,
1506                                                 found_key.offset, 0);
1507                         BUG_ON(ret);
1508                 }
1509 next:
1510                 if (path->slots[0] == 0) {
1511                         if (pending_del_nr)
1512                                 goto del_pending;
1513                         btrfs_release_path(root, path);
1514                         goto search_again;
1515                 }
1516
1517                 path->slots[0]--;
1518                 if (pending_del_nr &&
1519                     path->slots[0] + 1 != pending_del_slot) {
1520                         struct btrfs_key debug;
1521 del_pending:
1522                         btrfs_item_key_to_cpu(path->nodes[0], &debug,
1523                                               pending_del_slot);
1524                         ret = btrfs_del_items(trans, root, path,
1525                                               pending_del_slot,
1526                                               pending_del_nr);
1527                         BUG_ON(ret);
1528                         pending_del_nr = 0;
1529                         btrfs_release_path(root, path);
1530                         goto search_again;
1531                 }
1532         }
1533         ret = 0;
1534 error:
1535         if (pending_del_nr) {
1536                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
1537                                       pending_del_nr);
1538         }
1539         btrfs_free_path(path);
1540         inode->i_sb->s_dirt = 1;
1541         return ret;
1542 }
1543
1544 /*
1545  * taken from block_truncate_page, but does cow as it zeros out
1546  * any bytes left in the last page in the file.
1547  */
1548 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
1549 {
1550         struct inode *inode = mapping->host;
1551         struct btrfs_root *root = BTRFS_I(inode)->root;
1552         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1553         struct btrfs_ordered_extent *ordered;
1554         char *kaddr;
1555         u32 blocksize = root->sectorsize;
1556         pgoff_t index = from >> PAGE_CACHE_SHIFT;
1557         unsigned offset = from & (PAGE_CACHE_SIZE-1);
1558         struct page *page;
1559         int ret = 0;
1560         u64 page_start;
1561         u64 page_end;
1562
1563         if ((offset & (blocksize - 1)) == 0)
1564                 goto out;
1565
1566         ret = -ENOMEM;
1567 again:
1568         page = grab_cache_page(mapping, index);
1569         if (!page)
1570                 goto out;
1571
1572         page_start = page_offset(page);
1573         page_end = page_start + PAGE_CACHE_SIZE - 1;
1574
1575         if (!PageUptodate(page)) {
1576                 ret = btrfs_readpage(NULL, page);
1577                 lock_page(page);
1578                 if (page->mapping != mapping) {
1579                         unlock_page(page);
1580                         page_cache_release(page);
1581                         goto again;
1582                 }
1583                 if (!PageUptodate(page)) {
1584                         ret = -EIO;
1585                         goto out_unlock;
1586                 }
1587         }
1588         wait_on_page_writeback(page);
1589
1590         lock_extent(io_tree, page_start, page_end, GFP_NOFS);
1591         set_page_extent_mapped(page);
1592
1593         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1594         if (ordered) {
1595                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
1596                 unlock_page(page);
1597                 page_cache_release(page);
1598                 btrfs_start_ordered_extent(inode, ordered, 1);
1599                 btrfs_put_ordered_extent(ordered);
1600                 goto again;
1601         }
1602
1603         set_extent_delalloc(&BTRFS_I(inode)->io_tree, page_start,
1604                             page_end, GFP_NOFS);
1605         ret = 0;
1606         if (offset != PAGE_CACHE_SIZE) {
1607                 kaddr = kmap(page);
1608                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
1609                 flush_dcache_page(page);
1610                 kunmap(page);
1611         }
1612         ClearPageChecked(page);
1613         set_page_dirty(page);
1614         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
1615
1616 out_unlock:
1617         unlock_page(page);
1618         page_cache_release(page);
1619 out:
1620         return ret;
1621 }
1622
1623 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
1624 {
1625         struct inode *inode = dentry->d_inode;
1626         int err;
1627
1628         err = inode_change_ok(inode, attr);
1629         if (err)
1630                 return err;
1631
1632         if (S_ISREG(inode->i_mode) &&
1633             attr->ia_valid & ATTR_SIZE && attr->ia_size > inode->i_size) {
1634                 struct btrfs_trans_handle *trans;
1635                 struct btrfs_root *root = BTRFS_I(inode)->root;
1636                 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1637
1638                 u64 mask = root->sectorsize - 1;
1639                 u64 hole_start = (inode->i_size + mask) & ~mask;
1640                 u64 block_end = (attr->ia_size + mask) & ~mask;
1641                 u64 hole_size;
1642                 u64 alloc_hint = 0;
1643
1644                 if (attr->ia_size <= hole_start)
1645                         goto out;
1646
1647                 err = btrfs_check_free_space(root, 1, 0);
1648                 if (err)
1649                         goto fail;
1650
1651                 btrfs_truncate_page(inode->i_mapping, inode->i_size);
1652
1653                 hole_size = block_end - hole_start;
1654                 btrfs_wait_ordered_range(inode, hole_start, hole_size);
1655                 lock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
1656
1657                 trans = btrfs_start_transaction(root, 1);
1658                 btrfs_set_trans_block_group(trans, inode);
1659                 mutex_lock(&BTRFS_I(inode)->extent_mutex);
1660                 err = btrfs_drop_extents(trans, root, inode,
1661                                          hole_start, block_end, hole_start,
1662                                          &alloc_hint);
1663
1664                 if (alloc_hint != EXTENT_MAP_INLINE) {
1665                         err = btrfs_insert_file_extent(trans, root,
1666                                                        inode->i_ino,
1667                                                        hole_start, 0, 0,
1668                                                        hole_size, 0);
1669                         btrfs_drop_extent_cache(inode, hole_start,
1670                                                 (u64)-1);
1671                         btrfs_check_file(root, inode);
1672                 }
1673                 mutex_unlock(&BTRFS_I(inode)->extent_mutex);
1674                 btrfs_end_transaction(trans, root);
1675                 unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
1676                 if (err)
1677                         return err;
1678         }
1679 out:
1680         err = inode_setattr(inode, attr);
1681
1682         if (!err && ((attr->ia_valid & ATTR_MODE)))
1683                 err = btrfs_acl_chmod(inode);
1684 fail:
1685         return err;
1686 }
1687
1688 void btrfs_delete_inode(struct inode *inode)
1689 {
1690         struct btrfs_trans_handle *trans;
1691         struct btrfs_root *root = BTRFS_I(inode)->root;
1692         unsigned long nr;
1693         int ret;
1694
1695         truncate_inode_pages(&inode->i_data, 0);
1696         if (is_bad_inode(inode)) {
1697                 btrfs_orphan_del(NULL, inode);
1698                 goto no_delete;
1699         }
1700         btrfs_wait_ordered_range(inode, 0, (u64)-1);
1701
1702         btrfs_i_size_write(inode, 0);
1703         trans = btrfs_start_transaction(root, 1);
1704
1705         btrfs_set_trans_block_group(trans, inode);
1706         ret = btrfs_truncate_in_trans(trans, root, inode, 0);
1707         if (ret) {
1708                 btrfs_orphan_del(NULL, inode);
1709                 goto no_delete_lock;
1710         }
1711
1712         btrfs_orphan_del(trans, inode);
1713
1714         nr = trans->blocks_used;
1715         clear_inode(inode);
1716
1717         btrfs_end_transaction(trans, root);
1718         btrfs_btree_balance_dirty(root, nr);
1719         return;
1720
1721 no_delete_lock:
1722         nr = trans->blocks_used;
1723         btrfs_end_transaction(trans, root);
1724         btrfs_btree_balance_dirty(root, nr);
1725 no_delete:
1726         clear_inode(inode);
1727 }
1728
1729 /*
1730  * this returns the key found in the dir entry in the location pointer.
1731  * If no dir entries were found, location->objectid is 0.
1732  */
1733 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
1734                                struct btrfs_key *location)
1735 {
1736         const char *name = dentry->d_name.name;
1737         int namelen = dentry->d_name.len;
1738         struct btrfs_dir_item *di;
1739         struct btrfs_path *path;
1740         struct btrfs_root *root = BTRFS_I(dir)->root;
1741         int ret = 0;
1742
1743         if (namelen == 1 && strcmp(name, ".") == 0) {
1744                 location->objectid = dir->i_ino;
1745                 location->type = BTRFS_INODE_ITEM_KEY;
1746                 location->offset = 0;
1747                 return 0;
1748         }
1749         path = btrfs_alloc_path();
1750         BUG_ON(!path);
1751
1752         if (namelen == 2 && strcmp(name, "..") == 0) {
1753                 struct btrfs_key key;
1754                 struct extent_buffer *leaf;
1755                 u32 nritems;
1756                 int slot;
1757
1758                 key.objectid = dir->i_ino;
1759                 btrfs_set_key_type(&key, BTRFS_INODE_REF_KEY);
1760                 key.offset = 0;
1761                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1762                 BUG_ON(ret == 0);
1763                 ret = 0;
1764
1765                 leaf = path->nodes[0];
1766                 slot = path->slots[0];
1767                 nritems = btrfs_header_nritems(leaf);
1768                 if (slot >= nritems)
1769                         goto out_err;
1770
1771                 btrfs_item_key_to_cpu(leaf, &key, slot);
1772                 if (key.objectid != dir->i_ino ||
1773                     key.type != BTRFS_INODE_REF_KEY) {
1774                         goto out_err;
1775                 }
1776                 location->objectid = key.offset;
1777                 location->type = BTRFS_INODE_ITEM_KEY;
1778                 location->offset = 0;
1779                 goto out;
1780         }
1781
1782         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
1783                                     namelen, 0);
1784         if (IS_ERR(di))
1785                 ret = PTR_ERR(di);
1786         if (!di || IS_ERR(di)) {
1787                 goto out_err;
1788         }
1789         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
1790 out:
1791         btrfs_free_path(path);
1792         return ret;
1793 out_err:
1794         location->objectid = 0;
1795         goto out;
1796 }
1797
1798 /*
1799  * when we hit a tree root in a directory, the btrfs part of the inode
1800  * needs to be changed to reflect the root directory of the tree root.  This
1801  * is kind of like crossing a mount point.
1802  */
1803 static int fixup_tree_root_location(struct btrfs_root *root,
1804                              struct btrfs_key *location,
1805                              struct btrfs_root **sub_root,
1806                              struct dentry *dentry)
1807 {
1808         struct btrfs_path *path;
1809         struct btrfs_root_item *ri;
1810
1811         if (btrfs_key_type(location) != BTRFS_ROOT_ITEM_KEY)
1812                 return 0;
1813         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1814                 return 0;
1815
1816         path = btrfs_alloc_path();
1817         BUG_ON(!path);
1818
1819         *sub_root = btrfs_read_fs_root(root->fs_info, location,
1820                                         dentry->d_name.name,
1821                                         dentry->d_name.len);
1822         if (IS_ERR(*sub_root))
1823                 return PTR_ERR(*sub_root);
1824
1825         ri = &(*sub_root)->root_item;
1826         location->objectid = btrfs_root_dirid(ri);
1827         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
1828         location->offset = 0;
1829
1830         btrfs_free_path(path);
1831         return 0;
1832 }
1833
1834 static int btrfs_init_locked_inode(struct inode *inode, void *p)
1835 {
1836         struct btrfs_iget_args *args = p;
1837         inode->i_ino = args->ino;
1838         BTRFS_I(inode)->root = args->root;
1839         BTRFS_I(inode)->delalloc_bytes = 0;
1840         BTRFS_I(inode)->disk_i_size = 0;
1841         BTRFS_I(inode)->index_cnt = (u64)-1;
1842         extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
1843         extent_io_tree_init(&BTRFS_I(inode)->io_tree,
1844                              inode->i_mapping, GFP_NOFS);
1845         extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
1846                              inode->i_mapping, GFP_NOFS);
1847         btrfs_ordered_inode_tree_init(&BTRFS_I(inode)->ordered_tree);
1848         mutex_init(&BTRFS_I(inode)->csum_mutex);
1849         mutex_init(&BTRFS_I(inode)->extent_mutex);
1850         return 0;
1851 }
1852
1853 static int btrfs_find_actor(struct inode *inode, void *opaque)
1854 {
1855         struct btrfs_iget_args *args = opaque;
1856         return (args->ino == inode->i_ino &&
1857                 args->root == BTRFS_I(inode)->root);
1858 }
1859
1860 struct inode *btrfs_ilookup(struct super_block *s, u64 objectid,
1861                             u64 root_objectid)
1862 {
1863         struct btrfs_iget_args args;
1864         args.ino = objectid;
1865         args.root = btrfs_lookup_fs_root(btrfs_sb(s)->fs_info, root_objectid);
1866
1867         if (!args.root)
1868                 return NULL;
1869
1870         return ilookup5(s, objectid, btrfs_find_actor, (void *)&args);
1871 }
1872
1873 struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid,
1874                                 struct btrfs_root *root)
1875 {
1876         struct inode *inode;
1877         struct btrfs_iget_args args;
1878         args.ino = objectid;
1879         args.root = root;
1880
1881         inode = iget5_locked(s, objectid, btrfs_find_actor,
1882                              btrfs_init_locked_inode,
1883                              (void *)&args);
1884         return inode;
1885 }
1886
1887 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
1888                                    struct nameidata *nd)
1889 {
1890         struct inode * inode;
1891         struct btrfs_inode *bi = BTRFS_I(dir);
1892         struct btrfs_root *root = bi->root;
1893         struct btrfs_root *sub_root = root;
1894         struct btrfs_key location;
1895         int ret, do_orphan = 0;
1896
1897         if (dentry->d_name.len > BTRFS_NAME_LEN)
1898                 return ERR_PTR(-ENAMETOOLONG);
1899
1900         ret = btrfs_inode_by_name(dir, dentry, &location);
1901
1902         if (ret < 0)
1903                 return ERR_PTR(ret);
1904
1905         inode = NULL;
1906         if (location.objectid) {
1907                 ret = fixup_tree_root_location(root, &location, &sub_root,
1908                                                 dentry);
1909                 if (ret < 0)
1910                         return ERR_PTR(ret);
1911                 if (ret > 0)
1912                         return ERR_PTR(-ENOENT);
1913
1914                 inode = btrfs_iget_locked(dir->i_sb, location.objectid,
1915                                           sub_root);
1916                 if (!inode)
1917                         return ERR_PTR(-EACCES);
1918                 if (inode->i_state & I_NEW) {
1919                         /* the inode and parent dir are two different roots */
1920                         if (sub_root != root) {
1921                                 igrab(inode);
1922                                 sub_root->inode = inode;
1923                                 do_orphan = 1;
1924                         }
1925                         BTRFS_I(inode)->root = sub_root;
1926                         memcpy(&BTRFS_I(inode)->location, &location,
1927                                sizeof(location));
1928                         btrfs_read_locked_inode(inode);
1929                         unlock_new_inode(inode);
1930                 }
1931         }
1932
1933         if (unlikely(do_orphan))
1934                 btrfs_orphan_cleanup(sub_root);
1935
1936         return d_splice_alias(inode, dentry);
1937 }
1938
1939 static unsigned char btrfs_filetype_table[] = {
1940         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
1941 };
1942
1943 static int btrfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
1944 {
1945         struct inode *inode = filp->f_dentry->d_inode;
1946         struct btrfs_root *root = BTRFS_I(inode)->root;
1947         struct btrfs_item *item;
1948         struct btrfs_dir_item *di;
1949         struct btrfs_key key;
1950         struct btrfs_key found_key;
1951         struct btrfs_path *path;
1952         int ret;
1953         u32 nritems;
1954         struct extent_buffer *leaf;
1955         int slot;
1956         int advance;
1957         unsigned char d_type;
1958         int over = 0;
1959         u32 di_cur;
1960         u32 di_total;
1961         u32 di_len;
1962         int key_type = BTRFS_DIR_INDEX_KEY;
1963         char tmp_name[32];
1964         char *name_ptr;
1965         int name_len;
1966
1967         /* FIXME, use a real flag for deciding about the key type */
1968         if (root->fs_info->tree_root == root)
1969                 key_type = BTRFS_DIR_ITEM_KEY;
1970
1971         /* special case for "." */
1972         if (filp->f_pos == 0) {
1973                 over = filldir(dirent, ".", 1,
1974                                1, inode->i_ino,
1975                                DT_DIR);
1976                 if (over)
1977                         return 0;
1978                 filp->f_pos = 1;
1979         }
1980
1981         key.objectid = inode->i_ino;
1982         path = btrfs_alloc_path();
1983         path->reada = 2;
1984
1985         /* special case for .., just use the back ref */
1986         if (filp->f_pos == 1) {
1987                 btrfs_set_key_type(&key, BTRFS_INODE_REF_KEY);
1988                 key.offset = 0;
1989                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1990                 BUG_ON(ret == 0);
1991                 leaf = path->nodes[0];
1992                 slot = path->slots[0];
1993                 nritems = btrfs_header_nritems(leaf);
1994                 if (slot >= nritems) {
1995                         btrfs_release_path(root, path);
1996                         goto read_dir_items;
1997                 }
1998                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1999                 btrfs_release_path(root, path);
2000                 if (found_key.objectid != key.objectid ||
2001                     found_key.type != BTRFS_INODE_REF_KEY)
2002                         goto read_dir_items;
2003                 over = filldir(dirent, "..", 2,
2004                                2, found_key.offset, DT_DIR);
2005                 if (over)
2006                         goto nopos;
2007                 filp->f_pos = 2;
2008         }
2009
2010 read_dir_items:
2011         btrfs_set_key_type(&key, key_type);
2012         key.offset = filp->f_pos;
2013
2014         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2015         if (ret < 0)
2016                 goto err;
2017         advance = 0;
2018         while(1) {
2019                 leaf = path->nodes[0];
2020                 nritems = btrfs_header_nritems(leaf);
2021                 slot = path->slots[0];
2022                 if (advance || slot >= nritems) {
2023                         if (slot >= nritems -1) {
2024                                 ret = btrfs_next_leaf(root, path);
2025                                 if (ret)
2026                                         break;
2027                                 leaf = path->nodes[0];
2028                                 nritems = btrfs_header_nritems(leaf);
2029                                 slot = path->slots[0];
2030                         } else {
2031                                 slot++;
2032                                 path->slots[0]++;
2033                         }
2034                 }
2035                 advance = 1;
2036                 item = btrfs_item_nr(leaf, slot);
2037                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2038
2039                 if (found_key.objectid != key.objectid)
2040                         break;
2041                 if (btrfs_key_type(&found_key) != key_type)
2042                         break;
2043                 if (found_key.offset < filp->f_pos)
2044                         continue;
2045
2046                 filp->f_pos = found_key.offset;
2047                 advance = 1;
2048                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
2049                 di_cur = 0;
2050                 di_total = btrfs_item_size(leaf, item);
2051                 while(di_cur < di_total) {
2052                         struct btrfs_key location;
2053
2054                         name_len = btrfs_dir_name_len(leaf, di);
2055                         if (name_len < 32) {
2056                                 name_ptr = tmp_name;
2057                         } else {
2058                                 name_ptr = kmalloc(name_len, GFP_NOFS);
2059                                 BUG_ON(!name_ptr);
2060                         }
2061                         read_extent_buffer(leaf, name_ptr,
2062                                            (unsigned long)(di + 1), name_len);
2063
2064                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
2065                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
2066                         over = filldir(dirent, name_ptr, name_len,
2067                                        found_key.offset,
2068                                        location.objectid,
2069                                        d_type);
2070
2071                         if (name_ptr != tmp_name)
2072                                 kfree(name_ptr);
2073
2074                         if (over)
2075                                 goto nopos;
2076                         di_len = btrfs_dir_name_len(leaf, di) +
2077                                 btrfs_dir_data_len(leaf, di) +sizeof(*di);
2078                         di_cur += di_len;
2079                         di = (struct btrfs_dir_item *)((char *)di + di_len);
2080                 }
2081         }
2082         if (key_type == BTRFS_DIR_INDEX_KEY)
2083                 filp->f_pos = INT_LIMIT(typeof(filp->f_pos));
2084         else
2085                 filp->f_pos++;
2086 nopos:
2087         ret = 0;
2088 err:
2089         btrfs_free_path(path);
2090         return ret;
2091 }
2092
2093 int btrfs_write_inode(struct inode *inode, int wait)
2094 {
2095         struct btrfs_root *root = BTRFS_I(inode)->root;
2096         struct btrfs_trans_handle *trans;
2097         int ret = 0;
2098
2099         if (wait) {
2100                 trans = btrfs_join_transaction(root, 1);
2101                 btrfs_set_trans_block_group(trans, inode);
2102                 ret = btrfs_commit_transaction(trans, root);
2103         }
2104         return ret;
2105 }
2106
2107 /*
2108  * This is somewhat expensive, updating the tree every time the
2109  * inode changes.  But, it is most likely to find the inode in cache.
2110  * FIXME, needs more benchmarking...there are no reasons other than performance
2111  * to keep or drop this code.
2112  */
2113 void btrfs_dirty_inode(struct inode *inode)
2114 {
2115         struct btrfs_root *root = BTRFS_I(inode)->root;
2116         struct btrfs_trans_handle *trans;
2117
2118         trans = btrfs_join_transaction(root, 1);
2119         btrfs_set_trans_block_group(trans, inode);
2120         btrfs_update_inode(trans, root, inode);
2121         btrfs_end_transaction(trans, root);
2122 }
2123
2124 static int btrfs_set_inode_index_count(struct inode *inode)
2125 {
2126         struct btrfs_root *root = BTRFS_I(inode)->root;
2127         struct btrfs_key key, found_key;
2128         struct btrfs_path *path;
2129         struct extent_buffer *leaf;
2130         int ret;
2131
2132         key.objectid = inode->i_ino;
2133         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
2134         key.offset = (u64)-1;
2135
2136         path = btrfs_alloc_path();
2137         if (!path)
2138                 return -ENOMEM;
2139
2140         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2141         if (ret < 0)
2142                 goto out;
2143         /* FIXME: we should be able to handle this */
2144         if (ret == 0)
2145                 goto out;
2146         ret = 0;
2147
2148         /*
2149          * MAGIC NUMBER EXPLANATION:
2150          * since we search a directory based on f_pos we have to start at 2
2151          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
2152          * else has to start at 2
2153          */
2154         if (path->slots[0] == 0) {
2155                 BTRFS_I(inode)->index_cnt = 2;
2156                 goto out;
2157         }
2158
2159         path->slots[0]--;
2160
2161         leaf = path->nodes[0];
2162         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2163
2164         if (found_key.objectid != inode->i_ino ||
2165             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
2166                 BTRFS_I(inode)->index_cnt = 2;
2167                 goto out;
2168         }
2169
2170         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
2171 out:
2172         btrfs_free_path(path);
2173         return ret;
2174 }
2175
2176 static int btrfs_set_inode_index(struct inode *dir, struct inode *inode)
2177 {
2178         int ret = 0;
2179
2180         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
2181                 ret = btrfs_set_inode_index_count(dir);
2182                 if (ret)
2183                         return ret;
2184         }
2185
2186         BTRFS_I(inode)->index = BTRFS_I(dir)->index_cnt;
2187         BTRFS_I(dir)->index_cnt++;
2188
2189         return ret;
2190 }
2191
2192 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
2193                                      struct btrfs_root *root,
2194                                      struct inode *dir,
2195                                      const char *name, int name_len,
2196                                      u64 ref_objectid,
2197                                      u64 objectid,
2198                                      struct btrfs_block_group_cache *group,
2199                                      int mode)
2200 {
2201         struct inode *inode;
2202         struct btrfs_inode_item *inode_item;
2203         struct btrfs_block_group_cache *new_inode_group;
2204         struct btrfs_key *location;
2205         struct btrfs_path *path;
2206         struct btrfs_inode_ref *ref;
2207         struct btrfs_key key[2];
2208         u32 sizes[2];
2209         unsigned long ptr;
2210         int ret;
2211         int owner;
2212
2213         path = btrfs_alloc_path();
2214         BUG_ON(!path);
2215
2216         inode = new_inode(root->fs_info->sb);
2217         if (!inode)
2218                 return ERR_PTR(-ENOMEM);
2219
2220         if (dir) {
2221                 ret = btrfs_set_inode_index(dir, inode);
2222                 if (ret)
2223                         return ERR_PTR(ret);
2224         } else {
2225                 BTRFS_I(inode)->index = 0;
2226         }
2227         /*
2228          * index_cnt is ignored for everything but a dir,
2229          * btrfs_get_inode_index_count has an explanation for the magic
2230          * number
2231          */
2232         BTRFS_I(inode)->index_cnt = 2;
2233
2234         extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
2235         extent_io_tree_init(&BTRFS_I(inode)->io_tree,
2236                              inode->i_mapping, GFP_NOFS);
2237         extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
2238                              inode->i_mapping, GFP_NOFS);
2239         btrfs_ordered_inode_tree_init(&BTRFS_I(inode)->ordered_tree);
2240         mutex_init(&BTRFS_I(inode)->csum_mutex);
2241         mutex_init(&BTRFS_I(inode)->extent_mutex);
2242         BTRFS_I(inode)->delalloc_bytes = 0;
2243         BTRFS_I(inode)->disk_i_size = 0;
2244         BTRFS_I(inode)->root = root;
2245
2246         if (mode & S_IFDIR)
2247                 owner = 0;
2248         else
2249                 owner = 1;
2250         new_inode_group = btrfs_find_block_group(root, group, 0,
2251                                        BTRFS_BLOCK_GROUP_METADATA, owner);
2252         if (!new_inode_group) {
2253                 printk("find_block group failed\n");
2254                 new_inode_group = group;
2255         }
2256         BTRFS_I(inode)->block_group = new_inode_group;
2257         BTRFS_I(inode)->flags = 0;
2258
2259         key[0].objectid = objectid;
2260         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
2261         key[0].offset = 0;
2262
2263         key[1].objectid = objectid;
2264         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
2265         key[1].offset = ref_objectid;
2266
2267         sizes[0] = sizeof(struct btrfs_inode_item);
2268         sizes[1] = name_len + sizeof(*ref);
2269
2270         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
2271         if (ret != 0)
2272                 goto fail;
2273
2274         if (objectid > root->highest_inode)
2275                 root->highest_inode = objectid;
2276
2277         inode->i_uid = current->fsuid;
2278         inode->i_gid = current->fsgid;
2279         inode->i_mode = mode;
2280         inode->i_ino = objectid;
2281         inode->i_blocks = 0;
2282         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
2283         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2284                                   struct btrfs_inode_item);
2285         fill_inode_item(path->nodes[0], inode_item, inode);
2286
2287         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
2288                              struct btrfs_inode_ref);
2289         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
2290         btrfs_set_inode_ref_index(path->nodes[0], ref, BTRFS_I(inode)->index);
2291         ptr = (unsigned long)(ref + 1);
2292         write_extent_buffer(path->nodes[0], name, ptr, name_len);
2293
2294         btrfs_mark_buffer_dirty(path->nodes[0]);
2295         btrfs_free_path(path);
2296
2297         location = &BTRFS_I(inode)->location;
2298         location->objectid = objectid;
2299         location->offset = 0;
2300         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
2301
2302         insert_inode_hash(inode);
2303         return inode;
2304 fail:
2305         if (dir)
2306                 BTRFS_I(dir)->index_cnt--;
2307         btrfs_free_path(path);
2308         return ERR_PTR(ret);
2309 }
2310
2311 static inline u8 btrfs_inode_type(struct inode *inode)
2312 {
2313         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
2314 }
2315
2316 static int btrfs_add_link(struct btrfs_trans_handle *trans,
2317                             struct dentry *dentry, struct inode *inode,
2318                             int add_backref)
2319 {
2320         int ret;
2321         struct btrfs_key key;
2322         struct btrfs_root *root = BTRFS_I(dentry->d_parent->d_inode)->root;
2323         struct inode *parent_inode = dentry->d_parent->d_inode;
2324
2325         key.objectid = inode->i_ino;
2326         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
2327         key.offset = 0;
2328
2329         ret = btrfs_insert_dir_item(trans, root,
2330                                     dentry->d_name.name, dentry->d_name.len,
2331                                     dentry->d_parent->d_inode->i_ino,
2332                                     &key, btrfs_inode_type(inode),
2333                                     BTRFS_I(inode)->index);
2334         if (ret == 0) {
2335                 if (add_backref) {
2336                         ret = btrfs_insert_inode_ref(trans, root,
2337                                              dentry->d_name.name,
2338                                              dentry->d_name.len,
2339                                              inode->i_ino,
2340                                              parent_inode->i_ino,
2341                                              BTRFS_I(inode)->index);
2342                 }
2343                 btrfs_i_size_write(parent_inode, parent_inode->i_size +
2344                                    dentry->d_name.len * 2);
2345                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
2346                 ret = btrfs_update_inode(trans, root,
2347                                          dentry->d_parent->d_inode);
2348         }
2349         return ret;
2350 }
2351
2352 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
2353                             struct dentry *dentry, struct inode *inode,
2354                             int backref)
2355 {
2356         int err = btrfs_add_link(trans, dentry, inode, backref);
2357         if (!err) {
2358                 d_instantiate(dentry, inode);
2359                 return 0;
2360         }
2361         if (err > 0)
2362                 err = -EEXIST;
2363         return err;
2364 }
2365
2366 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
2367                         int mode, dev_t rdev)
2368 {
2369         struct btrfs_trans_handle *trans;
2370         struct btrfs_root *root = BTRFS_I(dir)->root;
2371         struct inode *inode = NULL;
2372         int err;
2373         int drop_inode = 0;
2374         u64 objectid;
2375         unsigned long nr = 0;
2376
2377         if (!new_valid_dev(rdev))
2378                 return -EINVAL;
2379
2380         err = btrfs_check_free_space(root, 1, 0);
2381         if (err)
2382                 goto fail;
2383
2384         trans = btrfs_start_transaction(root, 1);
2385         btrfs_set_trans_block_group(trans, dir);
2386
2387         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
2388         if (err) {
2389                 err = -ENOSPC;
2390                 goto out_unlock;
2391         }
2392
2393         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
2394                                 dentry->d_name.len,
2395                                 dentry->d_parent->d_inode->i_ino, objectid,
2396                                 BTRFS_I(dir)->block_group, mode);
2397         err = PTR_ERR(inode);
2398         if (IS_ERR(inode))
2399                 goto out_unlock;
2400
2401         err = btrfs_init_acl(inode, dir);
2402         if (err) {
2403                 drop_inode = 1;
2404                 goto out_unlock;
2405         }
2406
2407         btrfs_set_trans_block_group(trans, inode);
2408         err = btrfs_add_nondir(trans, dentry, inode, 0);
2409         if (err)
2410                 drop_inode = 1;
2411         else {
2412                 inode->i_op = &btrfs_special_inode_operations;
2413                 init_special_inode(inode, inode->i_mode, rdev);
2414                 btrfs_update_inode(trans, root, inode);
2415         }
2416         dir->i_sb->s_dirt = 1;
2417         btrfs_update_inode_block_group(trans, inode);
2418         btrfs_update_inode_block_group(trans, dir);
2419 out_unlock:
2420         nr = trans->blocks_used;
2421         btrfs_end_transaction_throttle(trans, root);
2422 fail:
2423         if (drop_inode) {
2424                 inode_dec_link_count(inode);
2425                 iput(inode);
2426         }
2427         btrfs_btree_balance_dirty(root, nr);
2428         return err;
2429 }
2430
2431 static int btrfs_create(struct inode *dir, struct dentry *dentry,
2432                         int mode, struct nameidata *nd)
2433 {
2434         struct btrfs_trans_handle *trans;
2435         struct btrfs_root *root = BTRFS_I(dir)->root;
2436         struct inode *inode = NULL;
2437         int err;
2438         int drop_inode = 0;
2439         unsigned long nr = 0;
2440         u64 objectid;
2441
2442         err = btrfs_check_free_space(root, 1, 0);
2443         if (err)
2444                 goto fail;
2445         trans = btrfs_start_transaction(root, 1);
2446         btrfs_set_trans_block_group(trans, dir);
2447
2448         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
2449         if (err) {
2450                 err = -ENOSPC;
2451                 goto out_unlock;
2452         }
2453
2454         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
2455                                 dentry->d_name.len,
2456                                 dentry->d_parent->d_inode->i_ino,
2457                                 objectid, BTRFS_I(dir)->block_group, mode);
2458         err = PTR_ERR(inode);
2459         if (IS_ERR(inode))
2460                 goto out_unlock;
2461
2462         err = btrfs_init_acl(inode, dir);
2463         if (err) {
2464                 drop_inode = 1;
2465                 goto out_unlock;
2466         }
2467
2468         btrfs_set_trans_block_group(trans, inode);
2469         err = btrfs_add_nondir(trans, dentry, inode, 0);
2470         if (err)
2471                 drop_inode = 1;
2472         else {
2473                 inode->i_mapping->a_ops = &btrfs_aops;
2474                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2475                 inode->i_fop = &btrfs_file_operations;
2476                 inode->i_op = &btrfs_file_inode_operations;
2477                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
2478                 extent_io_tree_init(&BTRFS_I(inode)->io_tree,
2479                                      inode->i_mapping, GFP_NOFS);
2480                 extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
2481                                      inode->i_mapping, GFP_NOFS);
2482                 mutex_init(&BTRFS_I(inode)->csum_mutex);
2483                 mutex_init(&BTRFS_I(inode)->extent_mutex);
2484                 BTRFS_I(inode)->delalloc_bytes = 0;
2485                 BTRFS_I(inode)->disk_i_size = 0;
2486                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2487                 btrfs_ordered_inode_tree_init(&BTRFS_I(inode)->ordered_tree);
2488         }
2489         dir->i_sb->s_dirt = 1;
2490         btrfs_update_inode_block_group(trans, inode);
2491         btrfs_update_inode_block_group(trans, dir);
2492 out_unlock:
2493         nr = trans->blocks_used;
2494         btrfs_end_transaction_throttle(trans, root);
2495 fail:
2496         if (drop_inode) {
2497                 inode_dec_link_count(inode);
2498                 iput(inode);
2499         }
2500         btrfs_btree_balance_dirty(root, nr);
2501         return err;
2502 }
2503
2504 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
2505                       struct dentry *dentry)
2506 {
2507         struct btrfs_trans_handle *trans;
2508         struct btrfs_root *root = BTRFS_I(dir)->root;
2509         struct inode *inode = old_dentry->d_inode;
2510         unsigned long nr = 0;
2511         int err;
2512         int drop_inode = 0;
2513
2514         if (inode->i_nlink == 0)
2515                 return -ENOENT;
2516
2517 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
2518         inode->i_nlink++;
2519 #else
2520         inc_nlink(inode);
2521 #endif
2522         err = btrfs_check_free_space(root, 1, 0);
2523         if (err)
2524                 goto fail;
2525         err = btrfs_set_inode_index(dir, inode);
2526         if (err)
2527                 goto fail;
2528
2529         trans = btrfs_start_transaction(root, 1);
2530
2531         btrfs_set_trans_block_group(trans, dir);
2532         atomic_inc(&inode->i_count);
2533
2534         err = btrfs_add_nondir(trans, dentry, inode, 1);
2535
2536         if (err)
2537                 drop_inode = 1;
2538
2539         dir->i_sb->s_dirt = 1;
2540         btrfs_update_inode_block_group(trans, dir);
2541         err = btrfs_update_inode(trans, root, inode);
2542
2543         if (err)
2544                 drop_inode = 1;
2545
2546         nr = trans->blocks_used;
2547         btrfs_end_transaction_throttle(trans, root);
2548 fail:
2549         if (drop_inode) {
2550                 inode_dec_link_count(inode);
2551                 iput(inode);
2552         }
2553         btrfs_btree_balance_dirty(root, nr);
2554         return err;
2555 }
2556
2557 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2558 {
2559         struct inode *inode = NULL;
2560         struct btrfs_trans_handle *trans;
2561         struct btrfs_root *root = BTRFS_I(dir)->root;
2562         int err = 0;
2563         int drop_on_err = 0;
2564         u64 objectid = 0;
2565         unsigned long nr = 1;
2566
2567         err = btrfs_check_free_space(root, 1, 0);
2568         if (err)
2569                 goto out_unlock;
2570
2571         trans = btrfs_start_transaction(root, 1);
2572         btrfs_set_trans_block_group(trans, dir);
2573
2574         if (IS_ERR(trans)) {
2575                 err = PTR_ERR(trans);
2576                 goto out_unlock;
2577         }
2578
2579         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
2580         if (err) {
2581                 err = -ENOSPC;
2582                 goto out_unlock;
2583         }
2584
2585         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
2586                                 dentry->d_name.len,
2587                                 dentry->d_parent->d_inode->i_ino, objectid,
2588                                 BTRFS_I(dir)->block_group, S_IFDIR | mode);
2589         if (IS_ERR(inode)) {
2590                 err = PTR_ERR(inode);
2591                 goto out_fail;
2592         }
2593
2594         drop_on_err = 1;
2595
2596         err = btrfs_init_acl(inode, dir);
2597         if (err)
2598                 goto out_fail;
2599
2600         inode->i_op = &btrfs_dir_inode_operations;
2601         inode->i_fop = &btrfs_dir_file_operations;
2602         btrfs_set_trans_block_group(trans, inode);
2603
2604         btrfs_i_size_write(inode, 0);
2605         err = btrfs_update_inode(trans, root, inode);
2606         if (err)
2607                 goto out_fail;
2608
2609         err = btrfs_add_link(trans, dentry, inode, 0);
2610         if (err)
2611                 goto out_fail;
2612
2613         d_instantiate(dentry, inode);
2614         drop_on_err = 0;
2615         dir->i_sb->s_dirt = 1;
2616         btrfs_update_inode_block_group(trans, inode);
2617         btrfs_update_inode_block_group(trans, dir);
2618
2619 out_fail:
2620         nr = trans->blocks_used;
2621         btrfs_end_transaction_throttle(trans, root);
2622
2623 out_unlock:
2624         if (drop_on_err)
2625                 iput(inode);
2626         btrfs_btree_balance_dirty(root, nr);
2627         return err;
2628 }
2629
2630 static int merge_extent_mapping(struct extent_map_tree *em_tree,
2631                                 struct extent_map *existing,
2632                                 struct extent_map *em,
2633                                 u64 map_start, u64 map_len)
2634 {
2635         u64 start_diff;
2636
2637         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
2638         start_diff = map_start - em->start;
2639         em->start = map_start;
2640         em->len = map_len;
2641         if (em->block_start < EXTENT_MAP_LAST_BYTE)
2642                 em->block_start += start_diff;
2643         return add_extent_mapping(em_tree, em);
2644 }
2645
2646 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
2647                                     size_t pg_offset, u64 start, u64 len,
2648                                     int create)
2649 {
2650         int ret;
2651         int err = 0;
2652         u64 bytenr;
2653         u64 extent_start = 0;
2654         u64 extent_end = 0;
2655         u64 objectid = inode->i_ino;
2656         u32 found_type;
2657         struct btrfs_path *path = NULL;
2658         struct btrfs_root *root = BTRFS_I(inode)->root;
2659         struct btrfs_file_extent_item *item;
2660         struct extent_buffer *leaf;
2661         struct btrfs_key found_key;
2662         struct extent_map *em = NULL;
2663         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2664         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2665         struct btrfs_trans_handle *trans = NULL;
2666
2667 again:
2668         spin_lock(&em_tree->lock);
2669         em = lookup_extent_mapping(em_tree, start, len);
2670         if (em)
2671                 em->bdev = root->fs_info->fs_devices->latest_bdev;
2672         spin_unlock(&em_tree->lock);
2673
2674         if (em) {
2675                 if (em->start > start || em->start + em->len <= start)
2676                         free_extent_map(em);
2677                 else if (em->block_start == EXTENT_MAP_INLINE && page)
2678                         free_extent_map(em);
2679                 else
2680                         goto out;
2681         }
2682         em = alloc_extent_map(GFP_NOFS);
2683         if (!em) {
2684                 err = -ENOMEM;
2685                 goto out;
2686         }
2687         em->bdev = root->fs_info->fs_devices->latest_bdev;
2688         em->start = EXTENT_MAP_HOLE;
2689         em->len = (u64)-1;
2690
2691         if (!path) {
2692                 path = btrfs_alloc_path();
2693                 BUG_ON(!path);
2694         }
2695
2696         ret = btrfs_lookup_file_extent(trans, root, path,
2697                                        objectid, start, trans != NULL);
2698         if (ret < 0) {
2699                 err = ret;
2700                 goto out;
2701         }
2702
2703         if (ret != 0) {
2704                 if (path->slots[0] == 0)
2705                         goto not_found;
2706                 path->slots[0]--;
2707         }
2708
2709         leaf = path->nodes[0];
2710         item = btrfs_item_ptr(leaf, path->slots[0],
2711                               struct btrfs_file_extent_item);
2712         /* are we inside the extent that was found? */
2713         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2714         found_type = btrfs_key_type(&found_key);
2715         if (found_key.objectid != objectid ||
2716             found_type != BTRFS_EXTENT_DATA_KEY) {
2717                 goto not_found;
2718         }
2719
2720         found_type = btrfs_file_extent_type(leaf, item);
2721         extent_start = found_key.offset;
2722         if (found_type == BTRFS_FILE_EXTENT_REG) {
2723                 extent_end = extent_start +
2724                        btrfs_file_extent_num_bytes(leaf, item);
2725                 err = 0;
2726                 if (start < extent_start || start >= extent_end) {
2727                         em->start = start;
2728                         if (start < extent_start) {
2729                                 if (start + len <= extent_start)
2730                                         goto not_found;
2731                                 em->len = extent_end - extent_start;
2732                         } else {
2733                                 em->len = len;
2734                         }
2735                         goto not_found_em;
2736                 }
2737                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
2738                 if (bytenr == 0) {
2739                         em->start = extent_start;
2740                         em->len = extent_end - extent_start;
2741                         em->block_start = EXTENT_MAP_HOLE;
2742                         goto insert;
2743                 }
2744                 bytenr += btrfs_file_extent_offset(leaf, item);
2745                 em->block_start = bytenr;
2746                 em->start = extent_start;
2747                 em->len = extent_end - extent_start;
2748                 goto insert;
2749         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
2750                 u64 page_start;
2751                 unsigned long ptr;
2752                 char *map;
2753                 size_t size;
2754                 size_t extent_offset;
2755                 size_t copy_size;
2756
2757                 size = btrfs_file_extent_inline_len(leaf, btrfs_item_nr(leaf,
2758                                                     path->slots[0]));
2759                 extent_end = (extent_start + size + root->sectorsize - 1) &
2760                         ~((u64)root->sectorsize - 1);
2761                 if (start < extent_start || start >= extent_end) {
2762                         em->start = start;
2763                         if (start < extent_start) {
2764                                 if (start + len <= extent_start)
2765                                         goto not_found;
2766                                 em->len = extent_end - extent_start;
2767                         } else {
2768                                 em->len = len;
2769                         }
2770                         goto not_found_em;
2771                 }
2772                 em->block_start = EXTENT_MAP_INLINE;
2773
2774                 if (!page) {
2775                         em->start = extent_start;
2776                         em->len = size;
2777                         goto out;
2778                 }
2779
2780                 page_start = page_offset(page) + pg_offset;
2781                 extent_offset = page_start - extent_start;
2782                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
2783                                 size - extent_offset);
2784                 em->start = extent_start + extent_offset;
2785                 em->len = (copy_size + root->sectorsize - 1) &
2786                         ~((u64)root->sectorsize - 1);
2787                 map = kmap(page);
2788                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
2789                 if (create == 0 && !PageUptodate(page)) {
2790                         read_extent_buffer(leaf, map + pg_offset, ptr,
2791                                            copy_size);
2792                         flush_dcache_page(page);
2793                 } else if (create && PageUptodate(page)) {
2794                         if (!trans) {
2795                                 kunmap(page);
2796                                 free_extent_map(em);
2797                                 em = NULL;
2798                                 btrfs_release_path(root, path);
2799                                 trans = btrfs_join_transaction(root, 1);
2800                                 goto again;
2801                         }
2802                         write_extent_buffer(leaf, map + pg_offset, ptr,
2803                                             copy_size);
2804                         btrfs_mark_buffer_dirty(leaf);
2805                 }
2806                 kunmap(page);
2807                 set_extent_uptodate(io_tree, em->start,
2808                                     extent_map_end(em) - 1, GFP_NOFS);
2809                 goto insert;
2810         } else {
2811                 printk("unkknown found_type %d\n", found_type);
2812                 WARN_ON(1);
2813         }
2814 not_found:
2815         em->start = start;
2816         em->len = len;
2817 not_found_em:
2818         em->block_start = EXTENT_MAP_HOLE;
2819 insert:
2820         btrfs_release_path(root, path);
2821         if (em->start > start || extent_map_end(em) <= start) {
2822                 printk("bad extent! em: [%Lu %Lu] passed [%Lu %Lu]\n", em->start, em->len, start, len);
2823                 err = -EIO;
2824                 goto out;
2825         }
2826
2827         err = 0;
2828         spin_lock(&em_tree->lock);
2829         ret = add_extent_mapping(em_tree, em);
2830         /* it is possible that someone inserted the extent into the tree
2831          * while we had the lock dropped.  It is also possible that
2832          * an overlapping map exists in the tree
2833          */
2834         if (ret == -EEXIST) {
2835                 struct extent_map *existing;
2836
2837                 ret = 0;
2838
2839                 existing = lookup_extent_mapping(em_tree, start, len);
2840                 if (existing && (existing->start > start ||
2841                     existing->start + existing->len <= start)) {
2842                         free_extent_map(existing);
2843                         existing = NULL;
2844                 }
2845                 if (!existing) {
2846                         existing = lookup_extent_mapping(em_tree, em->start,
2847                                                          em->len);
2848                         if (existing) {
2849                                 err = merge_extent_mapping(em_tree, existing,
2850                                                            em, start,
2851                                                            root->sectorsize);
2852                                 free_extent_map(existing);
2853                                 if (err) {
2854                                         free_extent_map(em);
2855                                         em = NULL;
2856                                 }
2857                         } else {
2858                                 err = -EIO;
2859                                 printk("failing to insert %Lu %Lu\n",
2860                                        start, len);
2861                                 free_extent_map(em);
2862                                 em = NULL;
2863                         }
2864                 } else {
2865                         free_extent_map(em);
2866                         em = existing;
2867                         err = 0;
2868                 }
2869         }
2870         spin_unlock(&em_tree->lock);
2871 out:
2872         if (path)
2873                 btrfs_free_path(path);
2874         if (trans) {
2875                 ret = btrfs_end_transaction(trans, root);
2876                 if (!err) {
2877                         err = ret;
2878                 }
2879         }
2880         if (err) {
2881                 free_extent_map(em);
2882                 WARN_ON(1);
2883                 return ERR_PTR(err);
2884         }
2885         return em;
2886 }
2887
2888 #if 0 /* waiting for O_DIRECT reads */
2889 static int btrfs_get_block(struct inode *inode, sector_t iblock,
2890                         struct buffer_head *bh_result, int create)
2891 {
2892         struct extent_map *em;
2893         u64 start = (u64)iblock << inode->i_blkbits;
2894         struct btrfs_multi_bio *multi = NULL;
2895         struct btrfs_root *root = BTRFS_I(inode)->root;
2896         u64 len;
2897         u64 logical;
2898         u64 map_length;
2899         int ret = 0;
2900
2901         em = btrfs_get_extent(inode, NULL, 0, start, bh_result->b_size, 0);
2902
2903         if (!em || IS_ERR(em))
2904                 goto out;
2905
2906         if (em->start > start || em->start + em->len <= start) {
2907             goto out;
2908         }
2909
2910         if (em->block_start == EXTENT_MAP_INLINE) {
2911                 ret = -EINVAL;
2912                 goto out;
2913         }
2914
2915         len = em->start + em->len - start;
2916         len = min_t(u64, len, INT_LIMIT(typeof(bh_result->b_size)));
2917
2918         if (em->block_start == EXTENT_MAP_HOLE ||
2919             em->block_start == EXTENT_MAP_DELALLOC) {
2920                 bh_result->b_size = len;
2921                 goto out;
2922         }
2923
2924         logical = start - em->start;
2925         logical = em->block_start + logical;
2926
2927         map_length = len;
2928         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
2929                               logical, &map_length, &multi, 0);
2930         BUG_ON(ret);
2931         bh_result->b_blocknr = multi->stripes[0].physical >> inode->i_blkbits;
2932         bh_result->b_size = min(map_length, len);
2933
2934         bh_result->b_bdev = multi->stripes[0].dev->bdev;
2935         set_buffer_mapped(bh_result);
2936         kfree(multi);
2937 out:
2938         free_extent_map(em);
2939         return ret;
2940 }
2941 #endif
2942
2943 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
2944                         const struct iovec *iov, loff_t offset,
2945                         unsigned long nr_segs)
2946 {
2947         return -EINVAL;
2948 #if 0
2949         struct file *file = iocb->ki_filp;
2950         struct inode *inode = file->f_mapping->host;
2951
2952         if (rw == WRITE)
2953                 return -EINVAL;
2954
2955         return blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
2956                                   offset, nr_segs, btrfs_get_block, NULL);
2957 #endif
2958 }
2959
2960 static sector_t btrfs_bmap(struct address_space *mapping, sector_t iblock)
2961 {
2962         return extent_bmap(mapping, iblock, btrfs_get_extent);
2963 }
2964
2965 int btrfs_readpage(struct file *file, struct page *page)
2966 {
2967         struct extent_io_tree *tree;
2968         tree = &BTRFS_I(page->mapping->host)->io_tree;
2969         return extent_read_full_page(tree, page, btrfs_get_extent);
2970 }
2971
2972 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
2973 {
2974         struct extent_io_tree *tree;
2975
2976
2977         if (current->flags & PF_MEMALLOC) {
2978                 redirty_page_for_writepage(wbc, page);
2979                 unlock_page(page);
2980                 return 0;
2981         }
2982         tree = &BTRFS_I(page->mapping->host)->io_tree;
2983         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
2984 }
2985
2986 int btrfs_writepages(struct address_space *mapping,
2987                      struct writeback_control *wbc)
2988 {
2989         struct extent_io_tree *tree;
2990         tree = &BTRFS_I(mapping->host)->io_tree;
2991         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
2992 }
2993
2994 static int
2995 btrfs_readpages(struct file *file, struct address_space *mapping,
2996                 struct list_head *pages, unsigned nr_pages)
2997 {
2998         struct extent_io_tree *tree;
2999         tree = &BTRFS_I(mapping->host)->io_tree;
3000         return extent_readpages(tree, mapping, pages, nr_pages,
3001                                 btrfs_get_extent);
3002 }
3003 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
3004 {
3005         struct extent_io_tree *tree;
3006         struct extent_map_tree *map;
3007         int ret;
3008
3009         tree = &BTRFS_I(page->mapping->host)->io_tree;
3010         map = &BTRFS_I(page->mapping->host)->extent_tree;
3011         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
3012         if (ret == 1) {
3013                 ClearPagePrivate(page);
3014                 set_page_private(page, 0);
3015                 page_cache_release(page);
3016         }
3017         return ret;
3018 }
3019
3020 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
3021 {
3022         return __btrfs_releasepage(page, gfp_flags);
3023 }
3024
3025 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
3026 {
3027         struct extent_io_tree *tree;
3028         struct btrfs_ordered_extent *ordered;
3029         u64 page_start = page_offset(page);
3030         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
3031
3032         wait_on_page_writeback(page);
3033         tree = &BTRFS_I(page->mapping->host)->io_tree;
3034         if (offset) {
3035                 btrfs_releasepage(page, GFP_NOFS);
3036                 return;
3037         }
3038
3039         lock_extent(tree, page_start, page_end, GFP_NOFS);
3040         ordered = btrfs_lookup_ordered_extent(page->mapping->host,
3041                                            page_offset(page));
3042         if (ordered) {
3043                 /*
3044                  * IO on this page will never be started, so we need
3045                  * to account for any ordered extents now
3046                  */
3047                 clear_extent_bit(tree, page_start, page_end,
3048                                  EXTENT_DIRTY | EXTENT_DELALLOC |
3049                                  EXTENT_LOCKED, 1, 0, GFP_NOFS);
3050                 btrfs_finish_ordered_io(page->mapping->host,
3051                                         page_start, page_end);
3052                 btrfs_put_ordered_extent(ordered);
3053                 lock_extent(tree, page_start, page_end, GFP_NOFS);
3054         }
3055         clear_extent_bit(tree, page_start, page_end,
3056                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
3057                  EXTENT_ORDERED,
3058                  1, 1, GFP_NOFS);
3059         __btrfs_releasepage(page, GFP_NOFS);
3060
3061         ClearPageChecked(page);
3062         if (PagePrivate(page)) {
3063                 ClearPagePrivate(page);
3064                 set_page_private(page, 0);
3065                 page_cache_release(page);
3066         }
3067 }
3068
3069 /*
3070  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
3071  * called from a page fault handler when a page is first dirtied. Hence we must
3072  * be careful to check for EOF conditions here. We set the page up correctly
3073  * for a written page which means we get ENOSPC checking when writing into
3074  * holes and correct delalloc and unwritten extent mapping on filesystems that
3075  * support these features.
3076  *
3077  * We are not allowed to take the i_mutex here so we have to play games to
3078  * protect against truncate races as the page could now be beyond EOF.  Because
3079  * vmtruncate() writes the inode size before removing pages, once we have the
3080  * page lock we can determine safely if the page is beyond EOF. If it is not
3081  * beyond EOF, then the page is guaranteed safe against truncation until we
3082  * unlock the page.
3083  */
3084 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct page *page)
3085 {
3086         struct inode *inode = fdentry(vma->vm_file)->d_inode;
3087         struct btrfs_root *root = BTRFS_I(inode)->root;
3088         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3089         struct btrfs_ordered_extent *ordered;
3090         char *kaddr;
3091         unsigned long zero_start;
3092         loff_t size;
3093         int ret;
3094         u64 page_start;
3095         u64 page_end;
3096
3097         ret = btrfs_check_free_space(root, PAGE_CACHE_SIZE, 0);
3098         if (ret)
3099                 goto out;
3100
3101         ret = -EINVAL;
3102 again:
3103         lock_page(page);
3104         size = i_size_read(inode);
3105         page_start = page_offset(page);
3106         page_end = page_start + PAGE_CACHE_SIZE - 1;
3107
3108         if ((page->mapping != inode->i_mapping) ||
3109             (page_start >= size)) {
3110                 /* page got truncated out from underneath us */
3111                 goto out_unlock;
3112         }
3113         wait_on_page_writeback(page);
3114
3115         lock_extent(io_tree, page_start, page_end, GFP_NOFS);
3116         set_page_extent_mapped(page);
3117
3118         /*
3119          * we can't set the delalloc bits if there are pending ordered
3120          * extents.  Drop our locks and wait for them to finish
3121          */
3122         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3123         if (ordered) {
3124                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3125                 unlock_page(page);
3126                 btrfs_start_ordered_extent(inode, ordered, 1);
3127                 btrfs_put_ordered_extent(ordered);
3128                 goto again;
3129         }
3130
3131         set_extent_delalloc(&BTRFS_I(inode)->io_tree, page_start,
3132                             page_end, GFP_NOFS);
3133         ret = 0;
3134
3135         /* page is wholly or partially inside EOF */
3136         if (page_start + PAGE_CACHE_SIZE > size)
3137                 zero_start = size & ~PAGE_CACHE_MASK;
3138         else
3139                 zero_start = PAGE_CACHE_SIZE;
3140
3141         if (zero_start != PAGE_CACHE_SIZE) {
3142                 kaddr = kmap(page);
3143                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
3144                 flush_dcache_page(page);
3145                 kunmap(page);
3146         }
3147         ClearPageChecked(page);
3148         set_page_dirty(page);
3149         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3150
3151 out_unlock:
3152         unlock_page(page);
3153 out:
3154         return ret;
3155 }
3156
3157 static void btrfs_truncate(struct inode *inode)
3158 {
3159         struct btrfs_root *root = BTRFS_I(inode)->root;
3160         int ret;
3161         struct btrfs_trans_handle *trans;
3162         unsigned long nr;
3163         u64 mask = root->sectorsize - 1;
3164
3165         if (!S_ISREG(inode->i_mode))
3166                 return;
3167         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
3168                 return;
3169
3170         btrfs_truncate_page(inode->i_mapping, inode->i_size);
3171         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
3172
3173         trans = btrfs_start_transaction(root, 1);
3174         btrfs_set_trans_block_group(trans, inode);
3175         btrfs_i_size_write(inode, inode->i_size);
3176
3177         ret = btrfs_orphan_add(trans, inode);
3178         if (ret)
3179                 goto out;
3180         /* FIXME, add redo link to tree so we don't leak on crash */
3181         ret = btrfs_truncate_in_trans(trans, root, inode,
3182                                       BTRFS_EXTENT_DATA_KEY);
3183         btrfs_update_inode(trans, root, inode);
3184
3185         ret = btrfs_orphan_del(trans, inode);
3186         BUG_ON(ret);
3187
3188 out:
3189         nr = trans->blocks_used;
3190         ret = btrfs_end_transaction_throttle(trans, root);
3191         BUG_ON(ret);
3192         btrfs_btree_balance_dirty(root, nr);
3193 }
3194
3195 /*
3196  * Invalidate a single dcache entry at the root of the filesystem.
3197  * Needed after creation of snapshot or subvolume.
3198  */
3199 void btrfs_invalidate_dcache_root(struct btrfs_root *root, char *name,
3200                                   int namelen)
3201 {
3202         struct dentry *alias, *entry;
3203         struct qstr qstr;
3204
3205         alias = d_find_alias(root->fs_info->sb->s_root->d_inode);
3206         if (alias) {
3207                 qstr.name = name;
3208                 qstr.len = namelen;
3209                 /* change me if btrfs ever gets a d_hash operation */
3210                 qstr.hash = full_name_hash(qstr.name, qstr.len);
3211                 entry = d_lookup(alias, &qstr);
3212                 dput(alias);
3213                 if (entry) {
3214                         d_invalidate(entry);
3215                         dput(entry);
3216                 }
3217         }
3218 }
3219
3220 int btrfs_create_subvol_root(struct btrfs_root *new_root,
3221                 struct btrfs_trans_handle *trans, u64 new_dirid,
3222                 struct btrfs_block_group_cache *block_group)
3223 {
3224         struct inode *inode;
3225
3226         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
3227                                 new_dirid, block_group, S_IFDIR | 0700);
3228         if (IS_ERR(inode))
3229                 return PTR_ERR(inode);
3230         inode->i_op = &btrfs_dir_inode_operations;
3231         inode->i_fop = &btrfs_dir_file_operations;
3232         new_root->inode = inode;
3233
3234         inode->i_nlink = 1;
3235         btrfs_i_size_write(inode, 0);
3236
3237         return btrfs_update_inode(trans, new_root, inode);
3238 }
3239
3240 unsigned long btrfs_force_ra(struct address_space *mapping,
3241                               struct file_ra_state *ra, struct file *file,
3242                               pgoff_t offset, pgoff_t last_index)
3243 {
3244         pgoff_t req_size = last_index - offset + 1;
3245
3246 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
3247         offset = page_cache_readahead(mapping, ra, file, offset, req_size);
3248         return offset;
3249 #else
3250         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
3251         return offset + req_size;
3252 #endif
3253 }
3254
3255 struct inode *btrfs_alloc_inode(struct super_block *sb)
3256 {
3257         struct btrfs_inode *ei;
3258
3259         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
3260         if (!ei)
3261                 return NULL;
3262         ei->last_trans = 0;
3263         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
3264         ei->i_acl = BTRFS_ACL_NOT_CACHED;
3265         ei->i_default_acl = BTRFS_ACL_NOT_CACHED;
3266         INIT_LIST_HEAD(&ei->i_orphan);
3267         return &ei->vfs_inode;
3268 }
3269
3270 void btrfs_destroy_inode(struct inode *inode)
3271 {
3272         struct btrfs_ordered_extent *ordered;
3273         WARN_ON(!list_empty(&inode->i_dentry));
3274         WARN_ON(inode->i_data.nrpages);
3275
3276         if (BTRFS_I(inode)->i_acl &&
3277             BTRFS_I(inode)->i_acl != BTRFS_ACL_NOT_CACHED)
3278                 posix_acl_release(BTRFS_I(inode)->i_acl);
3279         if (BTRFS_I(inode)->i_default_acl &&
3280             BTRFS_I(inode)->i_default_acl != BTRFS_ACL_NOT_CACHED)
3281                 posix_acl_release(BTRFS_I(inode)->i_default_acl);
3282
3283         spin_lock(&BTRFS_I(inode)->root->orphan_lock);
3284         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
3285                 printk(KERN_ERR "BTRFS: inode %lu: inode still on the orphan"
3286                        " list\n", inode->i_ino);
3287                 dump_stack();
3288         }
3289         spin_unlock(&BTRFS_I(inode)->root->orphan_lock);
3290
3291         while(1) {
3292                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
3293                 if (!ordered)
3294                         break;
3295                 else {
3296                         printk("found ordered extent %Lu %Lu\n",
3297                                ordered->file_offset, ordered->len);
3298                         btrfs_remove_ordered_extent(inode, ordered);
3299                         btrfs_put_ordered_extent(ordered);
3300                         btrfs_put_ordered_extent(ordered);
3301                 }
3302         }
3303         btrfs_drop_extent_cache(inode, 0, (u64)-1);
3304         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
3305 }
3306
3307 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
3308 static void init_once(struct kmem_cache * cachep, void *foo)
3309 #else
3310 static void init_once(void * foo, struct kmem_cache * cachep,
3311                       unsigned long flags)
3312 #endif
3313 {
3314         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
3315
3316         inode_init_once(&ei->vfs_inode);
3317 }
3318
3319 void btrfs_destroy_cachep(void)
3320 {
3321         if (btrfs_inode_cachep)
3322                 kmem_cache_destroy(btrfs_inode_cachep);
3323         if (btrfs_trans_handle_cachep)
3324                 kmem_cache_destroy(btrfs_trans_handle_cachep);
3325         if (btrfs_transaction_cachep)
3326                 kmem_cache_destroy(btrfs_transaction_cachep);
3327         if (btrfs_bit_radix_cachep)
3328                 kmem_cache_destroy(btrfs_bit_radix_cachep);
3329         if (btrfs_path_cachep)
3330                 kmem_cache_destroy(btrfs_path_cachep);
3331 }
3332
3333 struct kmem_cache *btrfs_cache_create(const char *name, size_t size,
3334                                        unsigned long extra_flags,
3335 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
3336                                        void (*ctor)(struct kmem_cache *, void *)
3337 #else
3338                                        void (*ctor)(void *, struct kmem_cache *,
3339                                                     unsigned long)
3340 #endif
3341                                      )
3342 {
3343         return kmem_cache_create(name, size, 0, (SLAB_RECLAIM_ACCOUNT |
3344                                  SLAB_MEM_SPREAD | extra_flags), ctor
3345 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
3346                                  ,NULL
3347 #endif
3348                                 );
3349 }
3350
3351 int btrfs_init_cachep(void)
3352 {
3353         btrfs_inode_cachep = btrfs_cache_create("btrfs_inode_cache",
3354                                           sizeof(struct btrfs_inode),
3355                                           0, init_once);
3356         if (!btrfs_inode_cachep)
3357                 goto fail;
3358         btrfs_trans_handle_cachep =
3359                         btrfs_cache_create("btrfs_trans_handle_cache",
3360                                            sizeof(struct btrfs_trans_handle),
3361                                            0, NULL);
3362         if (!btrfs_trans_handle_cachep)
3363                 goto fail;
3364         btrfs_transaction_cachep = btrfs_cache_create("btrfs_transaction_cache",
3365                                              sizeof(struct btrfs_transaction),
3366                                              0, NULL);
3367         if (!btrfs_transaction_cachep)
3368                 goto fail;
3369         btrfs_path_cachep = btrfs_cache_create("btrfs_path_cache",
3370                                          sizeof(struct btrfs_path),
3371                                          0, NULL);
3372         if (!btrfs_path_cachep)
3373                 goto fail;
3374         btrfs_bit_radix_cachep = btrfs_cache_create("btrfs_radix", 256,
3375                                               SLAB_DESTROY_BY_RCU, NULL);
3376         if (!btrfs_bit_radix_cachep)
3377                 goto fail;
3378         return 0;
3379 fail:
3380         btrfs_destroy_cachep();
3381         return -ENOMEM;
3382 }
3383
3384 static int btrfs_getattr(struct vfsmount *mnt,
3385                          struct dentry *dentry, struct kstat *stat)
3386 {
3387         struct inode *inode = dentry->d_inode;
3388         generic_fillattr(inode, stat);
3389         stat->blksize = PAGE_CACHE_SIZE;
3390         stat->blocks = inode->i_blocks + (BTRFS_I(inode)->delalloc_bytes >> 9);
3391         return 0;
3392 }
3393
3394 static int btrfs_rename(struct inode * old_dir, struct dentry *old_dentry,
3395                            struct inode * new_dir,struct dentry *new_dentry)
3396 {
3397         struct btrfs_trans_handle *trans;
3398         struct btrfs_root *root = BTRFS_I(old_dir)->root;
3399         struct inode *new_inode = new_dentry->d_inode;
3400         struct inode *old_inode = old_dentry->d_inode;
3401         struct timespec ctime = CURRENT_TIME;
3402         int ret;
3403
3404         if (S_ISDIR(old_inode->i_mode) && new_inode &&
3405             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
3406                 return -ENOTEMPTY;
3407         }
3408
3409         ret = btrfs_check_free_space(root, 1, 0);
3410         if (ret)
3411                 goto out_unlock;
3412
3413         trans = btrfs_start_transaction(root, 1);
3414
3415         btrfs_set_trans_block_group(trans, new_dir);
3416
3417         old_dentry->d_inode->i_nlink++;
3418         old_dir->i_ctime = old_dir->i_mtime = ctime;
3419         new_dir->i_ctime = new_dir->i_mtime = ctime;
3420         old_inode->i_ctime = ctime;
3421
3422         ret = btrfs_unlink_trans(trans, root, old_dir, old_dentry);
3423         if (ret)
3424                 goto out_fail;
3425
3426         if (new_inode) {
3427                 new_inode->i_ctime = CURRENT_TIME;
3428                 ret = btrfs_unlink_trans(trans, root, new_dir, new_dentry);
3429                 if (ret)
3430                         goto out_fail;
3431                 if (new_inode->i_nlink == 0) {
3432                         ret = btrfs_orphan_add(trans, new_inode);
3433                         if (ret)
3434                                 goto out_fail;
3435                 }
3436         }
3437         ret = btrfs_set_inode_index(new_dir, old_inode);
3438         if (ret)
3439                 goto out_fail;
3440
3441         ret = btrfs_add_link(trans, new_dentry, old_inode, 1);
3442         if (ret)
3443                 goto out_fail;
3444
3445 out_fail:
3446         btrfs_end_transaction(trans, root);
3447 out_unlock:
3448         return ret;
3449 }
3450
3451 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
3452                          const char *symname)
3453 {
3454         struct btrfs_trans_handle *trans;
3455         struct btrfs_root *root = BTRFS_I(dir)->root;
3456         struct btrfs_path *path;
3457         struct btrfs_key key;
3458         struct inode *inode = NULL;
3459         int err;
3460         int drop_inode = 0;
3461         u64 objectid;
3462         int name_len;
3463         int datasize;
3464         unsigned long ptr;
3465         struct btrfs_file_extent_item *ei;
3466         struct extent_buffer *leaf;
3467         unsigned long nr = 0;
3468
3469         name_len = strlen(symname) + 1;
3470         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
3471                 return -ENAMETOOLONG;
3472
3473         err = btrfs_check_free_space(root, 1, 0);
3474         if (err)
3475                 goto out_fail;
3476
3477         trans = btrfs_start_transaction(root, 1);
3478         btrfs_set_trans_block_group(trans, dir);
3479
3480         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3481         if (err) {
3482                 err = -ENOSPC;
3483                 goto out_unlock;
3484         }
3485
3486         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
3487                                 dentry->d_name.len,
3488                                 dentry->d_parent->d_inode->i_ino, objectid,
3489                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO);
3490         err = PTR_ERR(inode);
3491         if (IS_ERR(inode))
3492                 goto out_unlock;
3493
3494         err = btrfs_init_acl(inode, dir);
3495         if (err) {
3496                 drop_inode = 1;
3497                 goto out_unlock;
3498         }
3499
3500         btrfs_set_trans_block_group(trans, inode);
3501         err = btrfs_add_nondir(trans, dentry, inode, 0);
3502         if (err)
3503                 drop_inode = 1;
3504         else {
3505                 inode->i_mapping->a_ops = &btrfs_aops;
3506                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3507                 inode->i_fop = &btrfs_file_operations;
3508                 inode->i_op = &btrfs_file_inode_operations;
3509                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
3510                 extent_io_tree_init(&BTRFS_I(inode)->io_tree,
3511                                      inode->i_mapping, GFP_NOFS);
3512                 extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
3513                                      inode->i_mapping, GFP_NOFS);
3514                 mutex_init(&BTRFS_I(inode)->csum_mutex);
3515                 mutex_init(&BTRFS_I(inode)->extent_mutex);
3516                 BTRFS_I(inode)->delalloc_bytes = 0;
3517                 BTRFS_I(inode)->disk_i_size = 0;
3518                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3519                 btrfs_ordered_inode_tree_init(&BTRFS_I(inode)->ordered_tree);
3520         }
3521         dir->i_sb->s_dirt = 1;
3522         btrfs_update_inode_block_group(trans, inode);
3523         btrfs_update_inode_block_group(trans, dir);
3524         if (drop_inode)
3525                 goto out_unlock;
3526
3527         path = btrfs_alloc_path();
3528         BUG_ON(!path);
3529         key.objectid = inode->i_ino;
3530         key.offset = 0;
3531         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
3532         datasize = btrfs_file_extent_calc_inline_size(name_len);
3533         err = btrfs_insert_empty_item(trans, root, path, &key,
3534                                       datasize);
3535         if (err) {
3536                 drop_inode = 1;
3537                 goto out_unlock;
3538         }
3539         leaf = path->nodes[0];
3540         ei = btrfs_item_ptr(leaf, path->slots[0],
3541                             struct btrfs_file_extent_item);
3542         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
3543         btrfs_set_file_extent_type(leaf, ei,
3544                                    BTRFS_FILE_EXTENT_INLINE);
3545         ptr = btrfs_file_extent_inline_start(ei);
3546         write_extent_buffer(leaf, symname, ptr, name_len);
3547         btrfs_mark_buffer_dirty(leaf);
3548         btrfs_free_path(path);
3549
3550         inode->i_op = &btrfs_symlink_inode_operations;
3551         inode->i_mapping->a_ops = &btrfs_symlink_aops;
3552         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3553         btrfs_i_size_write(inode, name_len - 1);
3554         err = btrfs_update_inode(trans, root, inode);
3555         if (err)
3556                 drop_inode = 1;
3557
3558 out_unlock:
3559         nr = trans->blocks_used;
3560         btrfs_end_transaction_throttle(trans, root);
3561 out_fail:
3562         if (drop_inode) {
3563                 inode_dec_link_count(inode);
3564                 iput(inode);
3565         }
3566         btrfs_btree_balance_dirty(root, nr);
3567         return err;
3568 }
3569
3570 static int btrfs_set_page_dirty(struct page *page)
3571 {
3572         return __set_page_dirty_nobuffers(page);
3573 }
3574
3575 static int btrfs_permission(struct inode *inode, int mask,
3576                             struct nameidata *nd)
3577 {
3578         if (btrfs_test_flag(inode, READONLY) && (mask & MAY_WRITE))
3579                 return -EACCES;
3580         return generic_permission(inode, mask, btrfs_check_acl);
3581 }
3582
3583 static struct inode_operations btrfs_dir_inode_operations = {
3584         .lookup         = btrfs_lookup,
3585         .create         = btrfs_create,
3586         .unlink         = btrfs_unlink,
3587         .link           = btrfs_link,
3588         .mkdir          = btrfs_mkdir,
3589         .rmdir          = btrfs_rmdir,
3590         .rename         = btrfs_rename,
3591         .symlink        = btrfs_symlink,
3592         .setattr        = btrfs_setattr,
3593         .mknod          = btrfs_mknod,
3594         .setxattr       = generic_setxattr,
3595         .getxattr       = generic_getxattr,
3596         .listxattr      = btrfs_listxattr,
3597         .removexattr    = generic_removexattr,
3598         .permission     = btrfs_permission,
3599 };
3600 static struct inode_operations btrfs_dir_ro_inode_operations = {
3601         .lookup         = btrfs_lookup,
3602         .permission     = btrfs_permission,
3603 };
3604 static struct file_operations btrfs_dir_file_operations = {
3605         .llseek         = generic_file_llseek,
3606         .read           = generic_read_dir,
3607         .readdir        = btrfs_readdir,
3608         .unlocked_ioctl = btrfs_ioctl,
3609 #ifdef CONFIG_COMPAT
3610         .compat_ioctl   = btrfs_ioctl,
3611 #endif
3612         .release        = btrfs_release_file,
3613 };
3614
3615 static struct extent_io_ops btrfs_extent_io_ops = {
3616         .fill_delalloc = run_delalloc_range,
3617         .submit_bio_hook = btrfs_submit_bio_hook,
3618         .merge_bio_hook = btrfs_merge_bio_hook,
3619         .readpage_io_hook = btrfs_readpage_io_hook,
3620         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
3621         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
3622         .writepage_start_hook = btrfs_writepage_start_hook,
3623         .readpage_io_failed_hook = btrfs_io_failed_hook,
3624         .set_bit_hook = btrfs_set_bit_hook,
3625         .clear_bit_hook = btrfs_clear_bit_hook,
3626 };
3627
3628 static struct address_space_operations btrfs_aops = {
3629         .readpage       = btrfs_readpage,
3630         .writepage      = btrfs_writepage,
3631         .writepages     = btrfs_writepages,
3632         .readpages      = btrfs_readpages,
3633         .sync_page      = block_sync_page,
3634         .bmap           = btrfs_bmap,
3635         .direct_IO      = btrfs_direct_IO,
3636         .invalidatepage = btrfs_invalidatepage,
3637         .releasepage    = btrfs_releasepage,
3638         .set_page_dirty = btrfs_set_page_dirty,
3639 };
3640
3641 static struct address_space_operations btrfs_symlink_aops = {
3642         .readpage       = btrfs_readpage,
3643         .writepage      = btrfs_writepage,
3644         .invalidatepage = btrfs_invalidatepage,
3645         .releasepage    = btrfs_releasepage,
3646 };
3647
3648 static struct inode_operations btrfs_file_inode_operations = {
3649         .truncate       = btrfs_truncate,
3650         .getattr        = btrfs_getattr,
3651         .setattr        = btrfs_setattr,
3652         .setxattr       = generic_setxattr,
3653         .getxattr       = generic_getxattr,
3654         .listxattr      = btrfs_listxattr,
3655         .removexattr    = generic_removexattr,
3656         .permission     = btrfs_permission,
3657 };
3658 static struct inode_operations btrfs_special_inode_operations = {
3659         .getattr        = btrfs_getattr,
3660         .setattr        = btrfs_setattr,
3661         .permission     = btrfs_permission,
3662         .setxattr       = generic_setxattr,
3663         .getxattr       = generic_getxattr,
3664         .listxattr      = btrfs_listxattr,
3665         .removexattr    = generic_removexattr,
3666 };
3667 static struct inode_operations btrfs_symlink_inode_operations = {
3668         .readlink       = generic_readlink,
3669         .follow_link    = page_follow_link_light,
3670         .put_link       = page_put_link,
3671         .permission     = btrfs_permission,
3672 };