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