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