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