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