]> Pileus Git - ~andy/linux/blob - fs/btrfs/inode.c
Btrfs: Fix bookend extent race v2
[~andy/linux] / 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 #include "xattr.h"
49 #include "compat.h"
50 #include "tree-log.h"
51 #include "ref-cache.h"
52 #include "compression.h"
53
54 struct btrfs_iget_args {
55         u64 ino;
56         struct btrfs_root *root;
57 };
58
59 static struct inode_operations btrfs_dir_inode_operations;
60 static struct inode_operations btrfs_symlink_inode_operations;
61 static struct inode_operations btrfs_dir_ro_inode_operations;
62 static struct inode_operations btrfs_special_inode_operations;
63 static struct inode_operations btrfs_file_inode_operations;
64 static struct address_space_operations btrfs_aops;
65 static struct address_space_operations btrfs_symlink_aops;
66 static struct file_operations btrfs_dir_file_operations;
67 static struct extent_io_ops btrfs_extent_io_ops;
68
69 static struct kmem_cache *btrfs_inode_cachep;
70 struct kmem_cache *btrfs_trans_handle_cachep;
71 struct kmem_cache *btrfs_transaction_cachep;
72 struct kmem_cache *btrfs_bit_radix_cachep;
73 struct kmem_cache *btrfs_path_cachep;
74
75 #define S_SHIFT 12
76 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
77         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
78         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
79         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
80         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
81         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
82         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
83         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
84 };
85
86 static void btrfs_truncate(struct inode *inode);
87 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
88
89 /*
90  * a very lame attempt at stopping writes when the FS is 85% full.  There
91  * are countless ways this is incorrect, but it is better than nothing.
92  */
93 int btrfs_check_free_space(struct btrfs_root *root, u64 num_required,
94                            int for_del)
95 {
96         u64 total;
97         u64 used;
98         u64 thresh;
99         unsigned long flags;
100         int ret = 0;
101
102         spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
103         total = btrfs_super_total_bytes(&root->fs_info->super_copy);
104         used = btrfs_super_bytes_used(&root->fs_info->super_copy);
105         if (for_del)
106                 thresh = total * 90;
107         else
108                 thresh = total * 85;
109
110         do_div(thresh, 100);
111
112         if (used + root->fs_info->delalloc_bytes + num_required > thresh)
113                 ret = -ENOSPC;
114         spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
115         return ret;
116 }
117
118 /*
119  * this does all the hard work for inserting an inline extent into
120  * the btree.  The caller should have done a btrfs_drop_extents so that
121  * no overlapping inline items exist in the btree
122  */
123 static int noinline insert_inline_extent(struct btrfs_trans_handle *trans,
124                                 struct btrfs_root *root, struct inode *inode,
125                                 u64 start, size_t size, size_t compressed_size,
126                                 struct page **compressed_pages)
127 {
128         struct btrfs_key key;
129         struct btrfs_path *path;
130         struct extent_buffer *leaf;
131         struct page *page = NULL;
132         char *kaddr;
133         unsigned long ptr;
134         struct btrfs_file_extent_item *ei;
135         int err = 0;
136         int ret;
137         size_t cur_size = size;
138         size_t datasize;
139         unsigned long offset;
140         int use_compress = 0;
141
142         if (compressed_size && compressed_pages) {
143                 use_compress = 1;
144                 cur_size = compressed_size;
145         }
146
147         path = btrfs_alloc_path(); if (!path)
148                 return -ENOMEM;
149
150         btrfs_set_trans_block_group(trans, inode);
151
152         key.objectid = inode->i_ino;
153         key.offset = start;
154         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
155         inode_add_bytes(inode, size);
156         datasize = btrfs_file_extent_calc_inline_size(cur_size);
157
158         inode_add_bytes(inode, size);
159         ret = btrfs_insert_empty_item(trans, root, path, &key,
160                                       datasize);
161         BUG_ON(ret);
162         if (ret) {
163                 err = ret;
164                 printk("got bad ret %d\n", ret);
165                 goto fail;
166         }
167         leaf = path->nodes[0];
168         ei = btrfs_item_ptr(leaf, path->slots[0],
169                             struct btrfs_file_extent_item);
170         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
171         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
172         btrfs_set_file_extent_encryption(leaf, ei, 0);
173         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
174         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
175         ptr = btrfs_file_extent_inline_start(ei);
176
177         if (use_compress) {
178                 struct page *cpage;
179                 int i = 0;
180                 while(compressed_size > 0) {
181                         cpage = compressed_pages[i];
182                         cur_size = min(compressed_size,
183                                        PAGE_CACHE_SIZE);
184
185                         kaddr = kmap(cpage);
186                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
187                         kunmap(cpage);
188
189                         i++;
190                         ptr += cur_size;
191                         compressed_size -= cur_size;
192                 }
193                 btrfs_set_file_extent_compression(leaf, ei,
194                                                   BTRFS_COMPRESS_ZLIB);
195         } else {
196                 page = find_get_page(inode->i_mapping,
197                                      start >> PAGE_CACHE_SHIFT);
198                 btrfs_set_file_extent_compression(leaf, ei, 0);
199                 kaddr = kmap_atomic(page, KM_USER0);
200                 offset = start & (PAGE_CACHE_SIZE - 1);
201                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
202                 kunmap_atomic(kaddr, KM_USER0);
203                 page_cache_release(page);
204         }
205         btrfs_mark_buffer_dirty(leaf);
206         btrfs_free_path(path);
207
208         BTRFS_I(inode)->disk_i_size = inode->i_size;
209         btrfs_update_inode(trans, root, inode);
210         return 0;
211 fail:
212         btrfs_free_path(path);
213         return err;
214 }
215
216
217 /*
218  * conditionally insert an inline extent into the file.  This
219  * does the checks required to make sure the data is small enough
220  * to fit as an inline extent.
221  */
222 static int cow_file_range_inline(struct btrfs_trans_handle *trans,
223                                  struct btrfs_root *root,
224                                  struct inode *inode, u64 start, u64 end,
225                                  size_t compressed_size,
226                                  struct page **compressed_pages)
227 {
228         u64 isize = i_size_read(inode);
229         u64 actual_end = min(end + 1, isize);
230         u64 inline_len = actual_end - start;
231         u64 aligned_end = (end + root->sectorsize - 1) &
232                         ~((u64)root->sectorsize - 1);
233         u64 hint_byte;
234         u64 data_len = inline_len;
235         int ret;
236
237         if (compressed_size)
238                 data_len = compressed_size;
239
240         if (start > 0 ||
241             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
242             (!compressed_size &&
243             (actual_end & (root->sectorsize - 1)) == 0) ||
244             end + 1 < isize ||
245             data_len > root->fs_info->max_inline) {
246                 return 1;
247         }
248
249         ret = btrfs_drop_extents(trans, root, inode, start,
250                                  aligned_end, aligned_end, &hint_byte);
251         BUG_ON(ret);
252
253         if (isize > actual_end)
254                 inline_len = min_t(u64, isize, actual_end);
255         ret = insert_inline_extent(trans, root, inode, start,
256                                    inline_len, compressed_size,
257                                    compressed_pages);
258         BUG_ON(ret);
259         btrfs_drop_extent_cache(inode, start, aligned_end, 0);
260         return 0;
261 }
262
263 /*
264  * when extent_io.c finds a delayed allocation range in the file,
265  * the call backs end up in this code.  The basic idea is to
266  * allocate extents on disk for the range, and create ordered data structs
267  * in ram to track those extents.
268  *
269  * locked_page is the page that writepage had locked already.  We use
270  * it to make sure we don't do extra locks or unlocks.
271  *
272  * *page_started is set to one if we unlock locked_page and do everything
273  * required to start IO on it.  It may be clean and already done with
274  * IO when we return.
275  */
276 static int cow_file_range(struct inode *inode, struct page *locked_page,
277                           u64 start, u64 end, int *page_started)
278 {
279         struct btrfs_root *root = BTRFS_I(inode)->root;
280         struct btrfs_trans_handle *trans;
281         u64 alloc_hint = 0;
282         u64 num_bytes;
283         unsigned long ram_size;
284         u64 orig_start;
285         u64 disk_num_bytes;
286         u64 cur_alloc_size;
287         u64 blocksize = root->sectorsize;
288         u64 actual_end;
289         struct btrfs_key ins;
290         struct extent_map *em;
291         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
292         int ret = 0;
293         struct page **pages = NULL;
294         unsigned long nr_pages;
295         unsigned long nr_pages_ret = 0;
296         unsigned long total_compressed = 0;
297         unsigned long total_in = 0;
298         unsigned long max_compressed = 128 * 1024;
299         unsigned long max_uncompressed = 256 * 1024;
300         int i;
301         int will_compress;
302
303         trans = btrfs_join_transaction(root, 1);
304         BUG_ON(!trans);
305         btrfs_set_trans_block_group(trans, inode);
306         orig_start = start;
307
308         /*
309          * compression made this loop a bit ugly, but the basic idea is to
310          * compress some pages but keep the total size of the compressed
311          * extent relatively small.  If compression is off, this goto target
312          * is never used.
313          */
314 again:
315         will_compress = 0;
316         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
317         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
318
319         actual_end = min_t(u64, i_size_read(inode), end + 1);
320         total_compressed = actual_end - start;
321
322         /* we want to make sure that amount of ram required to uncompress
323          * an extent is reasonable, so we limit the total size in ram
324          * of a compressed extent to 256k
325          */
326         total_compressed = min(total_compressed, max_uncompressed);
327         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
328         num_bytes = max(blocksize,  num_bytes);
329         disk_num_bytes = num_bytes;
330         total_in = 0;
331         ret = 0;
332
333         /* we do compression for mount -o compress and when the
334          * inode has not been flagged as nocompress
335          */
336         if (!btrfs_test_flag(inode, NOCOMPRESS) &&
337             btrfs_test_opt(root, COMPRESS)) {
338                 WARN_ON(pages);
339                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
340
341                 /* we want to make sure the amount of IO required to satisfy
342                  * a random read is reasonably small, so we limit the size
343                  * of a compressed extent to 128k
344                  */
345                 ret = btrfs_zlib_compress_pages(inode->i_mapping, start,
346                                                 total_compressed, pages,
347                                                 nr_pages, &nr_pages_ret,
348                                                 &total_in,
349                                                 &total_compressed,
350                                                 max_compressed);
351
352                 if (!ret) {
353                         unsigned long offset = total_compressed &
354                                 (PAGE_CACHE_SIZE - 1);
355                         struct page *page = pages[nr_pages_ret - 1];
356                         char *kaddr;
357
358                         /* zero the tail end of the last page, we might be
359                          * sending it down to disk
360                          */
361                         if (offset) {
362                                 kaddr = kmap_atomic(page, KM_USER0);
363                                 memset(kaddr + offset, 0,
364                                        PAGE_CACHE_SIZE - offset);
365                                 kunmap_atomic(kaddr, KM_USER0);
366                         }
367                         will_compress = 1;
368                 }
369         }
370         if (start == 0) {
371                 /* lets try to make an inline extent */
372                 if (ret || total_in < (end - start + 1)) {
373                         /* we didn't compress the entire range, try
374                          * to make an uncompressed inline extent.  This
375                          * is almost sure to fail, but maybe inline sizes
376                          * will get bigger later
377                          */
378                         ret = cow_file_range_inline(trans, root, inode,
379                                                     start, end, 0, NULL);
380                 } else {
381                         ret = cow_file_range_inline(trans, root, inode,
382                                                     start, end,
383                                                     total_compressed, pages);
384                 }
385                 if (ret == 0) {
386                         extent_clear_unlock_delalloc(inode,
387                                                      &BTRFS_I(inode)->io_tree,
388                                                      start, end, NULL,
389                                                      1, 1, 1);
390                         *page_started = 1;
391                         ret = 0;
392                         goto free_pages_out;
393                 }
394         }
395
396         if (will_compress) {
397                 /*
398                  * we aren't doing an inline extent round the compressed size
399                  * up to a block size boundary so the allocator does sane
400                  * things
401                  */
402                 total_compressed = (total_compressed + blocksize - 1) &
403                         ~(blocksize - 1);
404
405                 /*
406                  * one last check to make sure the compression is really a
407                  * win, compare the page count read with the blocks on disk
408                  */
409                 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
410                         ~(PAGE_CACHE_SIZE - 1);
411                 if (total_compressed >= total_in) {
412                         will_compress = 0;
413                 } else {
414                         disk_num_bytes = total_compressed;
415                         num_bytes = total_in;
416                 }
417         }
418         if (!will_compress && pages) {
419                 /*
420                  * the compression code ran but failed to make things smaller,
421                  * free any pages it allocated and our page pointer array
422                  */
423                 for (i = 0; i < nr_pages_ret; i++) {
424                         page_cache_release(pages[i]);
425                 }
426                 kfree(pages);
427                 pages = NULL;
428                 total_compressed = 0;
429                 nr_pages_ret = 0;
430
431                 /* flag the file so we don't compress in the future */
432                 btrfs_set_flag(inode, NOCOMPRESS);
433         }
434
435         BUG_ON(disk_num_bytes >
436                btrfs_super_total_bytes(&root->fs_info->super_copy));
437
438         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
439
440         while(disk_num_bytes > 0) {
441                 unsigned long min_bytes;
442
443                 /*
444                  * the max size of a compressed extent is pretty small,
445                  * make the code a little less complex by forcing
446                  * the allocator to find a whole compressed extent at once
447                  */
448                 if (will_compress)
449                         min_bytes = disk_num_bytes;
450                 else
451                         min_bytes = root->sectorsize;
452
453                 cur_alloc_size = min(disk_num_bytes, root->fs_info->max_extent);
454                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
455                                            min_bytes, 0, alloc_hint,
456                                            (u64)-1, &ins, 1);
457                 if (ret) {
458                         WARN_ON(1);
459                         goto free_pages_out_fail;
460                 }
461                 em = alloc_extent_map(GFP_NOFS);
462                 em->start = start;
463
464                 if (will_compress) {
465                         ram_size = num_bytes;
466                         em->len = num_bytes;
467                 } else {
468                         /* ramsize == disk size */
469                         ram_size = ins.offset;
470                         em->len = ins.offset;
471                 }
472
473                 em->block_start = ins.objectid;
474                 em->block_len = ins.offset;
475                 em->bdev = root->fs_info->fs_devices->latest_bdev;
476                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
477
478                 if (will_compress)
479                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
480
481                 while(1) {
482                         spin_lock(&em_tree->lock);
483                         ret = add_extent_mapping(em_tree, em);
484                         spin_unlock(&em_tree->lock);
485                         if (ret != -EEXIST) {
486                                 free_extent_map(em);
487                                 break;
488                         }
489                         btrfs_drop_extent_cache(inode, start,
490                                                 start + ram_size - 1, 0);
491                 }
492
493                 cur_alloc_size = ins.offset;
494                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
495                                                ram_size, cur_alloc_size, 0,
496                                                will_compress);
497                 BUG_ON(ret);
498
499                 if (disk_num_bytes < cur_alloc_size) {
500                         printk("num_bytes %Lu cur_alloc %Lu\n", disk_num_bytes,
501                                cur_alloc_size);
502                         break;
503                 }
504
505                 if (will_compress) {
506                         /*
507                          * we're doing compression, we and we need to
508                          * submit the compressed extents down to the device.
509                          *
510                          * We lock down all the file pages, clearing their
511                          * dirty bits and setting them writeback.  Everyone
512                          * that wants to modify the page will wait on the
513                          * ordered extent above.
514                          *
515                          * The writeback bits on the file pages are
516                          * cleared when the compressed pages are on disk
517                          */
518                         btrfs_end_transaction(trans, root);
519
520                         if (start <= page_offset(locked_page) &&
521                             page_offset(locked_page) < start + ram_size) {
522                                 *page_started = 1;
523                         }
524
525                         extent_clear_unlock_delalloc(inode,
526                                                      &BTRFS_I(inode)->io_tree,
527                                                      start,
528                                                      start + ram_size - 1,
529                                                      NULL, 1, 1, 0);
530
531                         ret = btrfs_submit_compressed_write(inode, start,
532                                                  ram_size, ins.objectid,
533                                                  cur_alloc_size, pages,
534                                                  nr_pages_ret);
535
536                         BUG_ON(ret);
537                         trans = btrfs_join_transaction(root, 1);
538                         if (start + ram_size < end) {
539                                 start += ram_size;
540                                 alloc_hint = ins.objectid + ins.offset;
541                                 /* pages will be freed at end_bio time */
542                                 pages = NULL;
543                                 goto again;
544                         } else {
545                                 /* we've written everything, time to go */
546                                 break;
547                         }
548                 }
549                 /* we're not doing compressed IO, don't unlock the first
550                  * page (which the caller expects to stay locked), don't
551                  * clear any dirty bits and don't set any writeback bits
552                  */
553                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
554                                              start, start + ram_size - 1,
555                                              locked_page, 0, 0, 0);
556                 disk_num_bytes -= cur_alloc_size;
557                 num_bytes -= cur_alloc_size;
558                 alloc_hint = ins.objectid + ins.offset;
559                 start += cur_alloc_size;
560         }
561
562         ret = 0;
563 out:
564         btrfs_end_transaction(trans, root);
565
566         return ret;
567
568 free_pages_out_fail:
569         extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
570                                      start, end, locked_page, 0, 0, 0);
571 free_pages_out:
572         for (i = 0; i < nr_pages_ret; i++)
573                 page_cache_release(pages[i]);
574         if (pages)
575                 kfree(pages);
576
577         goto out;
578 }
579
580 /*
581  * when nowcow writeback call back.  This checks for snapshots or COW copies
582  * of the extents that exist in the file, and COWs the file as required.
583  *
584  * If no cow copies or snapshots exist, we write directly to the existing
585  * blocks on disk
586  */
587 static int run_delalloc_nocow(struct inode *inode, struct page *locked_page,
588                               u64 start, u64 end, int *page_started)
589 {
590         u64 extent_start;
591         u64 extent_end;
592         u64 bytenr;
593         u64 loops = 0;
594         u64 total_fs_bytes;
595         struct btrfs_root *root = BTRFS_I(inode)->root;
596         struct btrfs_block_group_cache *block_group;
597         struct btrfs_trans_handle *trans;
598         struct extent_buffer *leaf;
599         int found_type;
600         struct btrfs_path *path;
601         struct btrfs_file_extent_item *item;
602         int ret;
603         int err = 0;
604         struct btrfs_key found_key;
605
606         total_fs_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
607         path = btrfs_alloc_path();
608         BUG_ON(!path);
609         trans = btrfs_join_transaction(root, 1);
610         BUG_ON(!trans);
611 again:
612         ret = btrfs_lookup_file_extent(NULL, root, path,
613                                        inode->i_ino, start, 0);
614         if (ret < 0) {
615                 err = ret;
616                 goto out;
617         }
618
619         if (ret != 0) {
620                 if (path->slots[0] == 0)
621                         goto not_found;
622                 path->slots[0]--;
623         }
624
625         leaf = path->nodes[0];
626         item = btrfs_item_ptr(leaf, path->slots[0],
627                               struct btrfs_file_extent_item);
628
629         /* are we inside the extent that was found? */
630         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
631         found_type = btrfs_key_type(&found_key);
632         if (found_key.objectid != inode->i_ino ||
633             found_type != BTRFS_EXTENT_DATA_KEY)
634                 goto not_found;
635
636         found_type = btrfs_file_extent_type(leaf, item);
637         extent_start = found_key.offset;
638         if (found_type == BTRFS_FILE_EXTENT_REG) {
639                 u64 extent_num_bytes;
640
641                 extent_num_bytes = btrfs_file_extent_num_bytes(leaf, item);
642                 extent_end = extent_start + extent_num_bytes;
643                 err = 0;
644
645                 if (btrfs_file_extent_compression(leaf, item) ||
646                     btrfs_file_extent_encryption(leaf,item) ||
647                     btrfs_file_extent_other_encoding(leaf, item))
648                         goto not_found;
649
650                 if (loops && start != extent_start)
651                         goto not_found;
652
653                 if (start < extent_start || start >= extent_end)
654                         goto not_found;
655
656                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
657                 if (bytenr == 0)
658                         goto not_found;
659
660                 if (btrfs_cross_ref_exists(trans, root, &found_key, bytenr))
661                         goto not_found;
662                 /*
663                  * we may be called by the resizer, make sure we're inside
664                  * the limits of the FS
665                  */
666                 block_group = btrfs_lookup_block_group(root->fs_info,
667                                                        bytenr);
668                 if (!block_group || block_group->ro)
669                         goto not_found;
670
671                 bytenr += btrfs_file_extent_offset(leaf, item);
672                 extent_num_bytes = min(end + 1, extent_end) - start;
673                 ret = btrfs_add_ordered_extent(inode, start, bytenr,
674                                                 extent_num_bytes,
675                                                 extent_num_bytes, 1, 0);
676                 if (ret) {
677                         err = ret;
678                         goto out;
679                 }
680
681                 btrfs_release_path(root, path);
682                 start = extent_end;
683                 if (start <= end) {
684                         loops++;
685                         goto again;
686                 }
687         } else {
688 not_found:
689                 btrfs_end_transaction(trans, root);
690                 btrfs_free_path(path);
691                 return cow_file_range(inode, locked_page, start, end,
692                                       page_started);
693         }
694 out:
695         WARN_ON(err);
696         btrfs_end_transaction(trans, root);
697         btrfs_free_path(path);
698         return err;
699 }
700
701 /*
702  * extent_io.c call back to do delayed allocation processing
703  */
704 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
705                               u64 start, u64 end, int *page_started)
706 {
707         struct btrfs_root *root = BTRFS_I(inode)->root;
708         int ret;
709
710         if (btrfs_test_opt(root, NODATACOW) ||
711             btrfs_test_flag(inode, NODATACOW))
712                 ret = run_delalloc_nocow(inode, locked_page, start, end,
713                                          page_started);
714         else
715                 ret = cow_file_range(inode, locked_page, start, end,
716                                      page_started);
717
718         return ret;
719 }
720
721 /*
722  * extent_io.c set_bit_hook, used to track delayed allocation
723  * bytes in this file, and to maintain the list of inodes that
724  * have pending delalloc work to be done.
725  */
726 int btrfs_set_bit_hook(struct inode *inode, u64 start, u64 end,
727                        unsigned long old, unsigned long bits)
728 {
729         unsigned long flags;
730         if (!(old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
731                 struct btrfs_root *root = BTRFS_I(inode)->root;
732                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
733                 BTRFS_I(inode)->delalloc_bytes += end - start + 1;
734                 root->fs_info->delalloc_bytes += end - start + 1;
735                 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
736                         list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
737                                       &root->fs_info->delalloc_inodes);
738                 }
739                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
740         }
741         return 0;
742 }
743
744 /*
745  * extent_io.c clear_bit_hook, see set_bit_hook for why
746  */
747 int btrfs_clear_bit_hook(struct inode *inode, u64 start, u64 end,
748                          unsigned long old, unsigned long bits)
749 {
750         if ((old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
751                 struct btrfs_root *root = BTRFS_I(inode)->root;
752                 unsigned long flags;
753
754                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
755                 if (end - start + 1 > root->fs_info->delalloc_bytes) {
756                         printk("warning: delalloc account %Lu %Lu\n",
757                                end - start + 1, root->fs_info->delalloc_bytes);
758                         root->fs_info->delalloc_bytes = 0;
759                         BTRFS_I(inode)->delalloc_bytes = 0;
760                 } else {
761                         root->fs_info->delalloc_bytes -= end - start + 1;
762                         BTRFS_I(inode)->delalloc_bytes -= end - start + 1;
763                 }
764                 if (BTRFS_I(inode)->delalloc_bytes == 0 &&
765                     !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
766                         list_del_init(&BTRFS_I(inode)->delalloc_inodes);
767                 }
768                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
769         }
770         return 0;
771 }
772
773 /*
774  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
775  * we don't create bios that span stripes or chunks
776  */
777 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
778                          size_t size, struct bio *bio,
779                          unsigned long bio_flags)
780 {
781         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
782         struct btrfs_mapping_tree *map_tree;
783         u64 logical = (u64)bio->bi_sector << 9;
784         u64 length = 0;
785         u64 map_length;
786         int ret;
787
788         length = bio->bi_size;
789         map_tree = &root->fs_info->mapping_tree;
790         map_length = length;
791         ret = btrfs_map_block(map_tree, READ, logical,
792                               &map_length, NULL, 0);
793
794         if (map_length < length + size) {
795                 return 1;
796         }
797         return 0;
798 }
799
800 /*
801  * in order to insert checksums into the metadata in large chunks,
802  * we wait until bio submission time.   All the pages in the bio are
803  * checksummed and sums are attached onto the ordered extent record.
804  *
805  * At IO completion time the cums attached on the ordered extent record
806  * are inserted into the btree
807  */
808 int __btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
809                           int mirror_num, unsigned long bio_flags)
810 {
811         struct btrfs_root *root = BTRFS_I(inode)->root;
812         int ret = 0;
813
814         ret = btrfs_csum_one_bio(root, inode, bio);
815         BUG_ON(ret);
816
817         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
818 }
819
820 /*
821  * extent_io.c submission hook. This does the right thing for csum calculation on write,
822  * or reading the csums from the tree before a read
823  */
824 int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
825                           int mirror_num, unsigned long bio_flags)
826 {
827         struct btrfs_root *root = BTRFS_I(inode)->root;
828         int ret = 0;
829         int skip_sum;
830
831         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
832         BUG_ON(ret);
833
834         skip_sum = btrfs_test_opt(root, NODATASUM) ||
835                 btrfs_test_flag(inode, NODATASUM);
836
837         if (!(rw & (1 << BIO_RW))) {
838                 if (!skip_sum)
839                         btrfs_lookup_bio_sums(root, inode, bio);
840
841                 if (bio_flags & EXTENT_BIO_COMPRESSED)
842                         return btrfs_submit_compressed_read(inode, bio,
843                                                     mirror_num, bio_flags);
844                 goto mapit;
845         } else if (!skip_sum) {
846                 /* we're doing a write, do the async checksumming */
847                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
848                                    inode, rw, bio, mirror_num,
849                                    bio_flags, __btrfs_submit_bio_hook);
850         }
851
852 mapit:
853         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
854 }
855
856 /*
857  * given a list of ordered sums record them in the inode.  This happens
858  * at IO completion time based on sums calculated at bio submission time.
859  */
860 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
861                              struct inode *inode, u64 file_offset,
862                              struct list_head *list)
863 {
864         struct list_head *cur;
865         struct btrfs_ordered_sum *sum;
866
867         btrfs_set_trans_block_group(trans, inode);
868         list_for_each(cur, list) {
869                 sum = list_entry(cur, struct btrfs_ordered_sum, list);
870                 btrfs_csum_file_blocks(trans, BTRFS_I(inode)->root,
871                                        inode, sum);
872         }
873         return 0;
874 }
875
876 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end)
877 {
878         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
879                                    GFP_NOFS);
880 }
881
882 /* see btrfs_writepage_start_hook for details on why this is required */
883 struct btrfs_writepage_fixup {
884         struct page *page;
885         struct btrfs_work work;
886 };
887
888 void btrfs_writepage_fixup_worker(struct btrfs_work *work)
889 {
890         struct btrfs_writepage_fixup *fixup;
891         struct btrfs_ordered_extent *ordered;
892         struct page *page;
893         struct inode *inode;
894         u64 page_start;
895         u64 page_end;
896
897         fixup = container_of(work, struct btrfs_writepage_fixup, work);
898         page = fixup->page;
899 again:
900         lock_page(page);
901         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
902                 ClearPageChecked(page);
903                 goto out_page;
904         }
905
906         inode = page->mapping->host;
907         page_start = page_offset(page);
908         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
909
910         lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
911
912         /* already ordered? We're done */
913         if (test_range_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
914                              EXTENT_ORDERED, 0)) {
915                 goto out;
916         }
917
918         ordered = btrfs_lookup_ordered_extent(inode, page_start);
919         if (ordered) {
920                 unlock_extent(&BTRFS_I(inode)->io_tree, page_start,
921                               page_end, GFP_NOFS);
922                 unlock_page(page);
923                 btrfs_start_ordered_extent(inode, ordered, 1);
924                 goto again;
925         }
926
927         btrfs_set_extent_delalloc(inode, page_start, page_end);
928         ClearPageChecked(page);
929 out:
930         unlock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
931 out_page:
932         unlock_page(page);
933         page_cache_release(page);
934 }
935
936 /*
937  * There are a few paths in the higher layers of the kernel that directly
938  * set the page dirty bit without asking the filesystem if it is a
939  * good idea.  This causes problems because we want to make sure COW
940  * properly happens and the data=ordered rules are followed.
941  *
942  * In our case any range that doesn't have the ORDERED bit set
943  * hasn't been properly setup for IO.  We kick off an async process
944  * to fix it up.  The async helper will wait for ordered extents, set
945  * the delalloc bit and make it safe to write the page.
946  */
947 int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
948 {
949         struct inode *inode = page->mapping->host;
950         struct btrfs_writepage_fixup *fixup;
951         struct btrfs_root *root = BTRFS_I(inode)->root;
952         int ret;
953
954         ret = test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
955                              EXTENT_ORDERED, 0);
956         if (ret)
957                 return 0;
958
959         if (PageChecked(page))
960                 return -EAGAIN;
961
962         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
963         if (!fixup)
964                 return -EAGAIN;
965
966         SetPageChecked(page);
967         page_cache_get(page);
968         fixup->work.func = btrfs_writepage_fixup_worker;
969         fixup->page = page;
970         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
971         return -EAGAIN;
972 }
973
974 /* as ordered data IO finishes, this gets called so we can finish
975  * an ordered extent if the range of bytes in the file it covers are
976  * fully written.
977  */
978 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
979 {
980         struct btrfs_root *root = BTRFS_I(inode)->root;
981         struct btrfs_trans_handle *trans;
982         struct btrfs_ordered_extent *ordered_extent;
983         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
984         struct btrfs_file_extent_item *extent_item;
985         struct btrfs_path *path = NULL;
986         struct extent_buffer *leaf;
987         u64 alloc_hint = 0;
988         struct list_head list;
989         struct btrfs_key ins;
990         int ret;
991
992         ret = btrfs_dec_test_ordered_pending(inode, start, end - start + 1);
993         if (!ret)
994                 return 0;
995
996         trans = btrfs_join_transaction(root, 1);
997
998         ordered_extent = btrfs_lookup_ordered_extent(inode, start);
999         BUG_ON(!ordered_extent);
1000         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags))
1001                 goto nocow;
1002
1003         path = btrfs_alloc_path();
1004         BUG_ON(!path);
1005
1006         lock_extent(io_tree, ordered_extent->file_offset,
1007                     ordered_extent->file_offset + ordered_extent->len - 1,
1008                     GFP_NOFS);
1009
1010         INIT_LIST_HEAD(&list);
1011
1012         ret = btrfs_drop_extents(trans, root, inode,
1013                                  ordered_extent->file_offset,
1014                                  ordered_extent->file_offset +
1015                                  ordered_extent->len,
1016                                  ordered_extent->file_offset, &alloc_hint);
1017         BUG_ON(ret);
1018
1019         ins.objectid = inode->i_ino;
1020         ins.offset = ordered_extent->file_offset;
1021         ins.type = BTRFS_EXTENT_DATA_KEY;
1022         ret = btrfs_insert_empty_item(trans, root, path, &ins,
1023                                       sizeof(*extent_item));
1024         BUG_ON(ret);
1025         leaf = path->nodes[0];
1026         extent_item = btrfs_item_ptr(leaf, path->slots[0],
1027                                      struct btrfs_file_extent_item);
1028         btrfs_set_file_extent_generation(leaf, extent_item, trans->transid);
1029         btrfs_set_file_extent_type(leaf, extent_item, BTRFS_FILE_EXTENT_REG);
1030         btrfs_set_file_extent_disk_bytenr(leaf, extent_item,
1031                                           ordered_extent->start);
1032         btrfs_set_file_extent_disk_num_bytes(leaf, extent_item,
1033                                              ordered_extent->disk_len);
1034         btrfs_set_file_extent_offset(leaf, extent_item, 0);
1035
1036         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1037                 btrfs_set_file_extent_compression(leaf, extent_item, 1);
1038         else
1039                 btrfs_set_file_extent_compression(leaf, extent_item, 0);
1040         btrfs_set_file_extent_encryption(leaf, extent_item, 0);
1041         btrfs_set_file_extent_other_encoding(leaf, extent_item, 0);
1042
1043         /* ram bytes = extent_num_bytes for now */
1044         btrfs_set_file_extent_num_bytes(leaf, extent_item,
1045                                         ordered_extent->len);
1046         btrfs_set_file_extent_ram_bytes(leaf, extent_item,
1047                                         ordered_extent->len);
1048         btrfs_mark_buffer_dirty(leaf);
1049
1050         btrfs_drop_extent_cache(inode, ordered_extent->file_offset,
1051                                 ordered_extent->file_offset +
1052                                 ordered_extent->len - 1, 0);
1053
1054         ins.objectid = ordered_extent->start;
1055         ins.offset = ordered_extent->disk_len;
1056         ins.type = BTRFS_EXTENT_ITEM_KEY;
1057         ret = btrfs_alloc_reserved_extent(trans, root, leaf->start,
1058                                           root->root_key.objectid,
1059                                           trans->transid, inode->i_ino, &ins);
1060         BUG_ON(ret);
1061         btrfs_release_path(root, path);
1062
1063         inode_add_bytes(inode, ordered_extent->len);
1064         unlock_extent(io_tree, ordered_extent->file_offset,
1065                     ordered_extent->file_offset + ordered_extent->len - 1,
1066                     GFP_NOFS);
1067 nocow:
1068         add_pending_csums(trans, inode, ordered_extent->file_offset,
1069                           &ordered_extent->list);
1070
1071         mutex_lock(&BTRFS_I(inode)->extent_mutex);
1072         btrfs_ordered_update_i_size(inode, ordered_extent);
1073         btrfs_update_inode(trans, root, inode);
1074         btrfs_remove_ordered_extent(inode, ordered_extent);
1075         mutex_unlock(&BTRFS_I(inode)->extent_mutex);
1076
1077         /* once for us */
1078         btrfs_put_ordered_extent(ordered_extent);
1079         /* once for the tree */
1080         btrfs_put_ordered_extent(ordered_extent);
1081
1082         btrfs_end_transaction(trans, root);
1083         if (path)
1084                 btrfs_free_path(path);
1085         return 0;
1086 }
1087
1088 int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1089                                 struct extent_state *state, int uptodate)
1090 {
1091         return btrfs_finish_ordered_io(page->mapping->host, start, end);
1092 }
1093
1094 /*
1095  * When IO fails, either with EIO or csum verification fails, we
1096  * try other mirrors that might have a good copy of the data.  This
1097  * io_failure_record is used to record state as we go through all the
1098  * mirrors.  If another mirror has good data, the page is set up to date
1099  * and things continue.  If a good mirror can't be found, the original
1100  * bio end_io callback is called to indicate things have failed.
1101  */
1102 struct io_failure_record {
1103         struct page *page;
1104         u64 start;
1105         u64 len;
1106         u64 logical;
1107         int last_mirror;
1108 };
1109
1110 int btrfs_io_failed_hook(struct bio *failed_bio,
1111                          struct page *page, u64 start, u64 end,
1112                          struct extent_state *state)
1113 {
1114         struct io_failure_record *failrec = NULL;
1115         u64 private;
1116         struct extent_map *em;
1117         struct inode *inode = page->mapping->host;
1118         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1119         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1120         struct bio *bio;
1121         int num_copies;
1122         int ret;
1123         int rw;
1124         u64 logical;
1125         unsigned long bio_flags = 0;
1126
1127         ret = get_state_private(failure_tree, start, &private);
1128         if (ret) {
1129                 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1130                 if (!failrec)
1131                         return -ENOMEM;
1132                 failrec->start = start;
1133                 failrec->len = end - start + 1;
1134                 failrec->last_mirror = 0;
1135
1136                 spin_lock(&em_tree->lock);
1137                 em = lookup_extent_mapping(em_tree, start, failrec->len);
1138                 if (em->start > start || em->start + em->len < start) {
1139                         free_extent_map(em);
1140                         em = NULL;
1141                 }
1142                 spin_unlock(&em_tree->lock);
1143
1144                 if (!em || IS_ERR(em)) {
1145                         kfree(failrec);
1146                         return -EIO;
1147                 }
1148                 logical = start - em->start;
1149                 logical = em->block_start + logical;
1150                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1151                         bio_flags = EXTENT_BIO_COMPRESSED;
1152                 failrec->logical = logical;
1153                 free_extent_map(em);
1154                 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1155                                 EXTENT_DIRTY, GFP_NOFS);
1156                 set_state_private(failure_tree, start,
1157                                  (u64)(unsigned long)failrec);
1158         } else {
1159                 failrec = (struct io_failure_record *)(unsigned long)private;
1160         }
1161         num_copies = btrfs_num_copies(
1162                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
1163                               failrec->logical, failrec->len);
1164         failrec->last_mirror++;
1165         if (!state) {
1166                 spin_lock_irq(&BTRFS_I(inode)->io_tree.lock);
1167                 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1168                                                     failrec->start,
1169                                                     EXTENT_LOCKED);
1170                 if (state && state->start != failrec->start)
1171                         state = NULL;
1172                 spin_unlock_irq(&BTRFS_I(inode)->io_tree.lock);
1173         }
1174         if (!state || failrec->last_mirror > num_copies) {
1175                 set_state_private(failure_tree, failrec->start, 0);
1176                 clear_extent_bits(failure_tree, failrec->start,
1177                                   failrec->start + failrec->len - 1,
1178                                   EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1179                 kfree(failrec);
1180                 return -EIO;
1181         }
1182         bio = bio_alloc(GFP_NOFS, 1);
1183         bio->bi_private = state;
1184         bio->bi_end_io = failed_bio->bi_end_io;
1185         bio->bi_sector = failrec->logical >> 9;
1186         bio->bi_bdev = failed_bio->bi_bdev;
1187         bio->bi_size = 0;
1188         bio_add_page(bio, page, failrec->len, start - page_offset(page));
1189         if (failed_bio->bi_rw & (1 << BIO_RW))
1190                 rw = WRITE;
1191         else
1192                 rw = READ;
1193
1194         BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1195                                                       failrec->last_mirror,
1196                                                       bio_flags);
1197         return 0;
1198 }
1199
1200 /*
1201  * each time an IO finishes, we do a fast check in the IO failure tree
1202  * to see if we need to process or clean up an io_failure_record
1203  */
1204 int btrfs_clean_io_failures(struct inode *inode, u64 start)
1205 {
1206         u64 private;
1207         u64 private_failure;
1208         struct io_failure_record *failure;
1209         int ret;
1210
1211         private = 0;
1212         if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1213                              (u64)-1, 1, EXTENT_DIRTY)) {
1214                 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1215                                         start, &private_failure);
1216                 if (ret == 0) {
1217                         failure = (struct io_failure_record *)(unsigned long)
1218                                    private_failure;
1219                         set_state_private(&BTRFS_I(inode)->io_failure_tree,
1220                                           failure->start, 0);
1221                         clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1222                                           failure->start,
1223                                           failure->start + failure->len - 1,
1224                                           EXTENT_DIRTY | EXTENT_LOCKED,
1225                                           GFP_NOFS);
1226                         kfree(failure);
1227                 }
1228         }
1229         return 0;
1230 }
1231
1232 /*
1233  * when reads are done, we need to check csums to verify the data is correct
1234  * if there's a match, we allow the bio to finish.  If not, we go through
1235  * the io_failure_record routines to find good copies
1236  */
1237 int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1238                                struct extent_state *state)
1239 {
1240         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1241         struct inode *inode = page->mapping->host;
1242         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1243         char *kaddr;
1244         u64 private = ~(u32)0;
1245         int ret;
1246         struct btrfs_root *root = BTRFS_I(inode)->root;
1247         u32 csum = ~(u32)0;
1248         unsigned long flags;
1249
1250         if (btrfs_test_opt(root, NODATASUM) ||
1251             btrfs_test_flag(inode, NODATASUM))
1252                 return 0;
1253         if (state && state->start == start) {
1254                 private = state->private;
1255                 ret = 0;
1256         } else {
1257                 ret = get_state_private(io_tree, start, &private);
1258         }
1259         local_irq_save(flags);
1260         kaddr = kmap_atomic(page, KM_IRQ0);
1261         if (ret) {
1262                 goto zeroit;
1263         }
1264         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
1265         btrfs_csum_final(csum, (char *)&csum);
1266         if (csum != private) {
1267                 goto zeroit;
1268         }
1269         kunmap_atomic(kaddr, KM_IRQ0);
1270         local_irq_restore(flags);
1271
1272         /* if the io failure tree for this inode is non-empty,
1273          * check to see if we've recovered from a failed IO
1274          */
1275         btrfs_clean_io_failures(inode, start);
1276         return 0;
1277
1278 zeroit:
1279         printk("btrfs csum failed ino %lu off %llu csum %u private %Lu\n",
1280                page->mapping->host->i_ino, (unsigned long long)start, csum,
1281                private);
1282         memset(kaddr + offset, 1, end - start + 1);
1283         flush_dcache_page(page);
1284         kunmap_atomic(kaddr, KM_IRQ0);
1285         local_irq_restore(flags);
1286         if (private == 0)
1287                 return 0;
1288         return -EIO;
1289 }
1290
1291 /*
1292  * This creates an orphan entry for the given inode in case something goes
1293  * wrong in the middle of an unlink/truncate.
1294  */
1295 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
1296 {
1297         struct btrfs_root *root = BTRFS_I(inode)->root;
1298         int ret = 0;
1299
1300         spin_lock(&root->list_lock);
1301
1302         /* already on the orphan list, we're good */
1303         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
1304                 spin_unlock(&root->list_lock);
1305                 return 0;
1306         }
1307
1308         list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
1309
1310         spin_unlock(&root->list_lock);
1311
1312         /*
1313          * insert an orphan item to track this unlinked/truncated file
1314          */
1315         ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
1316
1317         return ret;
1318 }
1319
1320 /*
1321  * We have done the truncate/delete so we can go ahead and remove the orphan
1322  * item for this particular inode.
1323  */
1324 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
1325 {
1326         struct btrfs_root *root = BTRFS_I(inode)->root;
1327         int ret = 0;
1328
1329         spin_lock(&root->list_lock);
1330
1331         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
1332                 spin_unlock(&root->list_lock);
1333                 return 0;
1334         }
1335
1336         list_del_init(&BTRFS_I(inode)->i_orphan);
1337         if (!trans) {
1338                 spin_unlock(&root->list_lock);
1339                 return 0;
1340         }
1341
1342         spin_unlock(&root->list_lock);
1343
1344         ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
1345
1346         return ret;
1347 }
1348
1349 /*
1350  * this cleans up any orphans that may be left on the list from the last use
1351  * of this root.
1352  */
1353 void btrfs_orphan_cleanup(struct btrfs_root *root)
1354 {
1355         struct btrfs_path *path;
1356         struct extent_buffer *leaf;
1357         struct btrfs_item *item;
1358         struct btrfs_key key, found_key;
1359         struct btrfs_trans_handle *trans;
1360         struct inode *inode;
1361         int ret = 0, nr_unlink = 0, nr_truncate = 0;
1362
1363         /* don't do orphan cleanup if the fs is readonly. */
1364         if (root->fs_info->sb->s_flags & MS_RDONLY)
1365                 return;
1366
1367         path = btrfs_alloc_path();
1368         if (!path)
1369                 return;
1370         path->reada = -1;
1371
1372         key.objectid = BTRFS_ORPHAN_OBJECTID;
1373         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
1374         key.offset = (u64)-1;
1375
1376
1377         while (1) {
1378                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1379                 if (ret < 0) {
1380                         printk(KERN_ERR "Error searching slot for orphan: %d"
1381                                "\n", ret);
1382                         break;
1383                 }
1384
1385                 /*
1386                  * if ret == 0 means we found what we were searching for, which
1387                  * is weird, but possible, so only screw with path if we didnt
1388                  * find the key and see if we have stuff that matches
1389                  */
1390                 if (ret > 0) {
1391                         if (path->slots[0] == 0)
1392                                 break;
1393                         path->slots[0]--;
1394                 }
1395
1396                 /* pull out the item */
1397                 leaf = path->nodes[0];
1398                 item = btrfs_item_nr(leaf, path->slots[0]);
1399                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1400
1401                 /* make sure the item matches what we want */
1402                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
1403                         break;
1404                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
1405                         break;
1406
1407                 /* release the path since we're done with it */
1408                 btrfs_release_path(root, path);
1409
1410                 /*
1411                  * this is where we are basically btrfs_lookup, without the
1412                  * crossing root thing.  we store the inode number in the
1413                  * offset of the orphan item.
1414                  */
1415                 inode = btrfs_iget_locked(root->fs_info->sb,
1416                                           found_key.offset, root);
1417                 if (!inode)
1418                         break;
1419
1420                 if (inode->i_state & I_NEW) {
1421                         BTRFS_I(inode)->root = root;
1422
1423                         /* have to set the location manually */
1424                         BTRFS_I(inode)->location.objectid = inode->i_ino;
1425                         BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
1426                         BTRFS_I(inode)->location.offset = 0;
1427
1428                         btrfs_read_locked_inode(inode);
1429                         unlock_new_inode(inode);
1430                 }
1431
1432                 /*
1433                  * add this inode to the orphan list so btrfs_orphan_del does
1434                  * the proper thing when we hit it
1435                  */
1436                 spin_lock(&root->list_lock);
1437                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
1438                 spin_unlock(&root->list_lock);
1439
1440                 /*
1441                  * if this is a bad inode, means we actually succeeded in
1442                  * removing the inode, but not the orphan record, which means
1443                  * we need to manually delete the orphan since iput will just
1444                  * do a destroy_inode
1445                  */
1446                 if (is_bad_inode(inode)) {
1447                         trans = btrfs_start_transaction(root, 1);
1448                         btrfs_orphan_del(trans, inode);
1449                         btrfs_end_transaction(trans, root);
1450                         iput(inode);
1451                         continue;
1452                 }
1453
1454                 /* if we have links, this was a truncate, lets do that */
1455                 if (inode->i_nlink) {
1456                         nr_truncate++;
1457                         btrfs_truncate(inode);
1458                 } else {
1459                         nr_unlink++;
1460                 }
1461
1462                 /* this will do delete_inode and everything for us */
1463                 iput(inode);
1464         }
1465
1466         if (nr_unlink)
1467                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
1468         if (nr_truncate)
1469                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
1470
1471         btrfs_free_path(path);
1472 }
1473
1474 /*
1475  * read an inode from the btree into the in-memory inode
1476  */
1477 void btrfs_read_locked_inode(struct inode *inode)
1478 {
1479         struct btrfs_path *path;
1480         struct extent_buffer *leaf;
1481         struct btrfs_inode_item *inode_item;
1482         struct btrfs_timespec *tspec;
1483         struct btrfs_root *root = BTRFS_I(inode)->root;
1484         struct btrfs_key location;
1485         u64 alloc_group_block;
1486         u32 rdev;
1487         int ret;
1488
1489         path = btrfs_alloc_path();
1490         BUG_ON(!path);
1491         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
1492
1493         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
1494         if (ret)
1495                 goto make_bad;
1496
1497         leaf = path->nodes[0];
1498         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1499                                     struct btrfs_inode_item);
1500
1501         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
1502         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
1503         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
1504         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
1505         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
1506
1507         tspec = btrfs_inode_atime(inode_item);
1508         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1509         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1510
1511         tspec = btrfs_inode_mtime(inode_item);
1512         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1513         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1514
1515         tspec = btrfs_inode_ctime(inode_item);
1516         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1517         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1518
1519         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
1520         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
1521         inode->i_generation = BTRFS_I(inode)->generation;
1522         inode->i_rdev = 0;
1523         rdev = btrfs_inode_rdev(leaf, inode_item);
1524
1525         BTRFS_I(inode)->index_cnt = (u64)-1;
1526
1527         alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
1528         BTRFS_I(inode)->block_group = btrfs_lookup_block_group(root->fs_info,
1529                                                        alloc_group_block);
1530         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
1531         if (!BTRFS_I(inode)->block_group) {
1532                 BTRFS_I(inode)->block_group = btrfs_find_block_group(root,
1533                                                  NULL, 0,
1534                                                  BTRFS_BLOCK_GROUP_METADATA, 0);
1535         }
1536         btrfs_free_path(path);
1537         inode_item = NULL;
1538
1539         switch (inode->i_mode & S_IFMT) {
1540         case S_IFREG:
1541                 inode->i_mapping->a_ops = &btrfs_aops;
1542                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
1543                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
1544                 inode->i_fop = &btrfs_file_operations;
1545                 inode->i_op = &btrfs_file_inode_operations;
1546                 break;
1547         case S_IFDIR:
1548                 inode->i_fop = &btrfs_dir_file_operations;
1549                 if (root == root->fs_info->tree_root)
1550                         inode->i_op = &btrfs_dir_ro_inode_operations;
1551                 else
1552                         inode->i_op = &btrfs_dir_inode_operations;
1553                 break;
1554         case S_IFLNK:
1555                 inode->i_op = &btrfs_symlink_inode_operations;
1556                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
1557                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
1558                 break;
1559         default:
1560                 init_special_inode(inode, inode->i_mode, rdev);
1561                 break;
1562         }
1563         return;
1564
1565 make_bad:
1566         btrfs_free_path(path);
1567         make_bad_inode(inode);
1568 }
1569
1570 /*
1571  * given a leaf and an inode, copy the inode fields into the leaf
1572  */
1573 static void fill_inode_item(struct btrfs_trans_handle *trans,
1574                             struct extent_buffer *leaf,
1575                             struct btrfs_inode_item *item,
1576                             struct inode *inode)
1577 {
1578         btrfs_set_inode_uid(leaf, item, inode->i_uid);
1579         btrfs_set_inode_gid(leaf, item, inode->i_gid);
1580         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
1581         btrfs_set_inode_mode(leaf, item, inode->i_mode);
1582         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
1583
1584         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
1585                                inode->i_atime.tv_sec);
1586         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
1587                                 inode->i_atime.tv_nsec);
1588
1589         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
1590                                inode->i_mtime.tv_sec);
1591         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
1592                                 inode->i_mtime.tv_nsec);
1593
1594         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
1595                                inode->i_ctime.tv_sec);
1596         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
1597                                 inode->i_ctime.tv_nsec);
1598
1599         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
1600         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
1601         btrfs_set_inode_transid(leaf, item, trans->transid);
1602         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
1603         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
1604         btrfs_set_inode_block_group(leaf, item,
1605                                     BTRFS_I(inode)->block_group->key.objectid);
1606 }
1607
1608 /*
1609  * copy everything in the in-memory inode into the btree.
1610  */
1611 int noinline btrfs_update_inode(struct btrfs_trans_handle *trans,
1612                               struct btrfs_root *root,
1613                               struct inode *inode)
1614 {
1615         struct btrfs_inode_item *inode_item;
1616         struct btrfs_path *path;
1617         struct extent_buffer *leaf;
1618         int ret;
1619
1620         path = btrfs_alloc_path();
1621         BUG_ON(!path);
1622         ret = btrfs_lookup_inode(trans, root, path,
1623                                  &BTRFS_I(inode)->location, 1);
1624         if (ret) {
1625                 if (ret > 0)
1626                         ret = -ENOENT;
1627                 goto failed;
1628         }
1629
1630         leaf = path->nodes[0];
1631         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1632                                   struct btrfs_inode_item);
1633
1634         fill_inode_item(trans, leaf, inode_item, inode);
1635         btrfs_mark_buffer_dirty(leaf);
1636         btrfs_set_inode_last_trans(trans, inode);
1637         ret = 0;
1638 failed:
1639         btrfs_free_path(path);
1640         return ret;
1641 }
1642
1643
1644 /*
1645  * unlink helper that gets used here in inode.c and in the tree logging
1646  * recovery code.  It remove a link in a directory with a given name, and
1647  * also drops the back refs in the inode to the directory
1648  */
1649 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
1650                        struct btrfs_root *root,
1651                        struct inode *dir, struct inode *inode,
1652                        const char *name, int name_len)
1653 {
1654         struct btrfs_path *path;
1655         int ret = 0;
1656         struct extent_buffer *leaf;
1657         struct btrfs_dir_item *di;
1658         struct btrfs_key key;
1659         u64 index;
1660
1661         path = btrfs_alloc_path();
1662         if (!path) {
1663                 ret = -ENOMEM;
1664                 goto err;
1665         }
1666
1667         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
1668                                     name, name_len, -1);
1669         if (IS_ERR(di)) {
1670                 ret = PTR_ERR(di);
1671                 goto err;
1672         }
1673         if (!di) {
1674                 ret = -ENOENT;
1675                 goto err;
1676         }
1677         leaf = path->nodes[0];
1678         btrfs_dir_item_key_to_cpu(leaf, di, &key);
1679         ret = btrfs_delete_one_dir_name(trans, root, path, di);
1680         if (ret)
1681                 goto err;
1682         btrfs_release_path(root, path);
1683
1684         ret = btrfs_del_inode_ref(trans, root, name, name_len,
1685                                   inode->i_ino,
1686                                   dir->i_ino, &index);
1687         if (ret) {
1688                 printk("failed to delete reference to %.*s, "
1689                        "inode %lu parent %lu\n", name_len, name,
1690                        inode->i_ino, dir->i_ino);
1691                 goto err;
1692         }
1693
1694         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
1695                                          index, name, name_len, -1);
1696         if (IS_ERR(di)) {
1697                 ret = PTR_ERR(di);
1698                 goto err;
1699         }
1700         if (!di) {
1701                 ret = -ENOENT;
1702                 goto err;
1703         }
1704         ret = btrfs_delete_one_dir_name(trans, root, path, di);
1705         btrfs_release_path(root, path);
1706
1707         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
1708                                          inode, dir->i_ino);
1709         BUG_ON(ret != 0 && ret != -ENOENT);
1710         if (ret != -ENOENT)
1711                 BTRFS_I(dir)->log_dirty_trans = trans->transid;
1712
1713         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
1714                                            dir, index);
1715         BUG_ON(ret);
1716 err:
1717         btrfs_free_path(path);
1718         if (ret)
1719                 goto out;
1720
1721         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
1722         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
1723         btrfs_update_inode(trans, root, dir);
1724         btrfs_drop_nlink(inode);
1725         ret = btrfs_update_inode(trans, root, inode);
1726         dir->i_sb->s_dirt = 1;
1727 out:
1728         return ret;
1729 }
1730
1731 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
1732 {
1733         struct btrfs_root *root;
1734         struct btrfs_trans_handle *trans;
1735         struct inode *inode = dentry->d_inode;
1736         int ret;
1737         unsigned long nr = 0;
1738
1739         root = BTRFS_I(dir)->root;
1740
1741         ret = btrfs_check_free_space(root, 1, 1);
1742         if (ret)
1743                 goto fail;
1744
1745         trans = btrfs_start_transaction(root, 1);
1746
1747         btrfs_set_trans_block_group(trans, dir);
1748         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
1749                                  dentry->d_name.name, dentry->d_name.len);
1750
1751         if (inode->i_nlink == 0)
1752                 ret = btrfs_orphan_add(trans, inode);
1753
1754         nr = trans->blocks_used;
1755
1756         btrfs_end_transaction_throttle(trans, root);
1757 fail:
1758         btrfs_btree_balance_dirty(root, nr);
1759         return ret;
1760 }
1761
1762 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
1763 {
1764         struct inode *inode = dentry->d_inode;
1765         int err = 0;
1766         int ret;
1767         struct btrfs_root *root = BTRFS_I(dir)->root;
1768         struct btrfs_trans_handle *trans;
1769         unsigned long nr = 0;
1770
1771         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
1772                 return -ENOTEMPTY;
1773         }
1774
1775         ret = btrfs_check_free_space(root, 1, 1);
1776         if (ret)
1777                 goto fail;
1778
1779         trans = btrfs_start_transaction(root, 1);
1780         btrfs_set_trans_block_group(trans, dir);
1781
1782         err = btrfs_orphan_add(trans, inode);
1783         if (err)
1784                 goto fail_trans;
1785
1786         /* now the directory is empty */
1787         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
1788                                  dentry->d_name.name, dentry->d_name.len);
1789         if (!err) {
1790                 btrfs_i_size_write(inode, 0);
1791         }
1792
1793 fail_trans:
1794         nr = trans->blocks_used;
1795         ret = btrfs_end_transaction_throttle(trans, root);
1796 fail:
1797         btrfs_btree_balance_dirty(root, nr);
1798
1799         if (ret && !err)
1800                 err = ret;
1801         return err;
1802 }
1803
1804 /*
1805  * when truncating bytes in a file, it is possible to avoid reading
1806  * the leaves that contain only checksum items.  This can be the
1807  * majority of the IO required to delete a large file, but it must
1808  * be done carefully.
1809  *
1810  * The keys in the level just above the leaves are checked to make sure
1811  * the lowest key in a given leaf is a csum key, and starts at an offset
1812  * after the new  size.
1813  *
1814  * Then the key for the next leaf is checked to make sure it also has
1815  * a checksum item for the same file.  If it does, we know our target leaf
1816  * contains only checksum items, and it can be safely freed without reading
1817  * it.
1818  *
1819  * This is just an optimization targeted at large files.  It may do
1820  * nothing.  It will return 0 unless things went badly.
1821  */
1822 static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
1823                                      struct btrfs_root *root,
1824                                      struct btrfs_path *path,
1825                                      struct inode *inode, u64 new_size)
1826 {
1827         struct btrfs_key key;
1828         int ret;
1829         int nritems;
1830         struct btrfs_key found_key;
1831         struct btrfs_key other_key;
1832         struct btrfs_leaf_ref *ref;
1833         u64 leaf_gen;
1834         u64 leaf_start;
1835
1836         path->lowest_level = 1;
1837         key.objectid = inode->i_ino;
1838         key.type = BTRFS_CSUM_ITEM_KEY;
1839         key.offset = new_size;
1840 again:
1841         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1842         if (ret < 0)
1843                 goto out;
1844
1845         if (path->nodes[1] == NULL) {
1846                 ret = 0;
1847                 goto out;
1848         }
1849         ret = 0;
1850         btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
1851         nritems = btrfs_header_nritems(path->nodes[1]);
1852
1853         if (!nritems)
1854                 goto out;
1855
1856         if (path->slots[1] >= nritems)
1857                 goto next_node;
1858
1859         /* did we find a key greater than anything we want to delete? */
1860         if (found_key.objectid > inode->i_ino ||
1861            (found_key.objectid == inode->i_ino && found_key.type > key.type))
1862                 goto out;
1863
1864         /* we check the next key in the node to make sure the leave contains
1865          * only checksum items.  This comparison doesn't work if our
1866          * leaf is the last one in the node
1867          */
1868         if (path->slots[1] + 1 >= nritems) {
1869 next_node:
1870                 /* search forward from the last key in the node, this
1871                  * will bring us into the next node in the tree
1872                  */
1873                 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
1874
1875                 /* unlikely, but we inc below, so check to be safe */
1876                 if (found_key.offset == (u64)-1)
1877                         goto out;
1878
1879                 /* search_forward needs a path with locks held, do the
1880                  * search again for the original key.  It is possible
1881                  * this will race with a balance and return a path that
1882                  * we could modify, but this drop is just an optimization
1883                  * and is allowed to miss some leaves.
1884                  */
1885                 btrfs_release_path(root, path);
1886                 found_key.offset++;
1887
1888                 /* setup a max key for search_forward */
1889                 other_key.offset = (u64)-1;
1890                 other_key.type = key.type;
1891                 other_key.objectid = key.objectid;
1892
1893                 path->keep_locks = 1;
1894                 ret = btrfs_search_forward(root, &found_key, &other_key,
1895                                            path, 0, 0);
1896                 path->keep_locks = 0;
1897                 if (ret || found_key.objectid != key.objectid ||
1898                     found_key.type != key.type) {
1899                         ret = 0;
1900                         goto out;
1901                 }
1902
1903                 key.offset = found_key.offset;
1904                 btrfs_release_path(root, path);
1905                 cond_resched();
1906                 goto again;
1907         }
1908
1909         /* we know there's one more slot after us in the tree,
1910          * read that key so we can verify it is also a checksum item
1911          */
1912         btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
1913
1914         if (found_key.objectid < inode->i_ino)
1915                 goto next_key;
1916
1917         if (found_key.type != key.type || found_key.offset < new_size)
1918                 goto next_key;
1919
1920         /*
1921          * if the key for the next leaf isn't a csum key from this objectid,
1922          * we can't be sure there aren't good items inside this leaf.
1923          * Bail out
1924          */
1925         if (other_key.objectid != inode->i_ino || other_key.type != key.type)
1926                 goto out;
1927
1928         leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
1929         leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
1930         /*
1931          * it is safe to delete this leaf, it contains only
1932          * csum items from this inode at an offset >= new_size
1933          */
1934         ret = btrfs_del_leaf(trans, root, path, leaf_start);
1935         BUG_ON(ret);
1936
1937         if (root->ref_cows && leaf_gen < trans->transid) {
1938                 ref = btrfs_alloc_leaf_ref(root, 0);
1939                 if (ref) {
1940                         ref->root_gen = root->root_key.offset;
1941                         ref->bytenr = leaf_start;
1942                         ref->owner = 0;
1943                         ref->generation = leaf_gen;
1944                         ref->nritems = 0;
1945
1946                         ret = btrfs_add_leaf_ref(root, ref, 0);
1947                         WARN_ON(ret);
1948                         btrfs_free_leaf_ref(root, ref);
1949                 } else {
1950                         WARN_ON(1);
1951                 }
1952         }
1953 next_key:
1954         btrfs_release_path(root, path);
1955
1956         if (other_key.objectid == inode->i_ino &&
1957             other_key.type == key.type && other_key.offset > key.offset) {
1958                 key.offset = other_key.offset;
1959                 cond_resched();
1960                 goto again;
1961         }
1962         ret = 0;
1963 out:
1964         /* fixup any changes we've made to the path */
1965         path->lowest_level = 0;
1966         path->keep_locks = 0;
1967         btrfs_release_path(root, path);
1968         return ret;
1969 }
1970
1971 /*
1972  * this can truncate away extent items, csum items and directory items.
1973  * It starts at a high offset and removes keys until it can't find
1974  * any higher than new_size
1975  *
1976  * csum items that cross the new i_size are truncated to the new size
1977  * as well.
1978  *
1979  * min_type is the minimum key type to truncate down to.  If set to 0, this
1980  * will kill all the items on this inode, including the INODE_ITEM_KEY.
1981  */
1982 noinline int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
1983                                         struct btrfs_root *root,
1984                                         struct inode *inode,
1985                                         u64 new_size, u32 min_type)
1986 {
1987         int ret;
1988         struct btrfs_path *path;
1989         struct btrfs_key key;
1990         struct btrfs_key found_key;
1991         u32 found_type;
1992         struct extent_buffer *leaf;
1993         struct btrfs_file_extent_item *fi;
1994         u64 extent_start = 0;
1995         u64 extent_num_bytes = 0;
1996         u64 item_end = 0;
1997         u64 root_gen = 0;
1998         u64 root_owner = 0;
1999         int found_extent;
2000         int del_item;
2001         int pending_del_nr = 0;
2002         int pending_del_slot = 0;
2003         int extent_type = -1;
2004         u64 mask = root->sectorsize - 1;
2005
2006         if (root->ref_cows)
2007                 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
2008         path = btrfs_alloc_path();
2009         path->reada = -1;
2010         BUG_ON(!path);
2011
2012         /* FIXME, add redo link to tree so we don't leak on crash */
2013         key.objectid = inode->i_ino;
2014         key.offset = (u64)-1;
2015         key.type = (u8)-1;
2016
2017         btrfs_init_path(path);
2018
2019         ret = drop_csum_leaves(trans, root, path, inode, new_size);
2020         BUG_ON(ret);
2021
2022 search_again:
2023         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2024         if (ret < 0) {
2025                 goto error;
2026         }
2027         if (ret > 0) {
2028                 /* there are no items in the tree for us to truncate, we're
2029                  * done
2030                  */
2031                 if (path->slots[0] == 0) {
2032                         ret = 0;
2033                         goto error;
2034                 }
2035                 path->slots[0]--;
2036         }
2037
2038         while(1) {
2039                 fi = NULL;
2040                 leaf = path->nodes[0];
2041                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2042                 found_type = btrfs_key_type(&found_key);
2043
2044                 if (found_key.objectid != inode->i_ino)
2045                         break;
2046
2047                 if (found_type < min_type)
2048                         break;
2049
2050                 item_end = found_key.offset;
2051                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
2052                         fi = btrfs_item_ptr(leaf, path->slots[0],
2053                                             struct btrfs_file_extent_item);
2054                         extent_type = btrfs_file_extent_type(leaf, fi);
2055                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
2056                                 item_end +=
2057                                     btrfs_file_extent_num_bytes(leaf, fi);
2058                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
2059                                 item_end += btrfs_file_extent_inline_len(leaf,
2060                                                                          fi);
2061                         }
2062                         item_end--;
2063                 }
2064                 if (found_type == BTRFS_CSUM_ITEM_KEY) {
2065                         ret = btrfs_csum_truncate(trans, root, path,
2066                                                   new_size);
2067                         BUG_ON(ret);
2068                 }
2069                 if (item_end < new_size) {
2070                         if (found_type == BTRFS_DIR_ITEM_KEY) {
2071                                 found_type = BTRFS_INODE_ITEM_KEY;
2072                         } else if (found_type == BTRFS_EXTENT_ITEM_KEY) {
2073                                 found_type = BTRFS_CSUM_ITEM_KEY;
2074                         } else if (found_type == BTRFS_EXTENT_DATA_KEY) {
2075                                 found_type = BTRFS_XATTR_ITEM_KEY;
2076                         } else if (found_type == BTRFS_XATTR_ITEM_KEY) {
2077                                 found_type = BTRFS_INODE_REF_KEY;
2078                         } else if (found_type) {
2079                                 found_type--;
2080                         } else {
2081                                 break;
2082                         }
2083                         btrfs_set_key_type(&key, found_type);
2084                         goto next;
2085                 }
2086                 if (found_key.offset >= new_size)
2087                         del_item = 1;
2088                 else
2089                         del_item = 0;
2090                 found_extent = 0;
2091
2092                 /* FIXME, shrink the extent if the ref count is only 1 */
2093                 if (found_type != BTRFS_EXTENT_DATA_KEY)
2094                         goto delete;
2095
2096                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
2097                         u64 num_dec;
2098                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
2099                         if (!del_item) {
2100                                 u64 orig_num_bytes =
2101                                         btrfs_file_extent_num_bytes(leaf, fi);
2102                                 extent_num_bytes = new_size -
2103                                         found_key.offset + root->sectorsize - 1;
2104                                 extent_num_bytes = extent_num_bytes &
2105                                         ~((u64)root->sectorsize - 1);
2106                                 btrfs_set_file_extent_num_bytes(leaf, fi,
2107                                                          extent_num_bytes);
2108                                 num_dec = (orig_num_bytes -
2109                                            extent_num_bytes);
2110                                 if (root->ref_cows && extent_start != 0)
2111                                         inode_sub_bytes(inode, num_dec);
2112                                 btrfs_mark_buffer_dirty(leaf);
2113                         } else {
2114                                 extent_num_bytes =
2115                                         btrfs_file_extent_disk_num_bytes(leaf,
2116                                                                          fi);
2117                                 /* FIXME blocksize != 4096 */
2118                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
2119                                 if (extent_start != 0) {
2120                                         found_extent = 1;
2121                                         if (root->ref_cows)
2122                                                 inode_sub_bytes(inode, num_dec);
2123                                 }
2124                                 root_gen = btrfs_header_generation(leaf);
2125                                 root_owner = btrfs_header_owner(leaf);
2126                         }
2127                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
2128                         /*
2129                          * we can't truncate inline items that have had
2130                          * special encodings
2131                          */
2132                         if (!del_item &&
2133                             btrfs_file_extent_compression(leaf, fi) == 0 &&
2134                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
2135                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
2136                                 u32 size = new_size - found_key.offset;
2137
2138                                 if (root->ref_cows) {
2139                                         inode_sub_bytes(inode, item_end + 1 -
2140                                                         new_size);
2141                                 }
2142                                 size =
2143                                     btrfs_file_extent_calc_inline_size(size);
2144                                 ret = btrfs_truncate_item(trans, root, path,
2145                                                           size, 1);
2146                                 BUG_ON(ret);
2147                         } else if (root->ref_cows) {
2148                                 inode_sub_bytes(inode, item_end + 1 -
2149                                                 found_key.offset);
2150                         }
2151                 }
2152 delete:
2153                 if (del_item) {
2154                         if (!pending_del_nr) {
2155                                 /* no pending yet, add ourselves */
2156                                 pending_del_slot = path->slots[0];
2157                                 pending_del_nr = 1;
2158                         } else if (pending_del_nr &&
2159                                    path->slots[0] + 1 == pending_del_slot) {
2160                                 /* hop on the pending chunk */
2161                                 pending_del_nr++;
2162                                 pending_del_slot = path->slots[0];
2163                         } else {
2164                                 printk("bad pending slot %d pending_del_nr %d pending_del_slot %d\n", path->slots[0], pending_del_nr, pending_del_slot);
2165                         }
2166                 } else {
2167                         break;
2168                 }
2169                 if (found_extent) {
2170                         ret = btrfs_free_extent(trans, root, extent_start,
2171                                                 extent_num_bytes,
2172                                                 leaf->start, root_owner,
2173                                                 root_gen, inode->i_ino, 0);
2174                         BUG_ON(ret);
2175                 }
2176 next:
2177                 if (path->slots[0] == 0) {
2178                         if (pending_del_nr)
2179                                 goto del_pending;
2180                         btrfs_release_path(root, path);
2181                         goto search_again;
2182                 }
2183
2184                 path->slots[0]--;
2185                 if (pending_del_nr &&
2186                     path->slots[0] + 1 != pending_del_slot) {
2187                         struct btrfs_key debug;
2188 del_pending:
2189                         btrfs_item_key_to_cpu(path->nodes[0], &debug,
2190                                               pending_del_slot);
2191                         ret = btrfs_del_items(trans, root, path,
2192                                               pending_del_slot,
2193                                               pending_del_nr);
2194                         BUG_ON(ret);
2195                         pending_del_nr = 0;
2196                         btrfs_release_path(root, path);
2197                         goto search_again;
2198                 }
2199         }
2200         ret = 0;
2201 error:
2202         if (pending_del_nr) {
2203                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
2204                                       pending_del_nr);
2205         }
2206         btrfs_free_path(path);
2207         inode->i_sb->s_dirt = 1;
2208         return ret;
2209 }
2210
2211 /*
2212  * taken from block_truncate_page, but does cow as it zeros out
2213  * any bytes left in the last page in the file.
2214  */
2215 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
2216 {
2217         struct inode *inode = mapping->host;
2218         struct btrfs_root *root = BTRFS_I(inode)->root;
2219         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2220         struct btrfs_ordered_extent *ordered;
2221         char *kaddr;
2222         u32 blocksize = root->sectorsize;
2223         pgoff_t index = from >> PAGE_CACHE_SHIFT;
2224         unsigned offset = from & (PAGE_CACHE_SIZE-1);
2225         struct page *page;
2226         int ret = 0;
2227         u64 page_start;
2228         u64 page_end;
2229
2230         if ((offset & (blocksize - 1)) == 0)
2231                 goto out;
2232
2233         ret = -ENOMEM;
2234 again:
2235         page = grab_cache_page(mapping, index);
2236         if (!page)
2237                 goto out;
2238
2239         page_start = page_offset(page);
2240         page_end = page_start + PAGE_CACHE_SIZE - 1;
2241
2242         if (!PageUptodate(page)) {
2243                 ret = btrfs_readpage(NULL, page);
2244                 lock_page(page);
2245                 if (page->mapping != mapping) {
2246                         unlock_page(page);
2247                         page_cache_release(page);
2248                         goto again;
2249                 }
2250                 if (!PageUptodate(page)) {
2251                         ret = -EIO;
2252                         goto out_unlock;
2253                 }
2254         }
2255         wait_on_page_writeback(page);
2256
2257         lock_extent(io_tree, page_start, page_end, GFP_NOFS);
2258         set_page_extent_mapped(page);
2259
2260         ordered = btrfs_lookup_ordered_extent(inode, page_start);
2261         if (ordered) {
2262                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
2263                 unlock_page(page);
2264                 page_cache_release(page);
2265                 btrfs_start_ordered_extent(inode, ordered, 1);
2266                 btrfs_put_ordered_extent(ordered);
2267                 goto again;
2268         }
2269
2270         btrfs_set_extent_delalloc(inode, page_start, page_end);
2271         ret = 0;
2272         if (offset != PAGE_CACHE_SIZE) {
2273                 kaddr = kmap(page);
2274                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
2275                 flush_dcache_page(page);
2276                 kunmap(page);
2277         }
2278         ClearPageChecked(page);
2279         set_page_dirty(page);
2280         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
2281
2282 out_unlock:
2283         unlock_page(page);
2284         page_cache_release(page);
2285 out:
2286         return ret;
2287 }
2288
2289 int btrfs_cont_expand(struct inode *inode, loff_t size)
2290 {
2291         struct btrfs_trans_handle *trans;
2292         struct btrfs_root *root = BTRFS_I(inode)->root;
2293         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2294         struct extent_map *em;
2295         u64 mask = root->sectorsize - 1;
2296         u64 hole_start = (inode->i_size + mask) & ~mask;
2297         u64 block_end = (size + mask) & ~mask;
2298         u64 last_byte;
2299         u64 cur_offset;
2300         u64 hole_size;
2301         int err;
2302
2303         if (size <= hole_start)
2304                 return 0;
2305
2306         err = btrfs_check_free_space(root, 1, 0);
2307         if (err)
2308                 return err;
2309
2310         btrfs_truncate_page(inode->i_mapping, inode->i_size);
2311
2312         while (1) {
2313                 struct btrfs_ordered_extent *ordered;
2314                 btrfs_wait_ordered_range(inode, hole_start,
2315                                          block_end - hole_start);
2316                 lock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
2317                 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
2318                 if (!ordered)
2319                         break;
2320                 unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
2321                 btrfs_put_ordered_extent(ordered);
2322         }
2323
2324         trans = btrfs_start_transaction(root, 1);
2325         btrfs_set_trans_block_group(trans, inode);
2326
2327         cur_offset = hole_start;
2328         while (1) {
2329                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
2330                                 block_end - cur_offset, 0);
2331                 BUG_ON(IS_ERR(em) || !em);
2332                 last_byte = min(extent_map_end(em), block_end);
2333                 last_byte = (last_byte + mask) & ~mask;
2334                 if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2335                         hole_size = last_byte - cur_offset;
2336                         err = btrfs_insert_file_extent(trans, root,
2337                                         inode->i_ino, cur_offset, 0,
2338                                         0, hole_size, 0, hole_size,
2339                                         0, 0, 0);
2340                         btrfs_drop_extent_cache(inode, hole_start,
2341                                         last_byte - 1, 0);
2342                 }
2343                 free_extent_map(em);
2344                 cur_offset = last_byte;
2345                 if (err || cur_offset >= block_end)
2346                         break;
2347         }
2348
2349         btrfs_end_transaction(trans, root);
2350         unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
2351         return err;
2352 }
2353
2354 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
2355 {
2356         struct inode *inode = dentry->d_inode;
2357         int err;
2358
2359         err = inode_change_ok(inode, attr);
2360         if (err)
2361                 return err;
2362
2363         if (S_ISREG(inode->i_mode) &&
2364             attr->ia_valid & ATTR_SIZE && attr->ia_size > inode->i_size) {
2365                 err = btrfs_cont_expand(inode, attr->ia_size);
2366                 if (err)
2367                         return err;
2368         }
2369
2370         err = inode_setattr(inode, attr);
2371
2372         if (!err && ((attr->ia_valid & ATTR_MODE)))
2373                 err = btrfs_acl_chmod(inode);
2374         return err;
2375 }
2376
2377 void btrfs_delete_inode(struct inode *inode)
2378 {
2379         struct btrfs_trans_handle *trans;
2380         struct btrfs_root *root = BTRFS_I(inode)->root;
2381         unsigned long nr;
2382         int ret;
2383
2384         truncate_inode_pages(&inode->i_data, 0);
2385         if (is_bad_inode(inode)) {
2386                 btrfs_orphan_del(NULL, inode);
2387                 goto no_delete;
2388         }
2389         btrfs_wait_ordered_range(inode, 0, (u64)-1);
2390
2391         btrfs_i_size_write(inode, 0);
2392         trans = btrfs_start_transaction(root, 1);
2393
2394         btrfs_set_trans_block_group(trans, inode);
2395         ret = btrfs_truncate_inode_items(trans, root, inode, inode->i_size, 0);
2396         if (ret) {
2397                 btrfs_orphan_del(NULL, inode);
2398                 goto no_delete_lock;
2399         }
2400
2401         btrfs_orphan_del(trans, inode);
2402
2403         nr = trans->blocks_used;
2404         clear_inode(inode);
2405
2406         btrfs_end_transaction(trans, root);
2407         btrfs_btree_balance_dirty(root, nr);
2408         return;
2409
2410 no_delete_lock:
2411         nr = trans->blocks_used;
2412         btrfs_end_transaction(trans, root);
2413         btrfs_btree_balance_dirty(root, nr);
2414 no_delete:
2415         clear_inode(inode);
2416 }
2417
2418 /*
2419  * this returns the key found in the dir entry in the location pointer.
2420  * If no dir entries were found, location->objectid is 0.
2421  */
2422 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
2423                                struct btrfs_key *location)
2424 {
2425         const char *name = dentry->d_name.name;
2426         int namelen = dentry->d_name.len;
2427         struct btrfs_dir_item *di;
2428         struct btrfs_path *path;
2429         struct btrfs_root *root = BTRFS_I(dir)->root;
2430         int ret = 0;
2431
2432         path = btrfs_alloc_path();
2433         BUG_ON(!path);
2434
2435         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
2436                                     namelen, 0);
2437         if (IS_ERR(di))
2438                 ret = PTR_ERR(di);
2439         if (!di || IS_ERR(di)) {
2440                 goto out_err;
2441         }
2442         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
2443 out:
2444         btrfs_free_path(path);
2445         return ret;
2446 out_err:
2447         location->objectid = 0;
2448         goto out;
2449 }
2450
2451 /*
2452  * when we hit a tree root in a directory, the btrfs part of the inode
2453  * needs to be changed to reflect the root directory of the tree root.  This
2454  * is kind of like crossing a mount point.
2455  */
2456 static int fixup_tree_root_location(struct btrfs_root *root,
2457                              struct btrfs_key *location,
2458                              struct btrfs_root **sub_root,
2459                              struct dentry *dentry)
2460 {
2461         struct btrfs_root_item *ri;
2462
2463         if (btrfs_key_type(location) != BTRFS_ROOT_ITEM_KEY)
2464                 return 0;
2465         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
2466                 return 0;
2467
2468         *sub_root = btrfs_read_fs_root(root->fs_info, location,
2469                                         dentry->d_name.name,
2470                                         dentry->d_name.len);
2471         if (IS_ERR(*sub_root))
2472                 return PTR_ERR(*sub_root);
2473
2474         ri = &(*sub_root)->root_item;
2475         location->objectid = btrfs_root_dirid(ri);
2476         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
2477         location->offset = 0;
2478
2479         return 0;
2480 }
2481
2482 static noinline void init_btrfs_i(struct inode *inode)
2483 {
2484         struct btrfs_inode *bi = BTRFS_I(inode);
2485
2486         bi->i_acl = NULL;
2487         bi->i_default_acl = NULL;
2488
2489         bi->generation = 0;
2490         bi->last_trans = 0;
2491         bi->logged_trans = 0;
2492         bi->delalloc_bytes = 0;
2493         bi->disk_i_size = 0;
2494         bi->flags = 0;
2495         bi->index_cnt = (u64)-1;
2496         bi->log_dirty_trans = 0;
2497         extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
2498         extent_io_tree_init(&BTRFS_I(inode)->io_tree,
2499                              inode->i_mapping, GFP_NOFS);
2500         extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
2501                              inode->i_mapping, GFP_NOFS);
2502         INIT_LIST_HEAD(&BTRFS_I(inode)->delalloc_inodes);
2503         btrfs_ordered_inode_tree_init(&BTRFS_I(inode)->ordered_tree);
2504         mutex_init(&BTRFS_I(inode)->csum_mutex);
2505         mutex_init(&BTRFS_I(inode)->extent_mutex);
2506         mutex_init(&BTRFS_I(inode)->log_mutex);
2507 }
2508
2509 static int btrfs_init_locked_inode(struct inode *inode, void *p)
2510 {
2511         struct btrfs_iget_args *args = p;
2512         inode->i_ino = args->ino;
2513         init_btrfs_i(inode);
2514         BTRFS_I(inode)->root = args->root;
2515         return 0;
2516 }
2517
2518 static int btrfs_find_actor(struct inode *inode, void *opaque)
2519 {
2520         struct btrfs_iget_args *args = opaque;
2521         return (args->ino == inode->i_ino &&
2522                 args->root == BTRFS_I(inode)->root);
2523 }
2524
2525 struct inode *btrfs_ilookup(struct super_block *s, u64 objectid,
2526                             struct btrfs_root *root, int wait)
2527 {
2528         struct inode *inode;
2529         struct btrfs_iget_args args;
2530         args.ino = objectid;
2531         args.root = root;
2532
2533         if (wait) {
2534                 inode = ilookup5(s, objectid, btrfs_find_actor,
2535                                  (void *)&args);
2536         } else {
2537                 inode = ilookup5_nowait(s, objectid, btrfs_find_actor,
2538                                         (void *)&args);
2539         }
2540         return inode;
2541 }
2542
2543 struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid,
2544                                 struct btrfs_root *root)
2545 {
2546         struct inode *inode;
2547         struct btrfs_iget_args args;
2548         args.ino = objectid;
2549         args.root = root;
2550
2551         inode = iget5_locked(s, objectid, btrfs_find_actor,
2552                              btrfs_init_locked_inode,
2553                              (void *)&args);
2554         return inode;
2555 }
2556
2557 /* Get an inode object given its location and corresponding root.
2558  * Returns in *is_new if the inode was read from disk
2559  */
2560 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
2561                          struct btrfs_root *root, int *is_new)
2562 {
2563         struct inode *inode;
2564
2565         inode = btrfs_iget_locked(s, location->objectid, root);
2566         if (!inode)
2567                 return ERR_PTR(-EACCES);
2568
2569         if (inode->i_state & I_NEW) {
2570                 BTRFS_I(inode)->root = root;
2571                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
2572                 btrfs_read_locked_inode(inode);
2573                 unlock_new_inode(inode);
2574                 if (is_new)
2575                         *is_new = 1;
2576         } else {
2577                 if (is_new)
2578                         *is_new = 0;
2579         }
2580
2581         return inode;
2582 }
2583
2584 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
2585                                    struct nameidata *nd)
2586 {
2587         struct inode * inode;
2588         struct btrfs_inode *bi = BTRFS_I(dir);
2589         struct btrfs_root *root = bi->root;
2590         struct btrfs_root *sub_root = root;
2591         struct btrfs_key location;
2592         int ret, new, do_orphan = 0;
2593
2594         if (dentry->d_name.len > BTRFS_NAME_LEN)
2595                 return ERR_PTR(-ENAMETOOLONG);
2596
2597         ret = btrfs_inode_by_name(dir, dentry, &location);
2598
2599         if (ret < 0)
2600                 return ERR_PTR(ret);
2601
2602         inode = NULL;
2603         if (location.objectid) {
2604                 ret = fixup_tree_root_location(root, &location, &sub_root,
2605                                                 dentry);
2606                 if (ret < 0)
2607                         return ERR_PTR(ret);
2608                 if (ret > 0)
2609                         return ERR_PTR(-ENOENT);
2610                 inode = btrfs_iget(dir->i_sb, &location, sub_root, &new);
2611                 if (IS_ERR(inode))
2612                         return ERR_CAST(inode);
2613
2614                 /* the inode and parent dir are two different roots */
2615                 if (new && root != sub_root) {
2616                         igrab(inode);
2617                         sub_root->inode = inode;
2618                         do_orphan = 1;
2619                 }
2620         }
2621
2622         if (unlikely(do_orphan))
2623                 btrfs_orphan_cleanup(sub_root);
2624
2625         return d_splice_alias(inode, dentry);
2626 }
2627
2628 static unsigned char btrfs_filetype_table[] = {
2629         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
2630 };
2631
2632 static int btrfs_real_readdir(struct file *filp, void *dirent,
2633                               filldir_t filldir)
2634 {
2635         struct inode *inode = filp->f_dentry->d_inode;
2636         struct btrfs_root *root = BTRFS_I(inode)->root;
2637         struct btrfs_item *item;
2638         struct btrfs_dir_item *di;
2639         struct btrfs_key key;
2640         struct btrfs_key found_key;
2641         struct btrfs_path *path;
2642         int ret;
2643         u32 nritems;
2644         struct extent_buffer *leaf;
2645         int slot;
2646         int advance;
2647         unsigned char d_type;
2648         int over = 0;
2649         u32 di_cur;
2650         u32 di_total;
2651         u32 di_len;
2652         int key_type = BTRFS_DIR_INDEX_KEY;
2653         char tmp_name[32];
2654         char *name_ptr;
2655         int name_len;
2656
2657         /* FIXME, use a real flag for deciding about the key type */
2658         if (root->fs_info->tree_root == root)
2659                 key_type = BTRFS_DIR_ITEM_KEY;
2660
2661         /* special case for "." */
2662         if (filp->f_pos == 0) {
2663                 over = filldir(dirent, ".", 1,
2664                                1, inode->i_ino,
2665                                DT_DIR);
2666                 if (over)
2667                         return 0;
2668                 filp->f_pos = 1;
2669         }
2670         /* special case for .., just use the back ref */
2671         if (filp->f_pos == 1) {
2672                 u64 pino = parent_ino(filp->f_path.dentry);
2673                 over = filldir(dirent, "..", 2,
2674                                2, pino, DT_DIR);
2675                 if (over)
2676                         return 0;
2677                 filp->f_pos = 2;
2678         }
2679
2680         path = btrfs_alloc_path();
2681         path->reada = 2;
2682
2683         btrfs_set_key_type(&key, key_type);
2684         key.offset = filp->f_pos;
2685         key.objectid = inode->i_ino;
2686
2687         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2688         if (ret < 0)
2689                 goto err;
2690         advance = 0;
2691
2692         while (1) {
2693                 leaf = path->nodes[0];
2694                 nritems = btrfs_header_nritems(leaf);
2695                 slot = path->slots[0];
2696                 if (advance || slot >= nritems) {
2697                         if (slot >= nritems - 1) {
2698                                 ret = btrfs_next_leaf(root, path);
2699                                 if (ret)
2700                                         break;
2701                                 leaf = path->nodes[0];
2702                                 nritems = btrfs_header_nritems(leaf);
2703                                 slot = path->slots[0];
2704                         } else {
2705                                 slot++;
2706                                 path->slots[0]++;
2707                         }
2708                 }
2709                 advance = 1;
2710                 item = btrfs_item_nr(leaf, slot);
2711                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2712
2713                 if (found_key.objectid != key.objectid)
2714                         break;
2715                 if (btrfs_key_type(&found_key) != key_type)
2716                         break;
2717                 if (found_key.offset < filp->f_pos)
2718                         continue;
2719
2720                 filp->f_pos = found_key.offset;
2721
2722                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
2723                 di_cur = 0;
2724                 di_total = btrfs_item_size(leaf, item);
2725
2726                 while (di_cur < di_total) {
2727                         struct btrfs_key location;
2728
2729                         name_len = btrfs_dir_name_len(leaf, di);
2730                         if (name_len <= sizeof(tmp_name)) {
2731                                 name_ptr = tmp_name;
2732                         } else {
2733                                 name_ptr = kmalloc(name_len, GFP_NOFS);
2734                                 if (!name_ptr) {
2735                                         ret = -ENOMEM;
2736                                         goto err;
2737                                 }
2738                         }
2739                         read_extent_buffer(leaf, name_ptr,
2740                                            (unsigned long)(di + 1), name_len);
2741
2742                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
2743                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
2744                         over = filldir(dirent, name_ptr, name_len,
2745                                        found_key.offset, location.objectid,
2746                                        d_type);
2747
2748                         if (name_ptr != tmp_name)
2749                                 kfree(name_ptr);
2750
2751                         if (over)
2752                                 goto nopos;
2753
2754                         di_len = btrfs_dir_name_len(leaf, di) +
2755                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
2756                         di_cur += di_len;
2757                         di = (struct btrfs_dir_item *)((char *)di + di_len);
2758                 }
2759         }
2760
2761         /* Reached end of directory/root. Bump pos past the last item. */
2762         if (key_type == BTRFS_DIR_INDEX_KEY)
2763                 filp->f_pos = INT_LIMIT(typeof(filp->f_pos));
2764         else
2765                 filp->f_pos++;
2766 nopos:
2767         ret = 0;
2768 err:
2769         btrfs_free_path(path);
2770         return ret;
2771 }
2772
2773 int btrfs_write_inode(struct inode *inode, int wait)
2774 {
2775         struct btrfs_root *root = BTRFS_I(inode)->root;
2776         struct btrfs_trans_handle *trans;
2777         int ret = 0;
2778
2779         if (root->fs_info->closing > 1)
2780                 return 0;
2781
2782         if (wait) {
2783                 trans = btrfs_join_transaction(root, 1);
2784                 btrfs_set_trans_block_group(trans, inode);
2785                 ret = btrfs_commit_transaction(trans, root);
2786         }
2787         return ret;
2788 }
2789
2790 /*
2791  * This is somewhat expensive, updating the tree every time the
2792  * inode changes.  But, it is most likely to find the inode in cache.
2793  * FIXME, needs more benchmarking...there are no reasons other than performance
2794  * to keep or drop this code.
2795  */
2796 void btrfs_dirty_inode(struct inode *inode)
2797 {
2798         struct btrfs_root *root = BTRFS_I(inode)->root;
2799         struct btrfs_trans_handle *trans;
2800
2801         trans = btrfs_join_transaction(root, 1);
2802         btrfs_set_trans_block_group(trans, inode);
2803         btrfs_update_inode(trans, root, inode);
2804         btrfs_end_transaction(trans, root);
2805 }
2806
2807 /*
2808  * find the highest existing sequence number in a directory
2809  * and then set the in-memory index_cnt variable to reflect
2810  * free sequence numbers
2811  */
2812 static int btrfs_set_inode_index_count(struct inode *inode)
2813 {
2814         struct btrfs_root *root = BTRFS_I(inode)->root;
2815         struct btrfs_key key, found_key;
2816         struct btrfs_path *path;
2817         struct extent_buffer *leaf;
2818         int ret;
2819
2820         key.objectid = inode->i_ino;
2821         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
2822         key.offset = (u64)-1;
2823
2824         path = btrfs_alloc_path();
2825         if (!path)
2826                 return -ENOMEM;
2827
2828         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2829         if (ret < 0)
2830                 goto out;
2831         /* FIXME: we should be able to handle this */
2832         if (ret == 0)
2833                 goto out;
2834         ret = 0;
2835
2836         /*
2837          * MAGIC NUMBER EXPLANATION:
2838          * since we search a directory based on f_pos we have to start at 2
2839          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
2840          * else has to start at 2
2841          */
2842         if (path->slots[0] == 0) {
2843                 BTRFS_I(inode)->index_cnt = 2;
2844                 goto out;
2845         }
2846
2847         path->slots[0]--;
2848
2849         leaf = path->nodes[0];
2850         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2851
2852         if (found_key.objectid != inode->i_ino ||
2853             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
2854                 BTRFS_I(inode)->index_cnt = 2;
2855                 goto out;
2856         }
2857
2858         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
2859 out:
2860         btrfs_free_path(path);
2861         return ret;
2862 }
2863
2864 /*
2865  * helper to find a free sequence number in a given directory.  This current
2866  * code is very simple, later versions will do smarter things in the btree
2867  */
2868 static int btrfs_set_inode_index(struct inode *dir, struct inode *inode,
2869                                  u64 *index)
2870 {
2871         int ret = 0;
2872
2873         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
2874                 ret = btrfs_set_inode_index_count(dir);
2875                 if (ret) {
2876                         return ret;
2877                 }
2878         }
2879
2880         *index = BTRFS_I(dir)->index_cnt;
2881         BTRFS_I(dir)->index_cnt++;
2882
2883         return ret;
2884 }
2885
2886 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
2887                                      struct btrfs_root *root,
2888                                      struct inode *dir,
2889                                      const char *name, int name_len,
2890                                      u64 ref_objectid,
2891                                      u64 objectid,
2892                                      struct btrfs_block_group_cache *group,
2893                                      int mode, u64 *index)
2894 {
2895         struct inode *inode;
2896         struct btrfs_inode_item *inode_item;
2897         struct btrfs_block_group_cache *new_inode_group;
2898         struct btrfs_key *location;
2899         struct btrfs_path *path;
2900         struct btrfs_inode_ref *ref;
2901         struct btrfs_key key[2];
2902         u32 sizes[2];
2903         unsigned long ptr;
2904         int ret;
2905         int owner;
2906
2907         path = btrfs_alloc_path();
2908         BUG_ON(!path);
2909
2910         inode = new_inode(root->fs_info->sb);
2911         if (!inode)
2912                 return ERR_PTR(-ENOMEM);
2913
2914         if (dir) {
2915                 ret = btrfs_set_inode_index(dir, inode, index);
2916                 if (ret)
2917                         return ERR_PTR(ret);
2918         }
2919         /*
2920          * index_cnt is ignored for everything but a dir,
2921          * btrfs_get_inode_index_count has an explanation for the magic
2922          * number
2923          */
2924         init_btrfs_i(inode);
2925         BTRFS_I(inode)->index_cnt = 2;
2926         BTRFS_I(inode)->root = root;
2927         BTRFS_I(inode)->generation = trans->transid;
2928
2929         if (mode & S_IFDIR)
2930                 owner = 0;
2931         else
2932                 owner = 1;
2933         new_inode_group = btrfs_find_block_group(root, group, 0,
2934                                        BTRFS_BLOCK_GROUP_METADATA, owner);
2935         if (!new_inode_group) {
2936                 printk("find_block group failed\n");
2937                 new_inode_group = group;
2938         }
2939         BTRFS_I(inode)->block_group = new_inode_group;
2940
2941         key[0].objectid = objectid;
2942         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
2943         key[0].offset = 0;
2944
2945         key[1].objectid = objectid;
2946         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
2947         key[1].offset = ref_objectid;
2948
2949         sizes[0] = sizeof(struct btrfs_inode_item);
2950         sizes[1] = name_len + sizeof(*ref);
2951
2952         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
2953         if (ret != 0)
2954                 goto fail;
2955
2956         if (objectid > root->highest_inode)
2957                 root->highest_inode = objectid;
2958
2959         inode->i_uid = current->fsuid;
2960         inode->i_gid = current->fsgid;
2961         inode->i_mode = mode;
2962         inode->i_ino = objectid;
2963         inode_set_bytes(inode, 0);
2964         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
2965         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2966                                   struct btrfs_inode_item);
2967         fill_inode_item(trans, path->nodes[0], inode_item, inode);
2968
2969         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
2970                              struct btrfs_inode_ref);
2971         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
2972         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
2973         ptr = (unsigned long)(ref + 1);
2974         write_extent_buffer(path->nodes[0], name, ptr, name_len);
2975
2976         btrfs_mark_buffer_dirty(path->nodes[0]);
2977         btrfs_free_path(path);
2978
2979         location = &BTRFS_I(inode)->location;
2980         location->objectid = objectid;
2981         location->offset = 0;
2982         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
2983
2984         insert_inode_hash(inode);
2985         return inode;
2986 fail:
2987         if (dir)
2988                 BTRFS_I(dir)->index_cnt--;
2989         btrfs_free_path(path);
2990         return ERR_PTR(ret);
2991 }
2992
2993 static inline u8 btrfs_inode_type(struct inode *inode)
2994 {
2995         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
2996 }
2997
2998 /*
2999  * utility function to add 'inode' into 'parent_inode' with
3000  * a give name and a given sequence number.
3001  * if 'add_backref' is true, also insert a backref from the
3002  * inode to the parent directory.
3003  */
3004 int btrfs_add_link(struct btrfs_trans_handle *trans,
3005                    struct inode *parent_inode, struct inode *inode,
3006                    const char *name, int name_len, int add_backref, u64 index)
3007 {
3008         int ret;
3009         struct btrfs_key key;
3010         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
3011
3012         key.objectid = inode->i_ino;
3013         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
3014         key.offset = 0;
3015
3016         ret = btrfs_insert_dir_item(trans, root, name, name_len,
3017                                     parent_inode->i_ino,
3018                                     &key, btrfs_inode_type(inode),
3019                                     index);
3020         if (ret == 0) {
3021                 if (add_backref) {
3022                         ret = btrfs_insert_inode_ref(trans, root,
3023                                                      name, name_len,
3024                                                      inode->i_ino,
3025                                                      parent_inode->i_ino,
3026                                                      index);
3027                 }
3028                 btrfs_i_size_write(parent_inode, parent_inode->i_size +
3029                                    name_len * 2);
3030                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
3031                 ret = btrfs_update_inode(trans, root, parent_inode);
3032         }
3033         return ret;
3034 }
3035
3036 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
3037                             struct dentry *dentry, struct inode *inode,
3038                             int backref, u64 index)
3039 {
3040         int err = btrfs_add_link(trans, dentry->d_parent->d_inode,
3041                                  inode, dentry->d_name.name,
3042                                  dentry->d_name.len, backref, index);
3043         if (!err) {
3044                 d_instantiate(dentry, inode);
3045                 return 0;
3046         }
3047         if (err > 0)
3048                 err = -EEXIST;
3049         return err;
3050 }
3051
3052 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
3053                         int mode, dev_t rdev)
3054 {
3055         struct btrfs_trans_handle *trans;
3056         struct btrfs_root *root = BTRFS_I(dir)->root;
3057         struct inode *inode = NULL;
3058         int err;
3059         int drop_inode = 0;
3060         u64 objectid;
3061         unsigned long nr = 0;
3062         u64 index = 0;
3063
3064         if (!new_valid_dev(rdev))
3065                 return -EINVAL;
3066
3067         err = btrfs_check_free_space(root, 1, 0);
3068         if (err)
3069                 goto fail;
3070
3071         trans = btrfs_start_transaction(root, 1);
3072         btrfs_set_trans_block_group(trans, dir);
3073
3074         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3075         if (err) {
3076                 err = -ENOSPC;
3077                 goto out_unlock;
3078         }
3079
3080         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
3081                                 dentry->d_name.len,
3082                                 dentry->d_parent->d_inode->i_ino, objectid,
3083                                 BTRFS_I(dir)->block_group, mode, &index);
3084         err = PTR_ERR(inode);
3085         if (IS_ERR(inode))
3086                 goto out_unlock;
3087
3088         err = btrfs_init_acl(inode, dir);
3089         if (err) {
3090                 drop_inode = 1;
3091                 goto out_unlock;
3092         }
3093
3094         btrfs_set_trans_block_group(trans, inode);
3095         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
3096         if (err)
3097                 drop_inode = 1;
3098         else {
3099                 inode->i_op = &btrfs_special_inode_operations;
3100                 init_special_inode(inode, inode->i_mode, rdev);
3101                 btrfs_update_inode(trans, root, inode);
3102         }
3103         dir->i_sb->s_dirt = 1;
3104         btrfs_update_inode_block_group(trans, inode);
3105         btrfs_update_inode_block_group(trans, dir);
3106 out_unlock:
3107         nr = trans->blocks_used;
3108         btrfs_end_transaction_throttle(trans, root);
3109 fail:
3110         if (drop_inode) {
3111                 inode_dec_link_count(inode);
3112                 iput(inode);
3113         }
3114         btrfs_btree_balance_dirty(root, nr);
3115         return err;
3116 }
3117
3118 static int btrfs_create(struct inode *dir, struct dentry *dentry,
3119                         int mode, struct nameidata *nd)
3120 {
3121         struct btrfs_trans_handle *trans;
3122         struct btrfs_root *root = BTRFS_I(dir)->root;
3123         struct inode *inode = NULL;
3124         int err;
3125         int drop_inode = 0;
3126         unsigned long nr = 0;
3127         u64 objectid;
3128         u64 index = 0;
3129
3130         err = btrfs_check_free_space(root, 1, 0);
3131         if (err)
3132                 goto fail;
3133         trans = btrfs_start_transaction(root, 1);
3134         btrfs_set_trans_block_group(trans, dir);
3135
3136         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3137         if (err) {
3138                 err = -ENOSPC;
3139                 goto out_unlock;
3140         }
3141
3142         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
3143                                 dentry->d_name.len,
3144                                 dentry->d_parent->d_inode->i_ino,
3145                                 objectid, BTRFS_I(dir)->block_group, mode,
3146                                 &index);
3147         err = PTR_ERR(inode);
3148         if (IS_ERR(inode))
3149                 goto out_unlock;
3150
3151         err = btrfs_init_acl(inode, dir);
3152         if (err) {
3153                 drop_inode = 1;
3154                 goto out_unlock;
3155         }
3156
3157         btrfs_set_trans_block_group(trans, inode);
3158         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
3159         if (err)
3160                 drop_inode = 1;
3161         else {
3162                 inode->i_mapping->a_ops = &btrfs_aops;
3163                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3164                 inode->i_fop = &btrfs_file_operations;
3165                 inode->i_op = &btrfs_file_inode_operations;
3166                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3167         }
3168         dir->i_sb->s_dirt = 1;
3169         btrfs_update_inode_block_group(trans, inode);
3170         btrfs_update_inode_block_group(trans, dir);
3171 out_unlock:
3172         nr = trans->blocks_used;
3173         btrfs_end_transaction_throttle(trans, root);
3174 fail:
3175         if (drop_inode) {
3176                 inode_dec_link_count(inode);
3177                 iput(inode);
3178         }
3179         btrfs_btree_balance_dirty(root, nr);
3180         return err;
3181 }
3182
3183 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
3184                       struct dentry *dentry)
3185 {
3186         struct btrfs_trans_handle *trans;
3187         struct btrfs_root *root = BTRFS_I(dir)->root;
3188         struct inode *inode = old_dentry->d_inode;
3189         u64 index;
3190         unsigned long nr = 0;
3191         int err;
3192         int drop_inode = 0;
3193
3194         if (inode->i_nlink == 0)
3195                 return -ENOENT;
3196
3197         btrfs_inc_nlink(inode);
3198         err = btrfs_check_free_space(root, 1, 0);
3199         if (err)
3200                 goto fail;
3201         err = btrfs_set_inode_index(dir, inode, &index);
3202         if (err)
3203                 goto fail;
3204
3205         trans = btrfs_start_transaction(root, 1);
3206
3207         btrfs_set_trans_block_group(trans, dir);
3208         atomic_inc(&inode->i_count);
3209
3210         err = btrfs_add_nondir(trans, dentry, inode, 1, index);
3211
3212         if (err)
3213                 drop_inode = 1;
3214
3215         dir->i_sb->s_dirt = 1;
3216         btrfs_update_inode_block_group(trans, dir);
3217         err = btrfs_update_inode(trans, root, inode);
3218
3219         if (err)
3220                 drop_inode = 1;
3221
3222         nr = trans->blocks_used;
3223         btrfs_end_transaction_throttle(trans, root);
3224 fail:
3225         if (drop_inode) {
3226                 inode_dec_link_count(inode);
3227                 iput(inode);
3228         }
3229         btrfs_btree_balance_dirty(root, nr);
3230         return err;
3231 }
3232
3233 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3234 {
3235         struct inode *inode = NULL;
3236         struct btrfs_trans_handle *trans;
3237         struct btrfs_root *root = BTRFS_I(dir)->root;
3238         int err = 0;
3239         int drop_on_err = 0;
3240         u64 objectid = 0;
3241         u64 index = 0;
3242         unsigned long nr = 1;
3243
3244         err = btrfs_check_free_space(root, 1, 0);
3245         if (err)
3246                 goto out_unlock;
3247
3248         trans = btrfs_start_transaction(root, 1);
3249         btrfs_set_trans_block_group(trans, dir);
3250
3251         if (IS_ERR(trans)) {
3252                 err = PTR_ERR(trans);
3253                 goto out_unlock;
3254         }
3255
3256         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3257         if (err) {
3258                 err = -ENOSPC;
3259                 goto out_unlock;
3260         }
3261
3262         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
3263                                 dentry->d_name.len,
3264                                 dentry->d_parent->d_inode->i_ino, objectid,
3265                                 BTRFS_I(dir)->block_group, S_IFDIR | mode,
3266                                 &index);
3267         if (IS_ERR(inode)) {
3268                 err = PTR_ERR(inode);
3269                 goto out_fail;
3270         }
3271
3272         drop_on_err = 1;
3273
3274         err = btrfs_init_acl(inode, dir);
3275         if (err)
3276                 goto out_fail;
3277
3278         inode->i_op = &btrfs_dir_inode_operations;
3279         inode->i_fop = &btrfs_dir_file_operations;
3280         btrfs_set_trans_block_group(trans, inode);
3281
3282         btrfs_i_size_write(inode, 0);
3283         err = btrfs_update_inode(trans, root, inode);
3284         if (err)
3285                 goto out_fail;
3286
3287         err = btrfs_add_link(trans, dentry->d_parent->d_inode,
3288                                  inode, dentry->d_name.name,
3289                                  dentry->d_name.len, 0, index);
3290         if (err)
3291                 goto out_fail;
3292
3293         d_instantiate(dentry, inode);
3294         drop_on_err = 0;
3295         dir->i_sb->s_dirt = 1;
3296         btrfs_update_inode_block_group(trans, inode);
3297         btrfs_update_inode_block_group(trans, dir);
3298
3299 out_fail:
3300         nr = trans->blocks_used;
3301         btrfs_end_transaction_throttle(trans, root);
3302
3303 out_unlock:
3304         if (drop_on_err)
3305                 iput(inode);
3306         btrfs_btree_balance_dirty(root, nr);
3307         return err;
3308 }
3309
3310 /* helper for btfs_get_extent.  Given an existing extent in the tree,
3311  * and an extent that you want to insert, deal with overlap and insert
3312  * the new extent into the tree.
3313  */
3314 static int merge_extent_mapping(struct extent_map_tree *em_tree,
3315                                 struct extent_map *existing,
3316                                 struct extent_map *em,
3317                                 u64 map_start, u64 map_len)
3318 {
3319         u64 start_diff;
3320
3321         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
3322         start_diff = map_start - em->start;
3323         em->start = map_start;
3324         em->len = map_len;
3325         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
3326             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3327                 em->block_start += start_diff;
3328                 em->block_len -= start_diff;
3329         }
3330         return add_extent_mapping(em_tree, em);
3331 }
3332
3333 static noinline int uncompress_inline(struct btrfs_path *path,
3334                                       struct inode *inode, struct page *page,
3335                                       size_t pg_offset, u64 extent_offset,
3336                                       struct btrfs_file_extent_item *item)
3337 {
3338         int ret;
3339         struct extent_buffer *leaf = path->nodes[0];
3340         char *tmp;
3341         size_t max_size;
3342         unsigned long inline_size;
3343         unsigned long ptr;
3344
3345         WARN_ON(pg_offset != 0);
3346         max_size = btrfs_file_extent_ram_bytes(leaf, item);
3347         inline_size = btrfs_file_extent_inline_item_len(leaf,
3348                                         btrfs_item_nr(leaf, path->slots[0]));
3349         tmp = kmalloc(inline_size, GFP_NOFS);
3350         ptr = btrfs_file_extent_inline_start(item);
3351
3352         read_extent_buffer(leaf, tmp, ptr, inline_size);
3353
3354         max_size = min(PAGE_CACHE_SIZE, max_size);
3355         ret = btrfs_zlib_decompress(tmp, page, extent_offset,
3356                                     inline_size, max_size);
3357         if (ret) {
3358                 char *kaddr = kmap_atomic(page, KM_USER0);
3359                 unsigned long copy_size = min_t(u64,
3360                                   PAGE_CACHE_SIZE - pg_offset,
3361                                   max_size - extent_offset);
3362                 memset(kaddr + pg_offset, 0, copy_size);
3363                 kunmap_atomic(kaddr, KM_USER0);
3364         }
3365         kfree(tmp);
3366         return 0;
3367 }
3368
3369 /*
3370  * a bit scary, this does extent mapping from logical file offset to the disk.
3371  * the ugly parts come from merging extents from the disk with the
3372  * in-ram representation.  This gets more complex because of the data=ordered code,
3373  * where the in-ram extents might be locked pending data=ordered completion.
3374  *
3375  * This also copies inline extents directly into the page.
3376  */
3377 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
3378                                     size_t pg_offset, u64 start, u64 len,
3379                                     int create)
3380 {
3381         int ret;
3382         int err = 0;
3383         u64 bytenr;
3384         u64 extent_start = 0;
3385         u64 extent_end = 0;
3386         u64 objectid = inode->i_ino;
3387         u32 found_type;
3388         struct btrfs_path *path = NULL;
3389         struct btrfs_root *root = BTRFS_I(inode)->root;
3390         struct btrfs_file_extent_item *item;
3391         struct extent_buffer *leaf;
3392         struct btrfs_key found_key;
3393         struct extent_map *em = NULL;
3394         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3395         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3396         struct btrfs_trans_handle *trans = NULL;
3397         int compressed;
3398
3399 again:
3400         spin_lock(&em_tree->lock);
3401         em = lookup_extent_mapping(em_tree, start, len);
3402         if (em)
3403                 em->bdev = root->fs_info->fs_devices->latest_bdev;
3404         spin_unlock(&em_tree->lock);
3405
3406         if (em) {
3407                 if (em->start > start || em->start + em->len <= start)
3408                         free_extent_map(em);
3409                 else if (em->block_start == EXTENT_MAP_INLINE && page)
3410                         free_extent_map(em);
3411                 else
3412                         goto out;
3413         }
3414         em = alloc_extent_map(GFP_NOFS);
3415         if (!em) {
3416                 err = -ENOMEM;
3417                 goto out;
3418         }
3419         em->bdev = root->fs_info->fs_devices->latest_bdev;
3420         em->start = EXTENT_MAP_HOLE;
3421         em->len = (u64)-1;
3422         em->block_len = (u64)-1;
3423
3424         if (!path) {
3425                 path = btrfs_alloc_path();
3426                 BUG_ON(!path);
3427         }
3428
3429         ret = btrfs_lookup_file_extent(trans, root, path,
3430                                        objectid, start, trans != NULL);
3431         if (ret < 0) {
3432                 err = ret;
3433                 goto out;
3434         }
3435
3436         if (ret != 0) {
3437                 if (path->slots[0] == 0)
3438                         goto not_found;
3439                 path->slots[0]--;
3440         }
3441
3442         leaf = path->nodes[0];
3443         item = btrfs_item_ptr(leaf, path->slots[0],
3444                               struct btrfs_file_extent_item);
3445         /* are we inside the extent that was found? */
3446         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3447         found_type = btrfs_key_type(&found_key);
3448         if (found_key.objectid != objectid ||
3449             found_type != BTRFS_EXTENT_DATA_KEY) {
3450                 goto not_found;
3451         }
3452
3453         found_type = btrfs_file_extent_type(leaf, item);
3454         extent_start = found_key.offset;
3455         compressed = btrfs_file_extent_compression(leaf, item);
3456         if (found_type == BTRFS_FILE_EXTENT_REG) {
3457                 extent_end = extent_start +
3458                        btrfs_file_extent_num_bytes(leaf, item);
3459         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
3460                 size_t size;
3461                 size = btrfs_file_extent_inline_len(leaf, item);
3462                 extent_end = (extent_start + size + root->sectorsize - 1) &
3463                         ~((u64)root->sectorsize - 1);
3464         }
3465
3466         if (start >= extent_end) {
3467                 path->slots[0]++;
3468                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3469                         ret = btrfs_next_leaf(root, path);
3470                         if (ret < 0) {
3471                                 err = ret;
3472                                 goto out;
3473                         }
3474                         if (ret > 0)
3475                                 goto not_found;
3476                         leaf = path->nodes[0];
3477                 }
3478                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3479                 if (found_key.objectid != objectid ||
3480                     found_key.type != BTRFS_EXTENT_DATA_KEY)
3481                         goto not_found;
3482                 if (start + len <= found_key.offset)
3483                         goto not_found;
3484                 em->start = start;
3485                 em->len = found_key.offset - start;
3486                 goto not_found_em;
3487         }
3488
3489         if (found_type == BTRFS_FILE_EXTENT_REG) {
3490                 em->start = extent_start;
3491                 em->len = extent_end - extent_start;
3492                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
3493                 if (bytenr == 0) {
3494                         em->block_start = EXTENT_MAP_HOLE;
3495                         goto insert;
3496                 }
3497                 if (compressed) {
3498                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3499                         em->block_start = bytenr;
3500                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
3501                                                                          item);
3502                 } else {
3503                         bytenr += btrfs_file_extent_offset(leaf, item);
3504                         em->block_start = bytenr;
3505                         em->block_len = em->len;
3506                 }
3507                 goto insert;
3508         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
3509                 unsigned long ptr;
3510                 char *map;
3511                 size_t size;
3512                 size_t extent_offset;
3513                 size_t copy_size;
3514
3515                 em->block_start = EXTENT_MAP_INLINE;
3516                 if (!page || create) {
3517                         em->start = extent_start;
3518                         em->len = extent_end - extent_start;
3519                         goto out;
3520                 }
3521
3522                 size = btrfs_file_extent_inline_len(leaf, item);
3523                 extent_offset = page_offset(page) + pg_offset - extent_start;
3524                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
3525                                 size - extent_offset);
3526                 em->start = extent_start + extent_offset;
3527                 em->len = (copy_size + root->sectorsize - 1) &
3528                         ~((u64)root->sectorsize - 1);
3529                 if (compressed)
3530                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3531                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
3532                 if (create == 0 && !PageUptodate(page)) {
3533                         if (btrfs_file_extent_compression(leaf, item) ==
3534                             BTRFS_COMPRESS_ZLIB) {
3535                                 ret = uncompress_inline(path, inode, page,
3536                                                         pg_offset,
3537                                                         extent_offset, item);
3538                                 BUG_ON(ret);
3539                         } else {
3540                                 map = kmap(page);
3541                                 read_extent_buffer(leaf, map + pg_offset, ptr,
3542                                                    copy_size);
3543                                 kunmap(page);
3544                         }
3545                         flush_dcache_page(page);
3546                 } else if (create && PageUptodate(page)) {
3547                         if (!trans) {
3548                                 kunmap(page);
3549                                 free_extent_map(em);
3550                                 em = NULL;
3551                                 btrfs_release_path(root, path);
3552                                 trans = btrfs_join_transaction(root, 1);
3553                                 goto again;
3554                         }
3555                         map = kmap(page);
3556                         write_extent_buffer(leaf, map + pg_offset, ptr,
3557                                             copy_size);
3558                         kunmap(page);
3559                         btrfs_mark_buffer_dirty(leaf);
3560                 }
3561                 set_extent_uptodate(io_tree, em->start,
3562                                     extent_map_end(em) - 1, GFP_NOFS);
3563                 goto insert;
3564         } else {
3565                 printk("unkknown found_type %d\n", found_type);
3566                 WARN_ON(1);
3567         }
3568 not_found:
3569         em->start = start;
3570         em->len = len;
3571 not_found_em:
3572         em->block_start = EXTENT_MAP_HOLE;
3573         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
3574 insert:
3575         btrfs_release_path(root, path);
3576         if (em->start > start || extent_map_end(em) <= start) {
3577                 printk("bad extent! em: [%Lu %Lu] passed [%Lu %Lu]\n", em->start, em->len, start, len);
3578                 err = -EIO;
3579                 goto out;
3580         }
3581
3582         err = 0;
3583         spin_lock(&em_tree->lock);
3584         ret = add_extent_mapping(em_tree, em);
3585         /* it is possible that someone inserted the extent into the tree
3586          * while we had the lock dropped.  It is also possible that
3587          * an overlapping map exists in the tree
3588          */
3589         if (ret == -EEXIST) {
3590                 struct extent_map *existing;
3591
3592                 ret = 0;
3593
3594                 existing = lookup_extent_mapping(em_tree, start, len);
3595                 if (existing && (existing->start > start ||
3596                     existing->start + existing->len <= start)) {
3597                         free_extent_map(existing);
3598                         existing = NULL;
3599                 }
3600                 if (!existing) {
3601                         existing = lookup_extent_mapping(em_tree, em->start,
3602                                                          em->len);
3603                         if (existing) {
3604                                 err = merge_extent_mapping(em_tree, existing,
3605                                                            em, start,
3606                                                            root->sectorsize);
3607                                 free_extent_map(existing);
3608                                 if (err) {
3609                                         free_extent_map(em);
3610                                         em = NULL;
3611                                 }
3612                         } else {
3613                                 err = -EIO;
3614                                 printk("failing to insert %Lu %Lu\n",
3615                                        start, len);
3616                                 free_extent_map(em);
3617                                 em = NULL;
3618                         }
3619                 } else {
3620                         free_extent_map(em);
3621                         em = existing;
3622                         err = 0;
3623                 }
3624         }
3625         spin_unlock(&em_tree->lock);
3626 out:
3627         if (path)
3628                 btrfs_free_path(path);
3629         if (trans) {
3630                 ret = btrfs_end_transaction(trans, root);
3631                 if (!err) {
3632                         err = ret;
3633                 }
3634         }
3635         if (err) {
3636                 free_extent_map(em);
3637                 WARN_ON(1);
3638                 return ERR_PTR(err);
3639         }
3640         return em;
3641 }
3642
3643 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
3644                         const struct iovec *iov, loff_t offset,
3645                         unsigned long nr_segs)
3646 {
3647         return -EINVAL;
3648 }
3649
3650 static sector_t btrfs_bmap(struct address_space *mapping, sector_t iblock)
3651 {
3652         return extent_bmap(mapping, iblock, btrfs_get_extent);
3653 }
3654
3655 int btrfs_readpage(struct file *file, struct page *page)
3656 {
3657         struct extent_io_tree *tree;
3658         tree = &BTRFS_I(page->mapping->host)->io_tree;
3659         return extent_read_full_page(tree, page, btrfs_get_extent);
3660 }
3661
3662 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
3663 {
3664         struct extent_io_tree *tree;
3665
3666
3667         if (current->flags & PF_MEMALLOC) {
3668                 redirty_page_for_writepage(wbc, page);
3669                 unlock_page(page);
3670                 return 0;
3671         }
3672         tree = &BTRFS_I(page->mapping->host)->io_tree;
3673         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
3674 }
3675
3676 int btrfs_writepages(struct address_space *mapping,
3677                      struct writeback_control *wbc)
3678 {
3679         struct extent_io_tree *tree;
3680         tree = &BTRFS_I(mapping->host)->io_tree;
3681         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
3682 }
3683
3684 static int
3685 btrfs_readpages(struct file *file, struct address_space *mapping,
3686                 struct list_head *pages, unsigned nr_pages)
3687 {
3688         struct extent_io_tree *tree;
3689         tree = &BTRFS_I(mapping->host)->io_tree;
3690         return extent_readpages(tree, mapping, pages, nr_pages,
3691                                 btrfs_get_extent);
3692 }
3693 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
3694 {
3695         struct extent_io_tree *tree;
3696         struct extent_map_tree *map;
3697         int ret;
3698
3699         tree = &BTRFS_I(page->mapping->host)->io_tree;
3700         map = &BTRFS_I(page->mapping->host)->extent_tree;
3701         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
3702         if (ret == 1) {
3703                 ClearPagePrivate(page);
3704                 set_page_private(page, 0);
3705                 page_cache_release(page);
3706         }
3707         return ret;
3708 }
3709
3710 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
3711 {
3712         if (PageWriteback(page) || PageDirty(page))
3713                 return 0;
3714         return __btrfs_releasepage(page, gfp_flags);
3715 }
3716
3717 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
3718 {
3719         struct extent_io_tree *tree;
3720         struct btrfs_ordered_extent *ordered;
3721         u64 page_start = page_offset(page);
3722         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
3723
3724         wait_on_page_writeback(page);
3725         tree = &BTRFS_I(page->mapping->host)->io_tree;
3726         if (offset) {
3727                 btrfs_releasepage(page, GFP_NOFS);
3728                 return;
3729         }
3730
3731         lock_extent(tree, page_start, page_end, GFP_NOFS);
3732         ordered = btrfs_lookup_ordered_extent(page->mapping->host,
3733                                            page_offset(page));
3734         if (ordered) {
3735                 /*
3736                  * IO on this page will never be started, so we need
3737                  * to account for any ordered extents now
3738                  */
3739                 clear_extent_bit(tree, page_start, page_end,
3740                                  EXTENT_DIRTY | EXTENT_DELALLOC |
3741                                  EXTENT_LOCKED, 1, 0, GFP_NOFS);
3742                 btrfs_finish_ordered_io(page->mapping->host,
3743                                         page_start, page_end);
3744                 btrfs_put_ordered_extent(ordered);
3745                 lock_extent(tree, page_start, page_end, GFP_NOFS);
3746         }
3747         clear_extent_bit(tree, page_start, page_end,
3748                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
3749                  EXTENT_ORDERED,
3750                  1, 1, GFP_NOFS);
3751         __btrfs_releasepage(page, GFP_NOFS);
3752
3753         ClearPageChecked(page);
3754         if (PagePrivate(page)) {
3755                 ClearPagePrivate(page);
3756                 set_page_private(page, 0);
3757                 page_cache_release(page);
3758         }
3759 }
3760
3761 /*
3762  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
3763  * called from a page fault handler when a page is first dirtied. Hence we must
3764  * be careful to check for EOF conditions here. We set the page up correctly
3765  * for a written page which means we get ENOSPC checking when writing into
3766  * holes and correct delalloc and unwritten extent mapping on filesystems that
3767  * support these features.
3768  *
3769  * We are not allowed to take the i_mutex here so we have to play games to
3770  * protect against truncate races as the page could now be beyond EOF.  Because
3771  * vmtruncate() writes the inode size before removing pages, once we have the
3772  * page lock we can determine safely if the page is beyond EOF. If it is not
3773  * beyond EOF, then the page is guaranteed safe against truncation until we
3774  * unlock the page.
3775  */
3776 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct page *page)
3777 {
3778         struct inode *inode = fdentry(vma->vm_file)->d_inode;
3779         struct btrfs_root *root = BTRFS_I(inode)->root;
3780         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3781         struct btrfs_ordered_extent *ordered;
3782         char *kaddr;
3783         unsigned long zero_start;
3784         loff_t size;
3785         int ret;
3786         u64 page_start;
3787         u64 page_end;
3788
3789         ret = btrfs_check_free_space(root, PAGE_CACHE_SIZE, 0);
3790         if (ret)
3791                 goto out;
3792
3793         ret = -EINVAL;
3794 again:
3795         lock_page(page);
3796         size = i_size_read(inode);
3797         page_start = page_offset(page);
3798         page_end = page_start + PAGE_CACHE_SIZE - 1;
3799
3800         if ((page->mapping != inode->i_mapping) ||
3801             (page_start >= size)) {
3802                 /* page got truncated out from underneath us */
3803                 goto out_unlock;
3804         }
3805         wait_on_page_writeback(page);
3806
3807         lock_extent(io_tree, page_start, page_end, GFP_NOFS);
3808         set_page_extent_mapped(page);
3809
3810         /*
3811          * we can't set the delalloc bits if there are pending ordered
3812          * extents.  Drop our locks and wait for them to finish
3813          */
3814         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3815         if (ordered) {
3816                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3817                 unlock_page(page);
3818                 btrfs_start_ordered_extent(inode, ordered, 1);
3819                 btrfs_put_ordered_extent(ordered);
3820                 goto again;
3821         }
3822
3823         btrfs_set_extent_delalloc(inode, page_start, page_end);
3824         ret = 0;
3825
3826         /* page is wholly or partially inside EOF */
3827         if (page_start + PAGE_CACHE_SIZE > size)
3828                 zero_start = size & ~PAGE_CACHE_MASK;
3829         else
3830                 zero_start = PAGE_CACHE_SIZE;
3831
3832         if (zero_start != PAGE_CACHE_SIZE) {
3833                 kaddr = kmap(page);
3834                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
3835                 flush_dcache_page(page);
3836                 kunmap(page);
3837         }
3838         ClearPageChecked(page);
3839         set_page_dirty(page);
3840         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3841
3842 out_unlock:
3843         unlock_page(page);
3844 out:
3845         return ret;
3846 }
3847
3848 static void btrfs_truncate(struct inode *inode)
3849 {
3850         struct btrfs_root *root = BTRFS_I(inode)->root;
3851         int ret;
3852         struct btrfs_trans_handle *trans;
3853         unsigned long nr;
3854         u64 mask = root->sectorsize - 1;
3855
3856         if (!S_ISREG(inode->i_mode))
3857                 return;
3858         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
3859                 return;
3860
3861         btrfs_truncate_page(inode->i_mapping, inode->i_size);
3862         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
3863
3864         trans = btrfs_start_transaction(root, 1);
3865         btrfs_set_trans_block_group(trans, inode);
3866         btrfs_i_size_write(inode, inode->i_size);
3867
3868         ret = btrfs_orphan_add(trans, inode);
3869         if (ret)
3870                 goto out;
3871         /* FIXME, add redo link to tree so we don't leak on crash */
3872         ret = btrfs_truncate_inode_items(trans, root, inode, inode->i_size,
3873                                       BTRFS_EXTENT_DATA_KEY);
3874         btrfs_update_inode(trans, root, inode);
3875
3876         ret = btrfs_orphan_del(trans, inode);
3877         BUG_ON(ret);
3878
3879 out:
3880         nr = trans->blocks_used;
3881         ret = btrfs_end_transaction_throttle(trans, root);
3882         BUG_ON(ret);
3883         btrfs_btree_balance_dirty(root, nr);
3884 }
3885
3886 /*
3887  * Invalidate a single dcache entry at the root of the filesystem.
3888  * Needed after creation of snapshot or subvolume.
3889  */
3890 void btrfs_invalidate_dcache_root(struct btrfs_root *root, char *name,
3891                                   int namelen)
3892 {
3893         struct dentry *alias, *entry;
3894         struct qstr qstr;
3895
3896         alias = d_find_alias(root->fs_info->sb->s_root->d_inode);
3897         if (alias) {
3898                 qstr.name = name;
3899                 qstr.len = namelen;
3900                 /* change me if btrfs ever gets a d_hash operation */
3901                 qstr.hash = full_name_hash(qstr.name, qstr.len);
3902                 entry = d_lookup(alias, &qstr);
3903                 dput(alias);
3904                 if (entry) {
3905                         d_invalidate(entry);
3906                         dput(entry);
3907                 }
3908         }
3909 }
3910
3911 /*
3912  * create a new subvolume directory/inode (helper for the ioctl).
3913  */
3914 int btrfs_create_subvol_root(struct btrfs_root *new_root, struct dentry *dentry,
3915                 struct btrfs_trans_handle *trans, u64 new_dirid,
3916                 struct btrfs_block_group_cache *block_group)
3917 {
3918         struct inode *inode;
3919         int error;
3920         u64 index = 0;
3921
3922         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
3923                                 new_dirid, block_group, S_IFDIR | 0700, &index);
3924         if (IS_ERR(inode))
3925                 return PTR_ERR(inode);
3926         inode->i_op = &btrfs_dir_inode_operations;
3927         inode->i_fop = &btrfs_dir_file_operations;
3928         new_root->inode = inode;
3929
3930         inode->i_nlink = 1;
3931         btrfs_i_size_write(inode, 0);
3932
3933         error = btrfs_update_inode(trans, new_root, inode);
3934         if (error)
3935                 return error;
3936
3937         d_instantiate(dentry, inode);
3938         return 0;
3939 }
3940
3941 /* helper function for file defrag and space balancing.  This
3942  * forces readahead on a given range of bytes in an inode
3943  */
3944 unsigned long btrfs_force_ra(struct address_space *mapping,
3945                               struct file_ra_state *ra, struct file *file,
3946                               pgoff_t offset, pgoff_t last_index)
3947 {
3948         pgoff_t req_size = last_index - offset + 1;
3949
3950         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
3951         return offset + req_size;
3952 }
3953
3954 struct inode *btrfs_alloc_inode(struct super_block *sb)
3955 {
3956         struct btrfs_inode *ei;
3957
3958         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
3959         if (!ei)
3960                 return NULL;
3961         ei->last_trans = 0;
3962         ei->logged_trans = 0;
3963         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
3964         ei->i_acl = BTRFS_ACL_NOT_CACHED;
3965         ei->i_default_acl = BTRFS_ACL_NOT_CACHED;
3966         INIT_LIST_HEAD(&ei->i_orphan);
3967         return &ei->vfs_inode;
3968 }
3969
3970 void btrfs_destroy_inode(struct inode *inode)
3971 {
3972         struct btrfs_ordered_extent *ordered;
3973         WARN_ON(!list_empty(&inode->i_dentry));
3974         WARN_ON(inode->i_data.nrpages);
3975
3976         if (BTRFS_I(inode)->i_acl &&
3977             BTRFS_I(inode)->i_acl != BTRFS_ACL_NOT_CACHED)
3978                 posix_acl_release(BTRFS_I(inode)->i_acl);
3979         if (BTRFS_I(inode)->i_default_acl &&
3980             BTRFS_I(inode)->i_default_acl != BTRFS_ACL_NOT_CACHED)
3981                 posix_acl_release(BTRFS_I(inode)->i_default_acl);
3982
3983         spin_lock(&BTRFS_I(inode)->root->list_lock);
3984         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
3985                 printk(KERN_ERR "BTRFS: inode %lu: inode still on the orphan"
3986                        " list\n", inode->i_ino);
3987                 dump_stack();
3988         }
3989         spin_unlock(&BTRFS_I(inode)->root->list_lock);
3990
3991         while(1) {
3992                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
3993                 if (!ordered)
3994                         break;
3995                 else {
3996                         printk("found ordered extent %Lu %Lu\n",
3997                                ordered->file_offset, ordered->len);
3998                         btrfs_remove_ordered_extent(inode, ordered);
3999                         btrfs_put_ordered_extent(ordered);
4000                         btrfs_put_ordered_extent(ordered);
4001                 }
4002         }
4003         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
4004         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
4005 }
4006
4007 static void init_once(void *foo)
4008 {
4009         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
4010
4011         inode_init_once(&ei->vfs_inode);
4012 }
4013
4014 void btrfs_destroy_cachep(void)
4015 {
4016         if (btrfs_inode_cachep)
4017                 kmem_cache_destroy(btrfs_inode_cachep);
4018         if (btrfs_trans_handle_cachep)
4019                 kmem_cache_destroy(btrfs_trans_handle_cachep);
4020         if (btrfs_transaction_cachep)
4021                 kmem_cache_destroy(btrfs_transaction_cachep);
4022         if (btrfs_bit_radix_cachep)
4023                 kmem_cache_destroy(btrfs_bit_radix_cachep);
4024         if (btrfs_path_cachep)
4025                 kmem_cache_destroy(btrfs_path_cachep);
4026 }
4027
4028 struct kmem_cache *btrfs_cache_create(const char *name, size_t size,
4029                                        unsigned long extra_flags,
4030                                        void (*ctor)(void *))
4031 {
4032         return kmem_cache_create(name, size, 0, (SLAB_RECLAIM_ACCOUNT |
4033                                  SLAB_MEM_SPREAD | extra_flags), ctor);
4034 }
4035
4036 int btrfs_init_cachep(void)
4037 {
4038         btrfs_inode_cachep = btrfs_cache_create("btrfs_inode_cache",
4039                                           sizeof(struct btrfs_inode),
4040                                           0, init_once);
4041         if (!btrfs_inode_cachep)
4042                 goto fail;
4043         btrfs_trans_handle_cachep =
4044                         btrfs_cache_create("btrfs_trans_handle_cache",
4045                                            sizeof(struct btrfs_trans_handle),
4046                                            0, NULL);
4047         if (!btrfs_trans_handle_cachep)
4048                 goto fail;
4049         btrfs_transaction_cachep = btrfs_cache_create("btrfs_transaction_cache",
4050                                              sizeof(struct btrfs_transaction),
4051                                              0, NULL);
4052         if (!btrfs_transaction_cachep)
4053                 goto fail;
4054         btrfs_path_cachep = btrfs_cache_create("btrfs_path_cache",
4055                                          sizeof(struct btrfs_path),
4056                                          0, NULL);
4057         if (!btrfs_path_cachep)
4058                 goto fail;
4059         btrfs_bit_radix_cachep = btrfs_cache_create("btrfs_radix", 256,
4060                                               SLAB_DESTROY_BY_RCU, NULL);
4061         if (!btrfs_bit_radix_cachep)
4062                 goto fail;
4063         return 0;
4064 fail:
4065         btrfs_destroy_cachep();
4066         return -ENOMEM;
4067 }
4068
4069 static int btrfs_getattr(struct vfsmount *mnt,
4070                          struct dentry *dentry, struct kstat *stat)
4071 {
4072         struct inode *inode = dentry->d_inode;
4073         generic_fillattr(inode, stat);
4074         stat->blksize = PAGE_CACHE_SIZE;
4075         stat->blocks = (inode_get_bytes(inode) +
4076                         BTRFS_I(inode)->delalloc_bytes) >> 9;
4077         return 0;
4078 }
4079
4080 static int btrfs_rename(struct inode * old_dir, struct dentry *old_dentry,
4081                            struct inode * new_dir,struct dentry *new_dentry)
4082 {
4083         struct btrfs_trans_handle *trans;
4084         struct btrfs_root *root = BTRFS_I(old_dir)->root;
4085         struct inode *new_inode = new_dentry->d_inode;
4086         struct inode *old_inode = old_dentry->d_inode;
4087         struct timespec ctime = CURRENT_TIME;
4088         u64 index = 0;
4089         int ret;
4090
4091         if (S_ISDIR(old_inode->i_mode) && new_inode &&
4092             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
4093                 return -ENOTEMPTY;
4094         }
4095
4096         ret = btrfs_check_free_space(root, 1, 0);
4097         if (ret)
4098                 goto out_unlock;
4099
4100         trans = btrfs_start_transaction(root, 1);
4101
4102         btrfs_set_trans_block_group(trans, new_dir);
4103
4104         btrfs_inc_nlink(old_dentry->d_inode);
4105         old_dir->i_ctime = old_dir->i_mtime = ctime;
4106         new_dir->i_ctime = new_dir->i_mtime = ctime;
4107         old_inode->i_ctime = ctime;
4108
4109         ret = btrfs_unlink_inode(trans, root, old_dir, old_dentry->d_inode,
4110                                  old_dentry->d_name.name,
4111                                  old_dentry->d_name.len);
4112         if (ret)
4113                 goto out_fail;
4114
4115         if (new_inode) {
4116                 new_inode->i_ctime = CURRENT_TIME;
4117                 ret = btrfs_unlink_inode(trans, root, new_dir,
4118                                          new_dentry->d_inode,
4119                                          new_dentry->d_name.name,
4120                                          new_dentry->d_name.len);
4121                 if (ret)
4122                         goto out_fail;
4123                 if (new_inode->i_nlink == 0) {
4124                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
4125                         if (ret)
4126                                 goto out_fail;
4127                 }
4128
4129         }
4130         ret = btrfs_set_inode_index(new_dir, old_inode, &index);
4131         if (ret)
4132                 goto out_fail;
4133
4134         ret = btrfs_add_link(trans, new_dentry->d_parent->d_inode,
4135                              old_inode, new_dentry->d_name.name,
4136                              new_dentry->d_name.len, 1, index);
4137         if (ret)
4138                 goto out_fail;
4139
4140 out_fail:
4141         btrfs_end_transaction_throttle(trans, root);
4142 out_unlock:
4143         return ret;
4144 }
4145
4146 /*
4147  * some fairly slow code that needs optimization. This walks the list
4148  * of all the inodes with pending delalloc and forces them to disk.
4149  */
4150 int btrfs_start_delalloc_inodes(struct btrfs_root *root)
4151 {
4152         struct list_head *head = &root->fs_info->delalloc_inodes;
4153         struct btrfs_inode *binode;
4154         struct inode *inode;
4155         unsigned long flags;
4156
4157         spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
4158         while(!list_empty(head)) {
4159                 binode = list_entry(head->next, struct btrfs_inode,
4160                                     delalloc_inodes);
4161                 inode = igrab(&binode->vfs_inode);
4162                 if (!inode)
4163                         list_del_init(&binode->delalloc_inodes);
4164                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
4165                 if (inode) {
4166                         filemap_flush(inode->i_mapping);
4167                         iput(inode);
4168                 }
4169                 cond_resched();
4170                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
4171         }
4172         spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
4173
4174         /* the filemap_flush will queue IO into the worker threads, but
4175          * we have to make sure the IO is actually started and that
4176          * ordered extents get created before we return
4177          */
4178         atomic_inc(&root->fs_info->async_submit_draining);
4179         while(atomic_read(&root->fs_info->nr_async_submits)) {
4180                 wait_event(root->fs_info->async_submit_wait,
4181                    (atomic_read(&root->fs_info->nr_async_submits) == 0));
4182         }
4183         atomic_dec(&root->fs_info->async_submit_draining);
4184         return 0;
4185 }
4186
4187 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
4188                          const char *symname)
4189 {
4190         struct btrfs_trans_handle *trans;
4191         struct btrfs_root *root = BTRFS_I(dir)->root;
4192         struct btrfs_path *path;
4193         struct btrfs_key key;
4194         struct inode *inode = NULL;
4195         int err;
4196         int drop_inode = 0;
4197         u64 objectid;
4198         u64 index = 0 ;
4199         int name_len;
4200         int datasize;
4201         unsigned long ptr;
4202         struct btrfs_file_extent_item *ei;
4203         struct extent_buffer *leaf;
4204         unsigned long nr = 0;
4205
4206         name_len = strlen(symname) + 1;
4207         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
4208                 return -ENAMETOOLONG;
4209
4210         err = btrfs_check_free_space(root, 1, 0);
4211         if (err)
4212                 goto out_fail;
4213
4214         trans = btrfs_start_transaction(root, 1);
4215         btrfs_set_trans_block_group(trans, dir);
4216
4217         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
4218         if (err) {
4219                 err = -ENOSPC;
4220                 goto out_unlock;
4221         }
4222
4223         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4224                                 dentry->d_name.len,
4225                                 dentry->d_parent->d_inode->i_ino, objectid,
4226                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
4227                                 &index);
4228         err = PTR_ERR(inode);
4229         if (IS_ERR(inode))
4230                 goto out_unlock;
4231
4232         err = btrfs_init_acl(inode, dir);
4233         if (err) {
4234                 drop_inode = 1;
4235                 goto out_unlock;
4236         }
4237
4238         btrfs_set_trans_block_group(trans, inode);
4239         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4240         if (err)
4241                 drop_inode = 1;
4242         else {
4243                 inode->i_mapping->a_ops = &btrfs_aops;
4244                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4245                 inode->i_fop = &btrfs_file_operations;
4246                 inode->i_op = &btrfs_file_inode_operations;
4247                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4248         }
4249         dir->i_sb->s_dirt = 1;
4250         btrfs_update_inode_block_group(trans, inode);
4251         btrfs_update_inode_block_group(trans, dir);
4252         if (drop_inode)
4253                 goto out_unlock;
4254
4255         path = btrfs_alloc_path();
4256         BUG_ON(!path);
4257         key.objectid = inode->i_ino;
4258         key.offset = 0;
4259         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
4260         datasize = btrfs_file_extent_calc_inline_size(name_len);
4261         err = btrfs_insert_empty_item(trans, root, path, &key,
4262                                       datasize);
4263         if (err) {
4264                 drop_inode = 1;
4265                 goto out_unlock;
4266         }
4267         leaf = path->nodes[0];
4268         ei = btrfs_item_ptr(leaf, path->slots[0],
4269                             struct btrfs_file_extent_item);
4270         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
4271         btrfs_set_file_extent_type(leaf, ei,
4272                                    BTRFS_FILE_EXTENT_INLINE);
4273         btrfs_set_file_extent_encryption(leaf, ei, 0);
4274         btrfs_set_file_extent_compression(leaf, ei, 0);
4275         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
4276         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
4277
4278         ptr = btrfs_file_extent_inline_start(ei);
4279         write_extent_buffer(leaf, symname, ptr, name_len);
4280         btrfs_mark_buffer_dirty(leaf);
4281         btrfs_free_path(path);
4282
4283         inode->i_op = &btrfs_symlink_inode_operations;
4284         inode->i_mapping->a_ops = &btrfs_symlink_aops;
4285         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4286         btrfs_i_size_write(inode, name_len - 1);
4287         err = btrfs_update_inode(trans, root, inode);
4288         if (err)
4289                 drop_inode = 1;
4290
4291 out_unlock:
4292         nr = trans->blocks_used;
4293         btrfs_end_transaction_throttle(trans, root);
4294 out_fail:
4295         if (drop_inode) {
4296                 inode_dec_link_count(inode);
4297                 iput(inode);
4298         }
4299         btrfs_btree_balance_dirty(root, nr);
4300         return err;
4301 }
4302
4303 static int btrfs_set_page_dirty(struct page *page)
4304 {
4305         return __set_page_dirty_nobuffers(page);
4306 }
4307
4308 static int btrfs_permission(struct inode *inode, int mask)
4309 {
4310         if (btrfs_test_flag(inode, READONLY) && (mask & MAY_WRITE))
4311                 return -EACCES;
4312         return generic_permission(inode, mask, btrfs_check_acl);
4313 }
4314
4315 static struct inode_operations btrfs_dir_inode_operations = {
4316         .lookup         = btrfs_lookup,
4317         .create         = btrfs_create,
4318         .unlink         = btrfs_unlink,
4319         .link           = btrfs_link,
4320         .mkdir          = btrfs_mkdir,
4321         .rmdir          = btrfs_rmdir,
4322         .rename         = btrfs_rename,
4323         .symlink        = btrfs_symlink,
4324         .setattr        = btrfs_setattr,
4325         .mknod          = btrfs_mknod,
4326         .setxattr       = btrfs_setxattr,
4327         .getxattr       = btrfs_getxattr,
4328         .listxattr      = btrfs_listxattr,
4329         .removexattr    = btrfs_removexattr,
4330         .permission     = btrfs_permission,
4331 };
4332 static struct inode_operations btrfs_dir_ro_inode_operations = {
4333         .lookup         = btrfs_lookup,
4334         .permission     = btrfs_permission,
4335 };
4336 static struct file_operations btrfs_dir_file_operations = {
4337         .llseek         = generic_file_llseek,
4338         .read           = generic_read_dir,
4339         .readdir        = btrfs_real_readdir,
4340         .unlocked_ioctl = btrfs_ioctl,
4341 #ifdef CONFIG_COMPAT
4342         .compat_ioctl   = btrfs_ioctl,
4343 #endif
4344         .release        = btrfs_release_file,
4345         .fsync          = btrfs_sync_file,
4346 };
4347
4348 static struct extent_io_ops btrfs_extent_io_ops = {
4349         .fill_delalloc = run_delalloc_range,
4350         .submit_bio_hook = btrfs_submit_bio_hook,
4351         .merge_bio_hook = btrfs_merge_bio_hook,
4352         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
4353         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
4354         .writepage_start_hook = btrfs_writepage_start_hook,
4355         .readpage_io_failed_hook = btrfs_io_failed_hook,
4356         .set_bit_hook = btrfs_set_bit_hook,
4357         .clear_bit_hook = btrfs_clear_bit_hook,
4358 };
4359
4360 static struct address_space_operations btrfs_aops = {
4361         .readpage       = btrfs_readpage,
4362         .writepage      = btrfs_writepage,
4363         .writepages     = btrfs_writepages,
4364         .readpages      = btrfs_readpages,
4365         .sync_page      = block_sync_page,
4366         .bmap           = btrfs_bmap,
4367         .direct_IO      = btrfs_direct_IO,
4368         .invalidatepage = btrfs_invalidatepage,
4369         .releasepage    = btrfs_releasepage,
4370         .set_page_dirty = btrfs_set_page_dirty,
4371 };
4372
4373 static struct address_space_operations btrfs_symlink_aops = {
4374         .readpage       = btrfs_readpage,
4375         .writepage      = btrfs_writepage,
4376         .invalidatepage = btrfs_invalidatepage,
4377         .releasepage    = btrfs_releasepage,
4378 };
4379
4380 static struct inode_operations btrfs_file_inode_operations = {
4381         .truncate       = btrfs_truncate,
4382         .getattr        = btrfs_getattr,
4383         .setattr        = btrfs_setattr,
4384         .setxattr       = btrfs_setxattr,
4385         .getxattr       = btrfs_getxattr,
4386         .listxattr      = btrfs_listxattr,
4387         .removexattr    = btrfs_removexattr,
4388         .permission     = btrfs_permission,
4389 };
4390 static struct inode_operations btrfs_special_inode_operations = {
4391         .getattr        = btrfs_getattr,
4392         .setattr        = btrfs_setattr,
4393         .permission     = btrfs_permission,
4394         .setxattr       = btrfs_setxattr,
4395         .getxattr       = btrfs_getxattr,
4396         .listxattr      = btrfs_listxattr,
4397         .removexattr    = btrfs_removexattr,
4398 };
4399 static struct inode_operations btrfs_symlink_inode_operations = {
4400         .readlink       = generic_readlink,
4401         .follow_link    = page_follow_link_light,
4402         .put_link       = page_put_link,
4403         .permission     = btrfs_permission,
4404 };