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