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