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