Btrfs: create special free space cache inode
[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/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.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 "compression.h"
52 #include "locking.h"
53
54 struct btrfs_iget_args {
55         u64 ino;
56         struct btrfs_root *root;
57 };
58
59 static const struct inode_operations btrfs_dir_inode_operations;
60 static const struct inode_operations btrfs_symlink_inode_operations;
61 static const struct inode_operations btrfs_dir_ro_inode_operations;
62 static const struct inode_operations btrfs_special_inode_operations;
63 static const struct inode_operations btrfs_file_inode_operations;
64 static const struct address_space_operations btrfs_aops;
65 static const struct address_space_operations btrfs_symlink_aops;
66 static const struct file_operations btrfs_dir_file_operations;
67 static struct extent_io_ops btrfs_extent_io_ops;
68
69 static struct kmem_cache *btrfs_inode_cachep;
70 struct kmem_cache *btrfs_trans_handle_cachep;
71 struct kmem_cache *btrfs_transaction_cachep;
72 struct kmem_cache *btrfs_path_cachep;
73
74 #define S_SHIFT 12
75 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
76         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
77         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
78         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
79         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
80         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
81         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
82         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
83 };
84
85 static void btrfs_truncate(struct inode *inode);
86 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
87 static noinline int cow_file_range(struct inode *inode,
88                                    struct page *locked_page,
89                                    u64 start, u64 end, int *page_started,
90                                    unsigned long *nr_written, int unlock);
91
92 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
93                                      struct inode *inode,  struct inode *dir)
94 {
95         int err;
96
97         err = btrfs_init_acl(trans, inode, dir);
98         if (!err)
99                 err = btrfs_xattr_security_init(trans, inode, dir);
100         return err;
101 }
102
103 /*
104  * this does all the hard work for inserting an inline extent into
105  * the btree.  The caller should have done a btrfs_drop_extents so that
106  * no overlapping inline items exist in the btree
107  */
108 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
109                                 struct btrfs_root *root, struct inode *inode,
110                                 u64 start, size_t size, size_t compressed_size,
111                                 struct page **compressed_pages)
112 {
113         struct btrfs_key key;
114         struct btrfs_path *path;
115         struct extent_buffer *leaf;
116         struct page *page = NULL;
117         char *kaddr;
118         unsigned long ptr;
119         struct btrfs_file_extent_item *ei;
120         int err = 0;
121         int ret;
122         size_t cur_size = size;
123         size_t datasize;
124         unsigned long offset;
125         int use_compress = 0;
126
127         if (compressed_size && compressed_pages) {
128                 use_compress = 1;
129                 cur_size = compressed_size;
130         }
131
132         path = btrfs_alloc_path();
133         if (!path)
134                 return -ENOMEM;
135
136         path->leave_spinning = 1;
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_atomic(cpage, KM_USER0);
171                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
172                         kunmap_atomic(kaddr, KM_USER0);
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         /*
194          * we're an inline extent, so nobody can
195          * extend the file past i_size without locking
196          * a page we already have locked.
197          *
198          * We must do any isize and inode updates
199          * before we unlock the pages.  Otherwise we
200          * could end up racing with unlink.
201          */
202         BTRFS_I(inode)->disk_i_size = inode->i_size;
203         btrfs_update_inode(trans, root, inode);
204
205         return 0;
206 fail:
207         btrfs_free_path(path);
208         return err;
209 }
210
211
212 /*
213  * conditionally insert an inline extent into the file.  This
214  * does the checks required to make sure the data is small enough
215  * to fit as an inline extent.
216  */
217 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
218                                  struct btrfs_root *root,
219                                  struct inode *inode, u64 start, u64 end,
220                                  size_t compressed_size,
221                                  struct page **compressed_pages)
222 {
223         u64 isize = i_size_read(inode);
224         u64 actual_end = min(end + 1, isize);
225         u64 inline_len = actual_end - start;
226         u64 aligned_end = (end + root->sectorsize - 1) &
227                         ~((u64)root->sectorsize - 1);
228         u64 hint_byte;
229         u64 data_len = inline_len;
230         int ret;
231
232         if (compressed_size)
233                 data_len = compressed_size;
234
235         if (start > 0 ||
236             actual_end >= PAGE_CACHE_SIZE ||
237             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
238             (!compressed_size &&
239             (actual_end & (root->sectorsize - 1)) == 0) ||
240             end + 1 < isize ||
241             data_len > root->fs_info->max_inline) {
242                 return 1;
243         }
244
245         ret = btrfs_drop_extents(trans, inode, start, aligned_end,
246                                  &hint_byte, 1);
247         BUG_ON(ret);
248
249         if (isize > actual_end)
250                 inline_len = min_t(u64, isize, actual_end);
251         ret = insert_inline_extent(trans, root, inode, start,
252                                    inline_len, compressed_size,
253                                    compressed_pages);
254         BUG_ON(ret);
255         btrfs_delalloc_release_metadata(inode, end + 1 - start);
256         btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
257         return 0;
258 }
259
260 struct async_extent {
261         u64 start;
262         u64 ram_size;
263         u64 compressed_size;
264         struct page **pages;
265         unsigned long nr_pages;
266         struct list_head list;
267 };
268
269 struct async_cow {
270         struct inode *inode;
271         struct btrfs_root *root;
272         struct page *locked_page;
273         u64 start;
274         u64 end;
275         struct list_head extents;
276         struct btrfs_work work;
277 };
278
279 static noinline int add_async_extent(struct async_cow *cow,
280                                      u64 start, u64 ram_size,
281                                      u64 compressed_size,
282                                      struct page **pages,
283                                      unsigned long nr_pages)
284 {
285         struct async_extent *async_extent;
286
287         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
288         async_extent->start = start;
289         async_extent->ram_size = ram_size;
290         async_extent->compressed_size = compressed_size;
291         async_extent->pages = pages;
292         async_extent->nr_pages = nr_pages;
293         list_add_tail(&async_extent->list, &cow->extents);
294         return 0;
295 }
296
297 /*
298  * we create compressed extents in two phases.  The first
299  * phase compresses a range of pages that have already been
300  * locked (both pages and state bits are locked).
301  *
302  * This is done inside an ordered work queue, and the compression
303  * is spread across many cpus.  The actual IO submission is step
304  * two, and the ordered work queue takes care of making sure that
305  * happens in the same order things were put onto the queue by
306  * writepages and friends.
307  *
308  * If this code finds it can't get good compression, it puts an
309  * entry onto the work queue to write the uncompressed bytes.  This
310  * makes sure that both compressed inodes and uncompressed inodes
311  * are written in the same order that pdflush sent them down.
312  */
313 static noinline int compress_file_range(struct inode *inode,
314                                         struct page *locked_page,
315                                         u64 start, u64 end,
316                                         struct async_cow *async_cow,
317                                         int *num_added)
318 {
319         struct btrfs_root *root = BTRFS_I(inode)->root;
320         struct btrfs_trans_handle *trans;
321         u64 num_bytes;
322         u64 orig_start;
323         u64 disk_num_bytes;
324         u64 blocksize = root->sectorsize;
325         u64 actual_end;
326         u64 isize = i_size_read(inode);
327         int ret = 0;
328         struct page **pages = NULL;
329         unsigned long nr_pages;
330         unsigned long nr_pages_ret = 0;
331         unsigned long total_compressed = 0;
332         unsigned long total_in = 0;
333         unsigned long max_compressed = 128 * 1024;
334         unsigned long max_uncompressed = 128 * 1024;
335         int i;
336         int will_compress;
337
338         orig_start = start;
339
340         actual_end = min_t(u64, isize, end + 1);
341 again:
342         will_compress = 0;
343         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
344         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
345
346         /*
347          * we don't want to send crud past the end of i_size through
348          * compression, that's just a waste of CPU time.  So, if the
349          * end of the file is before the start of our current
350          * requested range of bytes, we bail out to the uncompressed
351          * cleanup code that can deal with all of this.
352          *
353          * It isn't really the fastest way to fix things, but this is a
354          * very uncommon corner.
355          */
356         if (actual_end <= start)
357                 goto cleanup_and_bail_uncompressed;
358
359         total_compressed = actual_end - start;
360
361         /* we want to make sure that amount of ram required to uncompress
362          * an extent is reasonable, so we limit the total size in ram
363          * of a compressed extent to 128k.  This is a crucial number
364          * because it also controls how easily we can spread reads across
365          * cpus for decompression.
366          *
367          * We also want to make sure the amount of IO required to do
368          * a random read is reasonably small, so we limit the size of
369          * a compressed extent to 128k.
370          */
371         total_compressed = min(total_compressed, max_uncompressed);
372         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
373         num_bytes = max(blocksize,  num_bytes);
374         disk_num_bytes = num_bytes;
375         total_in = 0;
376         ret = 0;
377
378         /*
379          * we do compression for mount -o compress and when the
380          * inode has not been flagged as nocompress.  This flag can
381          * change at any time if we discover bad compression ratios.
382          */
383         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
384             (btrfs_test_opt(root, COMPRESS) ||
385              (BTRFS_I(inode)->force_compress))) {
386                 WARN_ON(pages);
387                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
388
389                 ret = btrfs_zlib_compress_pages(inode->i_mapping, start,
390                                                 total_compressed, pages,
391                                                 nr_pages, &nr_pages_ret,
392                                                 &total_in,
393                                                 &total_compressed,
394                                                 max_compressed);
395
396                 if (!ret) {
397                         unsigned long offset = total_compressed &
398                                 (PAGE_CACHE_SIZE - 1);
399                         struct page *page = pages[nr_pages_ret - 1];
400                         char *kaddr;
401
402                         /* zero the tail end of the last page, we might be
403                          * sending it down to disk
404                          */
405                         if (offset) {
406                                 kaddr = kmap_atomic(page, KM_USER0);
407                                 memset(kaddr + offset, 0,
408                                        PAGE_CACHE_SIZE - offset);
409                                 kunmap_atomic(kaddr, KM_USER0);
410                         }
411                         will_compress = 1;
412                 }
413         }
414         if (start == 0) {
415                 trans = btrfs_join_transaction(root, 1);
416                 BUG_ON(!trans);
417                 btrfs_set_trans_block_group(trans, inode);
418                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
419
420                 /* lets try to make an inline extent */
421                 if (ret || total_in < (actual_end - start)) {
422                         /* we didn't compress the entire range, try
423                          * to make an uncompressed inline extent.
424                          */
425                         ret = cow_file_range_inline(trans, root, inode,
426                                                     start, end, 0, NULL);
427                 } else {
428                         /* try making a compressed inline extent */
429                         ret = cow_file_range_inline(trans, root, inode,
430                                                     start, end,
431                                                     total_compressed, pages);
432                 }
433                 if (ret == 0) {
434                         /*
435                          * inline extent creation worked, we don't need
436                          * to create any more async work items.  Unlock
437                          * and free up our temp pages.
438                          */
439                         extent_clear_unlock_delalloc(inode,
440                              &BTRFS_I(inode)->io_tree,
441                              start, end, NULL,
442                              EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
443                              EXTENT_CLEAR_DELALLOC |
444                              EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
445
446                         btrfs_end_transaction(trans, root);
447                         goto free_pages_out;
448                 }
449                 btrfs_end_transaction(trans, root);
450         }
451
452         if (will_compress) {
453                 /*
454                  * we aren't doing an inline extent round the compressed size
455                  * up to a block size boundary so the allocator does sane
456                  * things
457                  */
458                 total_compressed = (total_compressed + blocksize - 1) &
459                         ~(blocksize - 1);
460
461                 /*
462                  * one last check to make sure the compression is really a
463                  * win, compare the page count read with the blocks on disk
464                  */
465                 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
466                         ~(PAGE_CACHE_SIZE - 1);
467                 if (total_compressed >= total_in) {
468                         will_compress = 0;
469                 } else {
470                         disk_num_bytes = total_compressed;
471                         num_bytes = total_in;
472                 }
473         }
474         if (!will_compress && pages) {
475                 /*
476                  * the compression code ran but failed to make things smaller,
477                  * free any pages it allocated and our page pointer array
478                  */
479                 for (i = 0; i < nr_pages_ret; i++) {
480                         WARN_ON(pages[i]->mapping);
481                         page_cache_release(pages[i]);
482                 }
483                 kfree(pages);
484                 pages = NULL;
485                 total_compressed = 0;
486                 nr_pages_ret = 0;
487
488                 /* flag the file so we don't compress in the future */
489                 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
490                     !(BTRFS_I(inode)->force_compress)) {
491                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
492                 }
493         }
494         if (will_compress) {
495                 *num_added += 1;
496
497                 /* the async work queues will take care of doing actual
498                  * allocation on disk for these compressed pages,
499                  * and will submit them to the elevator.
500                  */
501                 add_async_extent(async_cow, start, num_bytes,
502                                  total_compressed, pages, nr_pages_ret);
503
504                 if (start + num_bytes < end && start + num_bytes < actual_end) {
505                         start += num_bytes;
506                         pages = NULL;
507                         cond_resched();
508                         goto again;
509                 }
510         } else {
511 cleanup_and_bail_uncompressed:
512                 /*
513                  * No compression, but we still need to write the pages in
514                  * the file we've been given so far.  redirty the locked
515                  * page if it corresponds to our extent and set things up
516                  * for the async work queue to run cow_file_range to do
517                  * the normal delalloc dance
518                  */
519                 if (page_offset(locked_page) >= start &&
520                     page_offset(locked_page) <= end) {
521                         __set_page_dirty_nobuffers(locked_page);
522                         /* unlocked later on in the async handlers */
523                 }
524                 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0);
525                 *num_added += 1;
526         }
527
528 out:
529         return 0;
530
531 free_pages_out:
532         for (i = 0; i < nr_pages_ret; i++) {
533                 WARN_ON(pages[i]->mapping);
534                 page_cache_release(pages[i]);
535         }
536         kfree(pages);
537
538         goto out;
539 }
540
541 /*
542  * phase two of compressed writeback.  This is the ordered portion
543  * of the code, which only gets called in the order the work was
544  * queued.  We walk all the async extents created by compress_file_range
545  * and send them down to the disk.
546  */
547 static noinline int submit_compressed_extents(struct inode *inode,
548                                               struct async_cow *async_cow)
549 {
550         struct async_extent *async_extent;
551         u64 alloc_hint = 0;
552         struct btrfs_trans_handle *trans;
553         struct btrfs_key ins;
554         struct extent_map *em;
555         struct btrfs_root *root = BTRFS_I(inode)->root;
556         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
557         struct extent_io_tree *io_tree;
558         int ret = 0;
559
560         if (list_empty(&async_cow->extents))
561                 return 0;
562
563
564         while (!list_empty(&async_cow->extents)) {
565                 async_extent = list_entry(async_cow->extents.next,
566                                           struct async_extent, list);
567                 list_del(&async_extent->list);
568
569                 io_tree = &BTRFS_I(inode)->io_tree;
570
571 retry:
572                 /* did the compression code fall back to uncompressed IO? */
573                 if (!async_extent->pages) {
574                         int page_started = 0;
575                         unsigned long nr_written = 0;
576
577                         lock_extent(io_tree, async_extent->start,
578                                          async_extent->start +
579                                          async_extent->ram_size - 1, GFP_NOFS);
580
581                         /* allocate blocks */
582                         ret = cow_file_range(inode, async_cow->locked_page,
583                                              async_extent->start,
584                                              async_extent->start +
585                                              async_extent->ram_size - 1,
586                                              &page_started, &nr_written, 0);
587
588                         /*
589                          * if page_started, cow_file_range inserted an
590                          * inline extent and took care of all the unlocking
591                          * and IO for us.  Otherwise, we need to submit
592                          * all those pages down to the drive.
593                          */
594                         if (!page_started && !ret)
595                                 extent_write_locked_range(io_tree,
596                                                   inode, async_extent->start,
597                                                   async_extent->start +
598                                                   async_extent->ram_size - 1,
599                                                   btrfs_get_extent,
600                                                   WB_SYNC_ALL);
601                         kfree(async_extent);
602                         cond_resched();
603                         continue;
604                 }
605
606                 lock_extent(io_tree, async_extent->start,
607                             async_extent->start + async_extent->ram_size - 1,
608                             GFP_NOFS);
609
610                 trans = btrfs_join_transaction(root, 1);
611                 ret = btrfs_reserve_extent(trans, root,
612                                            async_extent->compressed_size,
613                                            async_extent->compressed_size,
614                                            0, alloc_hint,
615                                            (u64)-1, &ins, 1);
616                 btrfs_end_transaction(trans, root);
617
618                 if (ret) {
619                         int i;
620                         for (i = 0; i < async_extent->nr_pages; i++) {
621                                 WARN_ON(async_extent->pages[i]->mapping);
622                                 page_cache_release(async_extent->pages[i]);
623                         }
624                         kfree(async_extent->pages);
625                         async_extent->nr_pages = 0;
626                         async_extent->pages = NULL;
627                         unlock_extent(io_tree, async_extent->start,
628                                       async_extent->start +
629                                       async_extent->ram_size - 1, GFP_NOFS);
630                         goto retry;
631                 }
632
633                 /*
634                  * here we're doing allocation and writeback of the
635                  * compressed pages
636                  */
637                 btrfs_drop_extent_cache(inode, async_extent->start,
638                                         async_extent->start +
639                                         async_extent->ram_size - 1, 0);
640
641                 em = alloc_extent_map(GFP_NOFS);
642                 em->start = async_extent->start;
643                 em->len = async_extent->ram_size;
644                 em->orig_start = em->start;
645
646                 em->block_start = ins.objectid;
647                 em->block_len = ins.offset;
648                 em->bdev = root->fs_info->fs_devices->latest_bdev;
649                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
650                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
651
652                 while (1) {
653                         write_lock(&em_tree->lock);
654                         ret = add_extent_mapping(em_tree, em);
655                         write_unlock(&em_tree->lock);
656                         if (ret != -EEXIST) {
657                                 free_extent_map(em);
658                                 break;
659                         }
660                         btrfs_drop_extent_cache(inode, async_extent->start,
661                                                 async_extent->start +
662                                                 async_extent->ram_size - 1, 0);
663                 }
664
665                 ret = btrfs_add_ordered_extent(inode, async_extent->start,
666                                                ins.objectid,
667                                                async_extent->ram_size,
668                                                ins.offset,
669                                                BTRFS_ORDERED_COMPRESSED);
670                 BUG_ON(ret);
671
672                 /*
673                  * clear dirty, set writeback and unlock the pages.
674                  */
675                 extent_clear_unlock_delalloc(inode,
676                                 &BTRFS_I(inode)->io_tree,
677                                 async_extent->start,
678                                 async_extent->start +
679                                 async_extent->ram_size - 1,
680                                 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
681                                 EXTENT_CLEAR_UNLOCK |
682                                 EXTENT_CLEAR_DELALLOC |
683                                 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
684
685                 ret = btrfs_submit_compressed_write(inode,
686                                     async_extent->start,
687                                     async_extent->ram_size,
688                                     ins.objectid,
689                                     ins.offset, async_extent->pages,
690                                     async_extent->nr_pages);
691
692                 BUG_ON(ret);
693                 alloc_hint = ins.objectid + ins.offset;
694                 kfree(async_extent);
695                 cond_resched();
696         }
697
698         return 0;
699 }
700
701 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
702                                       u64 num_bytes)
703 {
704         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
705         struct extent_map *em;
706         u64 alloc_hint = 0;
707
708         read_lock(&em_tree->lock);
709         em = search_extent_mapping(em_tree, start, num_bytes);
710         if (em) {
711                 /*
712                  * if block start isn't an actual block number then find the
713                  * first block in this inode and use that as a hint.  If that
714                  * block is also bogus then just don't worry about it.
715                  */
716                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
717                         free_extent_map(em);
718                         em = search_extent_mapping(em_tree, 0, 0);
719                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
720                                 alloc_hint = em->block_start;
721                         if (em)
722                                 free_extent_map(em);
723                 } else {
724                         alloc_hint = em->block_start;
725                         free_extent_map(em);
726                 }
727         }
728         read_unlock(&em_tree->lock);
729
730         return alloc_hint;
731 }
732
733 /*
734  * when extent_io.c finds a delayed allocation range in the file,
735  * the call backs end up in this code.  The basic idea is to
736  * allocate extents on disk for the range, and create ordered data structs
737  * in ram to track those extents.
738  *
739  * locked_page is the page that writepage had locked already.  We use
740  * it to make sure we don't do extra locks or unlocks.
741  *
742  * *page_started is set to one if we unlock locked_page and do everything
743  * required to start IO on it.  It may be clean and already done with
744  * IO when we return.
745  */
746 static noinline int cow_file_range(struct inode *inode,
747                                    struct page *locked_page,
748                                    u64 start, u64 end, int *page_started,
749                                    unsigned long *nr_written,
750                                    int unlock)
751 {
752         struct btrfs_root *root = BTRFS_I(inode)->root;
753         struct btrfs_trans_handle *trans;
754         u64 alloc_hint = 0;
755         u64 num_bytes;
756         unsigned long ram_size;
757         u64 disk_num_bytes;
758         u64 cur_alloc_size;
759         u64 blocksize = root->sectorsize;
760         u64 actual_end;
761         u64 isize = i_size_read(inode);
762         struct btrfs_key ins;
763         struct extent_map *em;
764         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
765         int ret = 0;
766
767         trans = btrfs_join_transaction(root, 1);
768         BUG_ON(!trans);
769         btrfs_set_trans_block_group(trans, inode);
770         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
771
772         actual_end = min_t(u64, isize, end + 1);
773
774         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
775         num_bytes = max(blocksize,  num_bytes);
776         disk_num_bytes = num_bytes;
777         ret = 0;
778
779         if (start == 0) {
780                 /* lets try to make an inline extent */
781                 ret = cow_file_range_inline(trans, root, inode,
782                                             start, end, 0, NULL);
783                 if (ret == 0) {
784                         extent_clear_unlock_delalloc(inode,
785                                      &BTRFS_I(inode)->io_tree,
786                                      start, end, NULL,
787                                      EXTENT_CLEAR_UNLOCK_PAGE |
788                                      EXTENT_CLEAR_UNLOCK |
789                                      EXTENT_CLEAR_DELALLOC |
790                                      EXTENT_CLEAR_DIRTY |
791                                      EXTENT_SET_WRITEBACK |
792                                      EXTENT_END_WRITEBACK);
793
794                         *nr_written = *nr_written +
795                              (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
796                         *page_started = 1;
797                         ret = 0;
798                         goto out;
799                 }
800         }
801
802         BUG_ON(disk_num_bytes >
803                btrfs_super_total_bytes(&root->fs_info->super_copy));
804
805         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
806         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
807
808         while (disk_num_bytes > 0) {
809                 unsigned long op;
810
811                 cur_alloc_size = disk_num_bytes;
812                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
813                                            root->sectorsize, 0, alloc_hint,
814                                            (u64)-1, &ins, 1);
815                 BUG_ON(ret);
816
817                 em = alloc_extent_map(GFP_NOFS);
818                 em->start = start;
819                 em->orig_start = em->start;
820                 ram_size = ins.offset;
821                 em->len = ins.offset;
822
823                 em->block_start = ins.objectid;
824                 em->block_len = ins.offset;
825                 em->bdev = root->fs_info->fs_devices->latest_bdev;
826                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
827
828                 while (1) {
829                         write_lock(&em_tree->lock);
830                         ret = add_extent_mapping(em_tree, em);
831                         write_unlock(&em_tree->lock);
832                         if (ret != -EEXIST) {
833                                 free_extent_map(em);
834                                 break;
835                         }
836                         btrfs_drop_extent_cache(inode, start,
837                                                 start + ram_size - 1, 0);
838                 }
839
840                 cur_alloc_size = ins.offset;
841                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
842                                                ram_size, cur_alloc_size, 0);
843                 BUG_ON(ret);
844
845                 if (root->root_key.objectid ==
846                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
847                         ret = btrfs_reloc_clone_csums(inode, start,
848                                                       cur_alloc_size);
849                         BUG_ON(ret);
850                 }
851
852                 if (disk_num_bytes < cur_alloc_size)
853                         break;
854
855                 /* we're not doing compressed IO, don't unlock the first
856                  * page (which the caller expects to stay locked), don't
857                  * clear any dirty bits and don't set any writeback bits
858                  *
859                  * Do set the Private2 bit so we know this page was properly
860                  * setup for writepage
861                  */
862                 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
863                 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
864                         EXTENT_SET_PRIVATE2;
865
866                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
867                                              start, start + ram_size - 1,
868                                              locked_page, op);
869                 disk_num_bytes -= cur_alloc_size;
870                 num_bytes -= cur_alloc_size;
871                 alloc_hint = ins.objectid + ins.offset;
872                 start += cur_alloc_size;
873         }
874 out:
875         ret = 0;
876         btrfs_end_transaction(trans, root);
877
878         return ret;
879 }
880
881 /*
882  * work queue call back to started compression on a file and pages
883  */
884 static noinline void async_cow_start(struct btrfs_work *work)
885 {
886         struct async_cow *async_cow;
887         int num_added = 0;
888         async_cow = container_of(work, struct async_cow, work);
889
890         compress_file_range(async_cow->inode, async_cow->locked_page,
891                             async_cow->start, async_cow->end, async_cow,
892                             &num_added);
893         if (num_added == 0)
894                 async_cow->inode = NULL;
895 }
896
897 /*
898  * work queue call back to submit previously compressed pages
899  */
900 static noinline void async_cow_submit(struct btrfs_work *work)
901 {
902         struct async_cow *async_cow;
903         struct btrfs_root *root;
904         unsigned long nr_pages;
905
906         async_cow = container_of(work, struct async_cow, work);
907
908         root = async_cow->root;
909         nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
910                 PAGE_CACHE_SHIFT;
911
912         atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
913
914         if (atomic_read(&root->fs_info->async_delalloc_pages) <
915             5 * 1042 * 1024 &&
916             waitqueue_active(&root->fs_info->async_submit_wait))
917                 wake_up(&root->fs_info->async_submit_wait);
918
919         if (async_cow->inode)
920                 submit_compressed_extents(async_cow->inode, async_cow);
921 }
922
923 static noinline void async_cow_free(struct btrfs_work *work)
924 {
925         struct async_cow *async_cow;
926         async_cow = container_of(work, struct async_cow, work);
927         kfree(async_cow);
928 }
929
930 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
931                                 u64 start, u64 end, int *page_started,
932                                 unsigned long *nr_written)
933 {
934         struct async_cow *async_cow;
935         struct btrfs_root *root = BTRFS_I(inode)->root;
936         unsigned long nr_pages;
937         u64 cur_end;
938         int limit = 10 * 1024 * 1042;
939
940         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
941                          1, 0, NULL, GFP_NOFS);
942         while (start < end) {
943                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
944                 async_cow->inode = inode;
945                 async_cow->root = root;
946                 async_cow->locked_page = locked_page;
947                 async_cow->start = start;
948
949                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
950                         cur_end = end;
951                 else
952                         cur_end = min(end, start + 512 * 1024 - 1);
953
954                 async_cow->end = cur_end;
955                 INIT_LIST_HEAD(&async_cow->extents);
956
957                 async_cow->work.func = async_cow_start;
958                 async_cow->work.ordered_func = async_cow_submit;
959                 async_cow->work.ordered_free = async_cow_free;
960                 async_cow->work.flags = 0;
961
962                 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
963                         PAGE_CACHE_SHIFT;
964                 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
965
966                 btrfs_queue_worker(&root->fs_info->delalloc_workers,
967                                    &async_cow->work);
968
969                 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
970                         wait_event(root->fs_info->async_submit_wait,
971                            (atomic_read(&root->fs_info->async_delalloc_pages) <
972                             limit));
973                 }
974
975                 while (atomic_read(&root->fs_info->async_submit_draining) &&
976                       atomic_read(&root->fs_info->async_delalloc_pages)) {
977                         wait_event(root->fs_info->async_submit_wait,
978                           (atomic_read(&root->fs_info->async_delalloc_pages) ==
979                            0));
980                 }
981
982                 *nr_written += nr_pages;
983                 start = cur_end + 1;
984         }
985         *page_started = 1;
986         return 0;
987 }
988
989 static noinline int csum_exist_in_range(struct btrfs_root *root,
990                                         u64 bytenr, u64 num_bytes)
991 {
992         int ret;
993         struct btrfs_ordered_sum *sums;
994         LIST_HEAD(list);
995
996         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
997                                        bytenr + num_bytes - 1, &list);
998         if (ret == 0 && list_empty(&list))
999                 return 0;
1000
1001         while (!list_empty(&list)) {
1002                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1003                 list_del(&sums->list);
1004                 kfree(sums);
1005         }
1006         return 1;
1007 }
1008
1009 /*
1010  * when nowcow writeback call back.  This checks for snapshots or COW copies
1011  * of the extents that exist in the file, and COWs the file as required.
1012  *
1013  * If no cow copies or snapshots exist, we write directly to the existing
1014  * blocks on disk
1015  */
1016 static noinline int run_delalloc_nocow(struct inode *inode,
1017                                        struct page *locked_page,
1018                               u64 start, u64 end, int *page_started, int force,
1019                               unsigned long *nr_written)
1020 {
1021         struct btrfs_root *root = BTRFS_I(inode)->root;
1022         struct btrfs_trans_handle *trans;
1023         struct extent_buffer *leaf;
1024         struct btrfs_path *path;
1025         struct btrfs_file_extent_item *fi;
1026         struct btrfs_key found_key;
1027         u64 cow_start;
1028         u64 cur_offset;
1029         u64 extent_end;
1030         u64 extent_offset;
1031         u64 disk_bytenr;
1032         u64 num_bytes;
1033         int extent_type;
1034         int ret;
1035         int type;
1036         int nocow;
1037         int check_prev = 1;
1038
1039         path = btrfs_alloc_path();
1040         BUG_ON(!path);
1041         trans = btrfs_join_transaction(root, 1);
1042         BUG_ON(!trans);
1043
1044         cow_start = (u64)-1;
1045         cur_offset = start;
1046         while (1) {
1047                 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
1048                                                cur_offset, 0);
1049                 BUG_ON(ret < 0);
1050                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1051                         leaf = path->nodes[0];
1052                         btrfs_item_key_to_cpu(leaf, &found_key,
1053                                               path->slots[0] - 1);
1054                         if (found_key.objectid == inode->i_ino &&
1055                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1056                                 path->slots[0]--;
1057                 }
1058                 check_prev = 0;
1059 next_slot:
1060                 leaf = path->nodes[0];
1061                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1062                         ret = btrfs_next_leaf(root, path);
1063                         if (ret < 0)
1064                                 BUG_ON(1);
1065                         if (ret > 0)
1066                                 break;
1067                         leaf = path->nodes[0];
1068                 }
1069
1070                 nocow = 0;
1071                 disk_bytenr = 0;
1072                 num_bytes = 0;
1073                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1074
1075                 if (found_key.objectid > inode->i_ino ||
1076                     found_key.type > BTRFS_EXTENT_DATA_KEY ||
1077                     found_key.offset > end)
1078                         break;
1079
1080                 if (found_key.offset > cur_offset) {
1081                         extent_end = found_key.offset;
1082                         extent_type = 0;
1083                         goto out_check;
1084                 }
1085
1086                 fi = btrfs_item_ptr(leaf, path->slots[0],
1087                                     struct btrfs_file_extent_item);
1088                 extent_type = btrfs_file_extent_type(leaf, fi);
1089
1090                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1091                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1092                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1093                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1094                         extent_end = found_key.offset +
1095                                 btrfs_file_extent_num_bytes(leaf, fi);
1096                         if (extent_end <= start) {
1097                                 path->slots[0]++;
1098                                 goto next_slot;
1099                         }
1100                         if (disk_bytenr == 0)
1101                                 goto out_check;
1102                         if (btrfs_file_extent_compression(leaf, fi) ||
1103                             btrfs_file_extent_encryption(leaf, fi) ||
1104                             btrfs_file_extent_other_encoding(leaf, fi))
1105                                 goto out_check;
1106                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1107                                 goto out_check;
1108                         if (btrfs_extent_readonly(root, disk_bytenr))
1109                                 goto out_check;
1110                         if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
1111                                                   found_key.offset -
1112                                                   extent_offset, disk_bytenr))
1113                                 goto out_check;
1114                         disk_bytenr += extent_offset;
1115                         disk_bytenr += cur_offset - found_key.offset;
1116                         num_bytes = min(end + 1, extent_end) - cur_offset;
1117                         /*
1118                          * force cow if csum exists in the range.
1119                          * this ensure that csum for a given extent are
1120                          * either valid or do not exist.
1121                          */
1122                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1123                                 goto out_check;
1124                         nocow = 1;
1125                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1126                         extent_end = found_key.offset +
1127                                 btrfs_file_extent_inline_len(leaf, fi);
1128                         extent_end = ALIGN(extent_end, root->sectorsize);
1129                 } else {
1130                         BUG_ON(1);
1131                 }
1132 out_check:
1133                 if (extent_end <= start) {
1134                         path->slots[0]++;
1135                         goto next_slot;
1136                 }
1137                 if (!nocow) {
1138                         if (cow_start == (u64)-1)
1139                                 cow_start = cur_offset;
1140                         cur_offset = extent_end;
1141                         if (cur_offset > end)
1142                                 break;
1143                         path->slots[0]++;
1144                         goto next_slot;
1145                 }
1146
1147                 btrfs_release_path(root, path);
1148                 if (cow_start != (u64)-1) {
1149                         ret = cow_file_range(inode, locked_page, cow_start,
1150                                         found_key.offset - 1, page_started,
1151                                         nr_written, 1);
1152                         BUG_ON(ret);
1153                         cow_start = (u64)-1;
1154                 }
1155
1156                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1157                         struct extent_map *em;
1158                         struct extent_map_tree *em_tree;
1159                         em_tree = &BTRFS_I(inode)->extent_tree;
1160                         em = alloc_extent_map(GFP_NOFS);
1161                         em->start = cur_offset;
1162                         em->orig_start = em->start;
1163                         em->len = num_bytes;
1164                         em->block_len = num_bytes;
1165                         em->block_start = disk_bytenr;
1166                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1167                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1168                         while (1) {
1169                                 write_lock(&em_tree->lock);
1170                                 ret = add_extent_mapping(em_tree, em);
1171                                 write_unlock(&em_tree->lock);
1172                                 if (ret != -EEXIST) {
1173                                         free_extent_map(em);
1174                                         break;
1175                                 }
1176                                 btrfs_drop_extent_cache(inode, em->start,
1177                                                 em->start + em->len - 1, 0);
1178                         }
1179                         type = BTRFS_ORDERED_PREALLOC;
1180                 } else {
1181                         type = BTRFS_ORDERED_NOCOW;
1182                 }
1183
1184                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1185                                                num_bytes, num_bytes, type);
1186                 BUG_ON(ret);
1187
1188                 if (root->root_key.objectid ==
1189                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1190                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1191                                                       num_bytes);
1192                         BUG_ON(ret);
1193                 }
1194
1195                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1196                                 cur_offset, cur_offset + num_bytes - 1,
1197                                 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1198                                 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1199                                 EXTENT_SET_PRIVATE2);
1200                 cur_offset = extent_end;
1201                 if (cur_offset > end)
1202                         break;
1203         }
1204         btrfs_release_path(root, path);
1205
1206         if (cur_offset <= end && cow_start == (u64)-1)
1207                 cow_start = cur_offset;
1208         if (cow_start != (u64)-1) {
1209                 ret = cow_file_range(inode, locked_page, cow_start, end,
1210                                      page_started, nr_written, 1);
1211                 BUG_ON(ret);
1212         }
1213
1214         ret = btrfs_end_transaction(trans, root);
1215         BUG_ON(ret);
1216         btrfs_free_path(path);
1217         return 0;
1218 }
1219
1220 /*
1221  * extent_io.c call back to do delayed allocation processing
1222  */
1223 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1224                               u64 start, u64 end, int *page_started,
1225                               unsigned long *nr_written)
1226 {
1227         int ret;
1228         struct btrfs_root *root = BTRFS_I(inode)->root;
1229
1230         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1231                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1232                                          page_started, 1, nr_written);
1233         else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1234                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1235                                          page_started, 0, nr_written);
1236         else if (!btrfs_test_opt(root, COMPRESS) &&
1237                  !(BTRFS_I(inode)->force_compress))
1238                 ret = cow_file_range(inode, locked_page, start, end,
1239                                       page_started, nr_written, 1);
1240         else
1241                 ret = cow_file_range_async(inode, locked_page, start, end,
1242                                            page_started, nr_written);
1243         return ret;
1244 }
1245
1246 static int btrfs_split_extent_hook(struct inode *inode,
1247                                    struct extent_state *orig, u64 split)
1248 {
1249         /* not delalloc, ignore it */
1250         if (!(orig->state & EXTENT_DELALLOC))
1251                 return 0;
1252
1253         atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1254         return 0;
1255 }
1256
1257 /*
1258  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1259  * extents so we can keep track of new extents that are just merged onto old
1260  * extents, such as when we are doing sequential writes, so we can properly
1261  * account for the metadata space we'll need.
1262  */
1263 static int btrfs_merge_extent_hook(struct inode *inode,
1264                                    struct extent_state *new,
1265                                    struct extent_state *other)
1266 {
1267         /* not delalloc, ignore it */
1268         if (!(other->state & EXTENT_DELALLOC))
1269                 return 0;
1270
1271         atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1272         return 0;
1273 }
1274
1275 /*
1276  * extent_io.c set_bit_hook, used to track delayed allocation
1277  * bytes in this file, and to maintain the list of inodes that
1278  * have pending delalloc work to be done.
1279  */
1280 static int btrfs_set_bit_hook(struct inode *inode,
1281                               struct extent_state *state, int *bits)
1282 {
1283
1284         /*
1285          * set_bit and clear bit hooks normally require _irqsave/restore
1286          * but in this case, we are only testeing for the DELALLOC
1287          * bit, which is only set or cleared with irqs on
1288          */
1289         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1290                 struct btrfs_root *root = BTRFS_I(inode)->root;
1291                 u64 len = state->end + 1 - state->start;
1292
1293                 if (*bits & EXTENT_FIRST_DELALLOC)
1294                         *bits &= ~EXTENT_FIRST_DELALLOC;
1295                 else
1296                         atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1297
1298                 spin_lock(&root->fs_info->delalloc_lock);
1299                 BTRFS_I(inode)->delalloc_bytes += len;
1300                 root->fs_info->delalloc_bytes += len;
1301                 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1302                         list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1303                                       &root->fs_info->delalloc_inodes);
1304                 }
1305                 spin_unlock(&root->fs_info->delalloc_lock);
1306         }
1307         return 0;
1308 }
1309
1310 /*
1311  * extent_io.c clear_bit_hook, see set_bit_hook for why
1312  */
1313 static int btrfs_clear_bit_hook(struct inode *inode,
1314                                 struct extent_state *state, int *bits)
1315 {
1316         /*
1317          * set_bit and clear bit hooks normally require _irqsave/restore
1318          * but in this case, we are only testeing for the DELALLOC
1319          * bit, which is only set or cleared with irqs on
1320          */
1321         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1322                 struct btrfs_root *root = BTRFS_I(inode)->root;
1323                 u64 len = state->end + 1 - state->start;
1324
1325                 if (*bits & EXTENT_FIRST_DELALLOC)
1326                         *bits &= ~EXTENT_FIRST_DELALLOC;
1327                 else if (!(*bits & EXTENT_DO_ACCOUNTING))
1328                         atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1329
1330                 if (*bits & EXTENT_DO_ACCOUNTING)
1331                         btrfs_delalloc_release_metadata(inode, len);
1332
1333                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID)
1334                         btrfs_free_reserved_data_space(inode, len);
1335
1336                 spin_lock(&root->fs_info->delalloc_lock);
1337                 root->fs_info->delalloc_bytes -= len;
1338                 BTRFS_I(inode)->delalloc_bytes -= len;
1339
1340                 if (BTRFS_I(inode)->delalloc_bytes == 0 &&
1341                     !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1342                         list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1343                 }
1344                 spin_unlock(&root->fs_info->delalloc_lock);
1345         }
1346         return 0;
1347 }
1348
1349 /*
1350  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1351  * we don't create bios that span stripes or chunks
1352  */
1353 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1354                          size_t size, struct bio *bio,
1355                          unsigned long bio_flags)
1356 {
1357         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1358         struct btrfs_mapping_tree *map_tree;
1359         u64 logical = (u64)bio->bi_sector << 9;
1360         u64 length = 0;
1361         u64 map_length;
1362         int ret;
1363
1364         if (bio_flags & EXTENT_BIO_COMPRESSED)
1365                 return 0;
1366
1367         length = bio->bi_size;
1368         map_tree = &root->fs_info->mapping_tree;
1369         map_length = length;
1370         ret = btrfs_map_block(map_tree, READ, logical,
1371                               &map_length, NULL, 0);
1372
1373         if (map_length < length + size)
1374                 return 1;
1375         return 0;
1376 }
1377
1378 /*
1379  * in order to insert checksums into the metadata in large chunks,
1380  * we wait until bio submission time.   All the pages in the bio are
1381  * checksummed and sums are attached onto the ordered extent record.
1382  *
1383  * At IO completion time the cums attached on the ordered extent record
1384  * are inserted into the btree
1385  */
1386 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1387                                     struct bio *bio, int mirror_num,
1388                                     unsigned long bio_flags,
1389                                     u64 bio_offset)
1390 {
1391         struct btrfs_root *root = BTRFS_I(inode)->root;
1392         int ret = 0;
1393
1394         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1395         BUG_ON(ret);
1396         return 0;
1397 }
1398
1399 /*
1400  * in order to insert checksums into the metadata in large chunks,
1401  * we wait until bio submission time.   All the pages in the bio are
1402  * checksummed and sums are attached onto the ordered extent record.
1403  *
1404  * At IO completion time the cums attached on the ordered extent record
1405  * are inserted into the btree
1406  */
1407 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1408                           int mirror_num, unsigned long bio_flags,
1409                           u64 bio_offset)
1410 {
1411         struct btrfs_root *root = BTRFS_I(inode)->root;
1412         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1413 }
1414
1415 /*
1416  * extent_io.c submission hook. This does the right thing for csum calculation
1417  * on write, or reading the csums from the tree before a read
1418  */
1419 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1420                           int mirror_num, unsigned long bio_flags,
1421                           u64 bio_offset)
1422 {
1423         struct btrfs_root *root = BTRFS_I(inode)->root;
1424         int ret = 0;
1425         int skip_sum;
1426
1427         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1428
1429         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1430         BUG_ON(ret);
1431
1432         if (!(rw & REQ_WRITE)) {
1433                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1434                         return btrfs_submit_compressed_read(inode, bio,
1435                                                     mirror_num, bio_flags);
1436                 } else if (!skip_sum)
1437                         btrfs_lookup_bio_sums(root, inode, bio, NULL);
1438                 goto mapit;
1439         } else if (!skip_sum) {
1440                 /* csum items have already been cloned */
1441                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1442                         goto mapit;
1443                 /* we're doing a write, do the async checksumming */
1444                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1445                                    inode, rw, bio, mirror_num,
1446                                    bio_flags, bio_offset,
1447                                    __btrfs_submit_bio_start,
1448                                    __btrfs_submit_bio_done);
1449         }
1450
1451 mapit:
1452         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1453 }
1454
1455 /*
1456  * given a list of ordered sums record them in the inode.  This happens
1457  * at IO completion time based on sums calculated at bio submission time.
1458  */
1459 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1460                              struct inode *inode, u64 file_offset,
1461                              struct list_head *list)
1462 {
1463         struct btrfs_ordered_sum *sum;
1464
1465         btrfs_set_trans_block_group(trans, inode);
1466
1467         list_for_each_entry(sum, list, list) {
1468                 btrfs_csum_file_blocks(trans,
1469                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1470         }
1471         return 0;
1472 }
1473
1474 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1475                               struct extent_state **cached_state)
1476 {
1477         if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1478                 WARN_ON(1);
1479         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1480                                    cached_state, GFP_NOFS);
1481 }
1482
1483 /* see btrfs_writepage_start_hook for details on why this is required */
1484 struct btrfs_writepage_fixup {
1485         struct page *page;
1486         struct btrfs_work work;
1487 };
1488
1489 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1490 {
1491         struct btrfs_writepage_fixup *fixup;
1492         struct btrfs_ordered_extent *ordered;
1493         struct extent_state *cached_state = NULL;
1494         struct page *page;
1495         struct inode *inode;
1496         u64 page_start;
1497         u64 page_end;
1498
1499         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1500         page = fixup->page;
1501 again:
1502         lock_page(page);
1503         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1504                 ClearPageChecked(page);
1505                 goto out_page;
1506         }
1507
1508         inode = page->mapping->host;
1509         page_start = page_offset(page);
1510         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1511
1512         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1513                          &cached_state, GFP_NOFS);
1514
1515         /* already ordered? We're done */
1516         if (PagePrivate2(page))
1517                 goto out;
1518
1519         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1520         if (ordered) {
1521                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1522                                      page_end, &cached_state, GFP_NOFS);
1523                 unlock_page(page);
1524                 btrfs_start_ordered_extent(inode, ordered, 1);
1525                 goto again;
1526         }
1527
1528         BUG();
1529         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1530         ClearPageChecked(page);
1531 out:
1532         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1533                              &cached_state, GFP_NOFS);
1534 out_page:
1535         unlock_page(page);
1536         page_cache_release(page);
1537 }
1538
1539 /*
1540  * There are a few paths in the higher layers of the kernel that directly
1541  * set the page dirty bit without asking the filesystem if it is a
1542  * good idea.  This causes problems because we want to make sure COW
1543  * properly happens and the data=ordered rules are followed.
1544  *
1545  * In our case any range that doesn't have the ORDERED bit set
1546  * hasn't been properly setup for IO.  We kick off an async process
1547  * to fix it up.  The async helper will wait for ordered extents, set
1548  * the delalloc bit and make it safe to write the page.
1549  */
1550 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1551 {
1552         struct inode *inode = page->mapping->host;
1553         struct btrfs_writepage_fixup *fixup;
1554         struct btrfs_root *root = BTRFS_I(inode)->root;
1555
1556         /* this page is properly in the ordered list */
1557         if (TestClearPagePrivate2(page))
1558                 return 0;
1559
1560         if (PageChecked(page))
1561                 return -EAGAIN;
1562
1563         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1564         if (!fixup)
1565                 return -EAGAIN;
1566
1567         SetPageChecked(page);
1568         page_cache_get(page);
1569         fixup->work.func = btrfs_writepage_fixup_worker;
1570         fixup->page = page;
1571         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1572         return -EAGAIN;
1573 }
1574
1575 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1576                                        struct inode *inode, u64 file_pos,
1577                                        u64 disk_bytenr, u64 disk_num_bytes,
1578                                        u64 num_bytes, u64 ram_bytes,
1579                                        u8 compression, u8 encryption,
1580                                        u16 other_encoding, int extent_type)
1581 {
1582         struct btrfs_root *root = BTRFS_I(inode)->root;
1583         struct btrfs_file_extent_item *fi;
1584         struct btrfs_path *path;
1585         struct extent_buffer *leaf;
1586         struct btrfs_key ins;
1587         u64 hint;
1588         int ret;
1589
1590         path = btrfs_alloc_path();
1591         BUG_ON(!path);
1592
1593         path->leave_spinning = 1;
1594
1595         /*
1596          * we may be replacing one extent in the tree with another.
1597          * The new extent is pinned in the extent map, and we don't want
1598          * to drop it from the cache until it is completely in the btree.
1599          *
1600          * So, tell btrfs_drop_extents to leave this extent in the cache.
1601          * the caller is expected to unpin it and allow it to be merged
1602          * with the others.
1603          */
1604         ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1605                                  &hint, 0);
1606         BUG_ON(ret);
1607
1608         ins.objectid = inode->i_ino;
1609         ins.offset = file_pos;
1610         ins.type = BTRFS_EXTENT_DATA_KEY;
1611         ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1612         BUG_ON(ret);
1613         leaf = path->nodes[0];
1614         fi = btrfs_item_ptr(leaf, path->slots[0],
1615                             struct btrfs_file_extent_item);
1616         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1617         btrfs_set_file_extent_type(leaf, fi, extent_type);
1618         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1619         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1620         btrfs_set_file_extent_offset(leaf, fi, 0);
1621         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1622         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1623         btrfs_set_file_extent_compression(leaf, fi, compression);
1624         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1625         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1626
1627         btrfs_unlock_up_safe(path, 1);
1628         btrfs_set_lock_blocking(leaf);
1629
1630         btrfs_mark_buffer_dirty(leaf);
1631
1632         inode_add_bytes(inode, num_bytes);
1633
1634         ins.objectid = disk_bytenr;
1635         ins.offset = disk_num_bytes;
1636         ins.type = BTRFS_EXTENT_ITEM_KEY;
1637         ret = btrfs_alloc_reserved_file_extent(trans, root,
1638                                         root->root_key.objectid,
1639                                         inode->i_ino, file_pos, &ins);
1640         BUG_ON(ret);
1641         btrfs_free_path(path);
1642
1643         return 0;
1644 }
1645
1646 /*
1647  * helper function for btrfs_finish_ordered_io, this
1648  * just reads in some of the csum leaves to prime them into ram
1649  * before we start the transaction.  It limits the amount of btree
1650  * reads required while inside the transaction.
1651  */
1652 /* as ordered data IO finishes, this gets called so we can finish
1653  * an ordered extent if the range of bytes in the file it covers are
1654  * fully written.
1655  */
1656 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1657 {
1658         struct btrfs_root *root = BTRFS_I(inode)->root;
1659         struct btrfs_trans_handle *trans = NULL;
1660         struct btrfs_ordered_extent *ordered_extent = NULL;
1661         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1662         struct extent_state *cached_state = NULL;
1663         int compressed = 0;
1664         int ret;
1665
1666         ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1667                                              end - start + 1);
1668         if (!ret)
1669                 return 0;
1670         BUG_ON(!ordered_extent);
1671
1672         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1673                 BUG_ON(!list_empty(&ordered_extent->list));
1674                 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1675                 if (!ret) {
1676                         trans = btrfs_join_transaction(root, 1);
1677                         btrfs_set_trans_block_group(trans, inode);
1678                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1679                         ret = btrfs_update_inode(trans, root, inode);
1680                         BUG_ON(ret);
1681                 }
1682                 goto out;
1683         }
1684
1685         lock_extent_bits(io_tree, ordered_extent->file_offset,
1686                          ordered_extent->file_offset + ordered_extent->len - 1,
1687                          0, &cached_state, GFP_NOFS);
1688
1689         trans = btrfs_join_transaction(root, 1);
1690         btrfs_set_trans_block_group(trans, inode);
1691         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1692
1693         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1694                 compressed = 1;
1695         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1696                 BUG_ON(compressed);
1697                 ret = btrfs_mark_extent_written(trans, inode,
1698                                                 ordered_extent->file_offset,
1699                                                 ordered_extent->file_offset +
1700                                                 ordered_extent->len);
1701                 BUG_ON(ret);
1702         } else {
1703                 BUG_ON(root == root->fs_info->tree_root);
1704                 ret = insert_reserved_file_extent(trans, inode,
1705                                                 ordered_extent->file_offset,
1706                                                 ordered_extent->start,
1707                                                 ordered_extent->disk_len,
1708                                                 ordered_extent->len,
1709                                                 ordered_extent->len,
1710                                                 compressed, 0, 0,
1711                                                 BTRFS_FILE_EXTENT_REG);
1712                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1713                                    ordered_extent->file_offset,
1714                                    ordered_extent->len);
1715                 BUG_ON(ret);
1716         }
1717         unlock_extent_cached(io_tree, ordered_extent->file_offset,
1718                              ordered_extent->file_offset +
1719                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
1720
1721         add_pending_csums(trans, inode, ordered_extent->file_offset,
1722                           &ordered_extent->list);
1723
1724         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1725         ret = btrfs_update_inode(trans, root, inode);
1726         BUG_ON(ret);
1727 out:
1728         btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1729         if (trans)
1730                 btrfs_end_transaction(trans, root);
1731         /* once for us */
1732         btrfs_put_ordered_extent(ordered_extent);
1733         /* once for the tree */
1734         btrfs_put_ordered_extent(ordered_extent);
1735
1736         return 0;
1737 }
1738
1739 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1740                                 struct extent_state *state, int uptodate)
1741 {
1742         ClearPagePrivate2(page);
1743         return btrfs_finish_ordered_io(page->mapping->host, start, end);
1744 }
1745
1746 /*
1747  * When IO fails, either with EIO or csum verification fails, we
1748  * try other mirrors that might have a good copy of the data.  This
1749  * io_failure_record is used to record state as we go through all the
1750  * mirrors.  If another mirror has good data, the page is set up to date
1751  * and things continue.  If a good mirror can't be found, the original
1752  * bio end_io callback is called to indicate things have failed.
1753  */
1754 struct io_failure_record {
1755         struct page *page;
1756         u64 start;
1757         u64 len;
1758         u64 logical;
1759         unsigned long bio_flags;
1760         int last_mirror;
1761 };
1762
1763 static int btrfs_io_failed_hook(struct bio *failed_bio,
1764                          struct page *page, u64 start, u64 end,
1765                          struct extent_state *state)
1766 {
1767         struct io_failure_record *failrec = NULL;
1768         u64 private;
1769         struct extent_map *em;
1770         struct inode *inode = page->mapping->host;
1771         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1772         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1773         struct bio *bio;
1774         int num_copies;
1775         int ret;
1776         int rw;
1777         u64 logical;
1778
1779         ret = get_state_private(failure_tree, start, &private);
1780         if (ret) {
1781                 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1782                 if (!failrec)
1783                         return -ENOMEM;
1784                 failrec->start = start;
1785                 failrec->len = end - start + 1;
1786                 failrec->last_mirror = 0;
1787                 failrec->bio_flags = 0;
1788
1789                 read_lock(&em_tree->lock);
1790                 em = lookup_extent_mapping(em_tree, start, failrec->len);
1791                 if (em->start > start || em->start + em->len < start) {
1792                         free_extent_map(em);
1793                         em = NULL;
1794                 }
1795                 read_unlock(&em_tree->lock);
1796
1797                 if (!em || IS_ERR(em)) {
1798                         kfree(failrec);
1799                         return -EIO;
1800                 }
1801                 logical = start - em->start;
1802                 logical = em->block_start + logical;
1803                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1804                         logical = em->block_start;
1805                         failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1806                 }
1807                 failrec->logical = logical;
1808                 free_extent_map(em);
1809                 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1810                                 EXTENT_DIRTY, GFP_NOFS);
1811                 set_state_private(failure_tree, start,
1812                                  (u64)(unsigned long)failrec);
1813         } else {
1814                 failrec = (struct io_failure_record *)(unsigned long)private;
1815         }
1816         num_copies = btrfs_num_copies(
1817                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
1818                               failrec->logical, failrec->len);
1819         failrec->last_mirror++;
1820         if (!state) {
1821                 spin_lock(&BTRFS_I(inode)->io_tree.lock);
1822                 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1823                                                     failrec->start,
1824                                                     EXTENT_LOCKED);
1825                 if (state && state->start != failrec->start)
1826                         state = NULL;
1827                 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1828         }
1829         if (!state || failrec->last_mirror > num_copies) {
1830                 set_state_private(failure_tree, failrec->start, 0);
1831                 clear_extent_bits(failure_tree, failrec->start,
1832                                   failrec->start + failrec->len - 1,
1833                                   EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1834                 kfree(failrec);
1835                 return -EIO;
1836         }
1837         bio = bio_alloc(GFP_NOFS, 1);
1838         bio->bi_private = state;
1839         bio->bi_end_io = failed_bio->bi_end_io;
1840         bio->bi_sector = failrec->logical >> 9;
1841         bio->bi_bdev = failed_bio->bi_bdev;
1842         bio->bi_size = 0;
1843
1844         bio_add_page(bio, page, failrec->len, start - page_offset(page));
1845         if (failed_bio->bi_rw & REQ_WRITE)
1846                 rw = WRITE;
1847         else
1848                 rw = READ;
1849
1850         BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1851                                                       failrec->last_mirror,
1852                                                       failrec->bio_flags, 0);
1853         return 0;
1854 }
1855
1856 /*
1857  * each time an IO finishes, we do a fast check in the IO failure tree
1858  * to see if we need to process or clean up an io_failure_record
1859  */
1860 static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1861 {
1862         u64 private;
1863         u64 private_failure;
1864         struct io_failure_record *failure;
1865         int ret;
1866
1867         private = 0;
1868         if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1869                              (u64)-1, 1, EXTENT_DIRTY)) {
1870                 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1871                                         start, &private_failure);
1872                 if (ret == 0) {
1873                         failure = (struct io_failure_record *)(unsigned long)
1874                                    private_failure;
1875                         set_state_private(&BTRFS_I(inode)->io_failure_tree,
1876                                           failure->start, 0);
1877                         clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1878                                           failure->start,
1879                                           failure->start + failure->len - 1,
1880                                           EXTENT_DIRTY | EXTENT_LOCKED,
1881                                           GFP_NOFS);
1882                         kfree(failure);
1883                 }
1884         }
1885         return 0;
1886 }
1887
1888 /*
1889  * when reads are done, we need to check csums to verify the data is correct
1890  * if there's a match, we allow the bio to finish.  If not, we go through
1891  * the io_failure_record routines to find good copies
1892  */
1893 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1894                                struct extent_state *state)
1895 {
1896         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1897         struct inode *inode = page->mapping->host;
1898         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1899         char *kaddr;
1900         u64 private = ~(u32)0;
1901         int ret;
1902         struct btrfs_root *root = BTRFS_I(inode)->root;
1903         u32 csum = ~(u32)0;
1904
1905         if (PageChecked(page)) {
1906                 ClearPageChecked(page);
1907                 goto good;
1908         }
1909
1910         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1911                 return 0;
1912
1913         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1914             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1915                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1916                                   GFP_NOFS);
1917                 return 0;
1918         }
1919
1920         if (state && state->start == start) {
1921                 private = state->private;
1922                 ret = 0;
1923         } else {
1924                 ret = get_state_private(io_tree, start, &private);
1925         }
1926         kaddr = kmap_atomic(page, KM_USER0);
1927         if (ret)
1928                 goto zeroit;
1929
1930         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
1931         btrfs_csum_final(csum, (char *)&csum);
1932         if (csum != private)
1933                 goto zeroit;
1934
1935         kunmap_atomic(kaddr, KM_USER0);
1936 good:
1937         /* if the io failure tree for this inode is non-empty,
1938          * check to see if we've recovered from a failed IO
1939          */
1940         btrfs_clean_io_failures(inode, start);
1941         return 0;
1942
1943 zeroit:
1944         if (printk_ratelimit()) {
1945                 printk(KERN_INFO "btrfs csum failed ino %lu off %llu csum %u "
1946                        "private %llu\n", page->mapping->host->i_ino,
1947                        (unsigned long long)start, csum,
1948                        (unsigned long long)private);
1949         }
1950         memset(kaddr + offset, 1, end - start + 1);
1951         flush_dcache_page(page);
1952         kunmap_atomic(kaddr, KM_USER0);
1953         if (private == 0)
1954                 return 0;
1955         return -EIO;
1956 }
1957
1958 struct delayed_iput {
1959         struct list_head list;
1960         struct inode *inode;
1961 };
1962
1963 void btrfs_add_delayed_iput(struct inode *inode)
1964 {
1965         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1966         struct delayed_iput *delayed;
1967
1968         if (atomic_add_unless(&inode->i_count, -1, 1))
1969                 return;
1970
1971         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
1972         delayed->inode = inode;
1973
1974         spin_lock(&fs_info->delayed_iput_lock);
1975         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
1976         spin_unlock(&fs_info->delayed_iput_lock);
1977 }
1978
1979 void btrfs_run_delayed_iputs(struct btrfs_root *root)
1980 {
1981         LIST_HEAD(list);
1982         struct btrfs_fs_info *fs_info = root->fs_info;
1983         struct delayed_iput *delayed;
1984         int empty;
1985
1986         spin_lock(&fs_info->delayed_iput_lock);
1987         empty = list_empty(&fs_info->delayed_iputs);
1988         spin_unlock(&fs_info->delayed_iput_lock);
1989         if (empty)
1990                 return;
1991
1992         down_read(&root->fs_info->cleanup_work_sem);
1993         spin_lock(&fs_info->delayed_iput_lock);
1994         list_splice_init(&fs_info->delayed_iputs, &list);
1995         spin_unlock(&fs_info->delayed_iput_lock);
1996
1997         while (!list_empty(&list)) {
1998                 delayed = list_entry(list.next, struct delayed_iput, list);
1999                 list_del(&delayed->list);
2000                 iput(delayed->inode);
2001                 kfree(delayed);
2002         }
2003         up_read(&root->fs_info->cleanup_work_sem);
2004 }
2005
2006 /*
2007  * calculate extra metadata reservation when snapshotting a subvolume
2008  * contains orphan files.
2009  */
2010 void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2011                                 struct btrfs_pending_snapshot *pending,
2012                                 u64 *bytes_to_reserve)
2013 {
2014         struct btrfs_root *root;
2015         struct btrfs_block_rsv *block_rsv;
2016         u64 num_bytes;
2017         int index;
2018
2019         root = pending->root;
2020         if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2021                 return;
2022
2023         block_rsv = root->orphan_block_rsv;
2024
2025         /* orphan block reservation for the snapshot */
2026         num_bytes = block_rsv->size;
2027
2028         /*
2029          * after the snapshot is created, COWing tree blocks may use more
2030          * space than it frees. So we should make sure there is enough
2031          * reserved space.
2032          */
2033         index = trans->transid & 0x1;
2034         if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2035                 num_bytes += block_rsv->size -
2036                              (block_rsv->reserved + block_rsv->freed[index]);
2037         }
2038
2039         *bytes_to_reserve += num_bytes;
2040 }
2041
2042 void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2043                                 struct btrfs_pending_snapshot *pending)
2044 {
2045         struct btrfs_root *root = pending->root;
2046         struct btrfs_root *snap = pending->snap;
2047         struct btrfs_block_rsv *block_rsv;
2048         u64 num_bytes;
2049         int index;
2050         int ret;
2051
2052         if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2053                 return;
2054
2055         /* refill source subvolume's orphan block reservation */
2056         block_rsv = root->orphan_block_rsv;
2057         index = trans->transid & 0x1;
2058         if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2059                 num_bytes = block_rsv->size -
2060                             (block_rsv->reserved + block_rsv->freed[index]);
2061                 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2062                                               root->orphan_block_rsv,
2063                                               num_bytes);
2064                 BUG_ON(ret);
2065         }
2066
2067         /* setup orphan block reservation for the snapshot */
2068         block_rsv = btrfs_alloc_block_rsv(snap);
2069         BUG_ON(!block_rsv);
2070
2071         btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2072         snap->orphan_block_rsv = block_rsv;
2073
2074         num_bytes = root->orphan_block_rsv->size;
2075         ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2076                                       block_rsv, num_bytes);
2077         BUG_ON(ret);
2078
2079 #if 0
2080         /* insert orphan item for the snapshot */
2081         WARN_ON(!root->orphan_item_inserted);
2082         ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2083                                        snap->root_key.objectid);
2084         BUG_ON(ret);
2085         snap->orphan_item_inserted = 1;
2086 #endif
2087 }
2088
2089 enum btrfs_orphan_cleanup_state {
2090         ORPHAN_CLEANUP_STARTED  = 1,
2091         ORPHAN_CLEANUP_DONE     = 2,
2092 };
2093
2094 /*
2095  * This is called in transaction commmit time. If there are no orphan
2096  * files in the subvolume, it removes orphan item and frees block_rsv
2097  * structure.
2098  */
2099 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2100                               struct btrfs_root *root)
2101 {
2102         int ret;
2103
2104         if (!list_empty(&root->orphan_list) ||
2105             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2106                 return;
2107
2108         if (root->orphan_item_inserted &&
2109             btrfs_root_refs(&root->root_item) > 0) {
2110                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2111                                             root->root_key.objectid);
2112                 BUG_ON(ret);
2113                 root->orphan_item_inserted = 0;
2114         }
2115
2116         if (root->orphan_block_rsv) {
2117                 WARN_ON(root->orphan_block_rsv->size > 0);
2118                 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2119                 root->orphan_block_rsv = NULL;
2120         }
2121 }
2122
2123 /*
2124  * This creates an orphan entry for the given inode in case something goes
2125  * wrong in the middle of an unlink/truncate.
2126  *
2127  * NOTE: caller of this function should reserve 5 units of metadata for
2128  *       this function.
2129  */
2130 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2131 {
2132         struct btrfs_root *root = BTRFS_I(inode)->root;
2133         struct btrfs_block_rsv *block_rsv = NULL;
2134         int reserve = 0;
2135         int insert = 0;
2136         int ret;
2137
2138         if (!root->orphan_block_rsv) {
2139                 block_rsv = btrfs_alloc_block_rsv(root);
2140                 BUG_ON(!block_rsv);
2141         }
2142
2143         spin_lock(&root->orphan_lock);
2144         if (!root->orphan_block_rsv) {
2145                 root->orphan_block_rsv = block_rsv;
2146         } else if (block_rsv) {
2147                 btrfs_free_block_rsv(root, block_rsv);
2148                 block_rsv = NULL;
2149         }
2150
2151         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2152                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2153 #if 0
2154                 /*
2155                  * For proper ENOSPC handling, we should do orphan
2156                  * cleanup when mounting. But this introduces backward
2157                  * compatibility issue.
2158                  */
2159                 if (!xchg(&root->orphan_item_inserted, 1))
2160                         insert = 2;
2161                 else
2162                         insert = 1;
2163 #endif
2164                 insert = 1;
2165         } else {
2166                 WARN_ON(!BTRFS_I(inode)->orphan_meta_reserved);
2167         }
2168
2169         if (!BTRFS_I(inode)->orphan_meta_reserved) {
2170                 BTRFS_I(inode)->orphan_meta_reserved = 1;
2171                 reserve = 1;
2172         }
2173         spin_unlock(&root->orphan_lock);
2174
2175         if (block_rsv)
2176                 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2177
2178         /* grab metadata reservation from transaction handle */
2179         if (reserve) {
2180                 ret = btrfs_orphan_reserve_metadata(trans, inode);
2181                 BUG_ON(ret);
2182         }
2183
2184         /* insert an orphan item to track this unlinked/truncated file */
2185         if (insert >= 1) {
2186                 ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
2187                 BUG_ON(ret);
2188         }
2189
2190         /* insert an orphan item to track subvolume contains orphan files */
2191         if (insert >= 2) {
2192                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2193                                                root->root_key.objectid);
2194                 BUG_ON(ret);
2195         }
2196         return 0;
2197 }
2198
2199 /*
2200  * We have done the truncate/delete so we can go ahead and remove the orphan
2201  * item for this particular inode.
2202  */
2203 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2204 {
2205         struct btrfs_root *root = BTRFS_I(inode)->root;
2206         int delete_item = 0;
2207         int release_rsv = 0;
2208         int ret = 0;
2209
2210         spin_lock(&root->orphan_lock);
2211         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2212                 list_del_init(&BTRFS_I(inode)->i_orphan);
2213                 delete_item = 1;
2214         }
2215
2216         if (BTRFS_I(inode)->orphan_meta_reserved) {
2217                 BTRFS_I(inode)->orphan_meta_reserved = 0;
2218                 release_rsv = 1;
2219         }
2220         spin_unlock(&root->orphan_lock);
2221
2222         if (trans && delete_item) {
2223                 ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
2224                 BUG_ON(ret);
2225         }
2226
2227         if (release_rsv)
2228                 btrfs_orphan_release_metadata(inode);
2229
2230         return 0;
2231 }
2232
2233 /*
2234  * this cleans up any orphans that may be left on the list from the last use
2235  * of this root.
2236  */
2237 void btrfs_orphan_cleanup(struct btrfs_root *root)
2238 {
2239         struct btrfs_path *path;
2240         struct extent_buffer *leaf;
2241         struct btrfs_item *item;
2242         struct btrfs_key key, found_key;
2243         struct btrfs_trans_handle *trans;
2244         struct inode *inode;
2245         int ret = 0, nr_unlink = 0, nr_truncate = 0;
2246
2247         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2248                 return;
2249
2250         path = btrfs_alloc_path();
2251         BUG_ON(!path);
2252         path->reada = -1;
2253
2254         key.objectid = BTRFS_ORPHAN_OBJECTID;
2255         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2256         key.offset = (u64)-1;
2257
2258         while (1) {
2259                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2260                 if (ret < 0) {
2261                         printk(KERN_ERR "Error searching slot for orphan: %d"
2262                                "\n", ret);
2263                         break;
2264                 }
2265
2266                 /*
2267                  * if ret == 0 means we found what we were searching for, which
2268                  * is weird, but possible, so only screw with path if we didnt
2269                  * find the key and see if we have stuff that matches
2270                  */
2271                 if (ret > 0) {
2272                         if (path->slots[0] == 0)
2273                                 break;
2274                         path->slots[0]--;
2275                 }
2276
2277                 /* pull out the item */
2278                 leaf = path->nodes[0];
2279                 item = btrfs_item_nr(leaf, path->slots[0]);
2280                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2281
2282                 /* make sure the item matches what we want */
2283                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2284                         break;
2285                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2286                         break;
2287
2288                 /* release the path since we're done with it */
2289                 btrfs_release_path(root, path);
2290
2291                 /*
2292                  * this is where we are basically btrfs_lookup, without the
2293                  * crossing root thing.  we store the inode number in the
2294                  * offset of the orphan item.
2295                  */
2296                 found_key.objectid = found_key.offset;
2297                 found_key.type = BTRFS_INODE_ITEM_KEY;
2298                 found_key.offset = 0;
2299                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2300                 BUG_ON(IS_ERR(inode));
2301
2302                 /*
2303                  * add this inode to the orphan list so btrfs_orphan_del does
2304                  * the proper thing when we hit it
2305                  */
2306                 spin_lock(&root->orphan_lock);
2307                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2308                 spin_unlock(&root->orphan_lock);
2309
2310                 /*
2311                  * if this is a bad inode, means we actually succeeded in
2312                  * removing the inode, but not the orphan record, which means
2313                  * we need to manually delete the orphan since iput will just
2314                  * do a destroy_inode
2315                  */
2316                 if (is_bad_inode(inode)) {
2317                         trans = btrfs_start_transaction(root, 0);
2318                         btrfs_orphan_del(trans, inode);
2319                         btrfs_end_transaction(trans, root);
2320                         iput(inode);
2321                         continue;
2322                 }
2323
2324                 /* if we have links, this was a truncate, lets do that */
2325                 if (inode->i_nlink) {
2326                         nr_truncate++;
2327                         btrfs_truncate(inode);
2328                 } else {
2329                         nr_unlink++;
2330                 }
2331
2332                 /* this will do delete_inode and everything for us */
2333                 iput(inode);
2334         }
2335         btrfs_free_path(path);
2336
2337         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2338
2339         if (root->orphan_block_rsv)
2340                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2341                                         (u64)-1);
2342
2343         if (root->orphan_block_rsv || root->orphan_item_inserted) {
2344                 trans = btrfs_join_transaction(root, 1);
2345                 btrfs_end_transaction(trans, root);
2346         }
2347
2348         if (nr_unlink)
2349                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2350         if (nr_truncate)
2351                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2352 }
2353
2354 /*
2355  * very simple check to peek ahead in the leaf looking for xattrs.  If we
2356  * don't find any xattrs, we know there can't be any acls.
2357  *
2358  * slot is the slot the inode is in, objectid is the objectid of the inode
2359  */
2360 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2361                                           int slot, u64 objectid)
2362 {
2363         u32 nritems = btrfs_header_nritems(leaf);
2364         struct btrfs_key found_key;
2365         int scanned = 0;
2366
2367         slot++;
2368         while (slot < nritems) {
2369                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2370
2371                 /* we found a different objectid, there must not be acls */
2372                 if (found_key.objectid != objectid)
2373                         return 0;
2374
2375                 /* we found an xattr, assume we've got an acl */
2376                 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2377                         return 1;
2378
2379                 /*
2380                  * we found a key greater than an xattr key, there can't
2381                  * be any acls later on
2382                  */
2383                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2384                         return 0;
2385
2386                 slot++;
2387                 scanned++;
2388
2389                 /*
2390                  * it goes inode, inode backrefs, xattrs, extents,
2391                  * so if there are a ton of hard links to an inode there can
2392                  * be a lot of backrefs.  Don't waste time searching too hard,
2393                  * this is just an optimization
2394                  */
2395                 if (scanned >= 8)
2396                         break;
2397         }
2398         /* we hit the end of the leaf before we found an xattr or
2399          * something larger than an xattr.  We have to assume the inode
2400          * has acls
2401          */
2402         return 1;
2403 }
2404
2405 /*
2406  * read an inode from the btree into the in-memory inode
2407  */
2408 static void btrfs_read_locked_inode(struct inode *inode)
2409 {
2410         struct btrfs_path *path;
2411         struct extent_buffer *leaf;
2412         struct btrfs_inode_item *inode_item;
2413         struct btrfs_timespec *tspec;
2414         struct btrfs_root *root = BTRFS_I(inode)->root;
2415         struct btrfs_key location;
2416         int maybe_acls;
2417         u64 alloc_group_block;
2418         u32 rdev;
2419         int ret;
2420
2421         path = btrfs_alloc_path();
2422         BUG_ON(!path);
2423         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2424
2425         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2426         if (ret)
2427                 goto make_bad;
2428
2429         leaf = path->nodes[0];
2430         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2431                                     struct btrfs_inode_item);
2432
2433         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2434         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2435         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2436         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2437         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2438
2439         tspec = btrfs_inode_atime(inode_item);
2440         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2441         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2442
2443         tspec = btrfs_inode_mtime(inode_item);
2444         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2445         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2446
2447         tspec = btrfs_inode_ctime(inode_item);
2448         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2449         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2450
2451         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2452         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2453         BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2454         inode->i_generation = BTRFS_I(inode)->generation;
2455         inode->i_rdev = 0;
2456         rdev = btrfs_inode_rdev(leaf, inode_item);
2457
2458         BTRFS_I(inode)->index_cnt = (u64)-1;
2459         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2460
2461         alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
2462
2463         /*
2464          * try to precache a NULL acl entry for files that don't have
2465          * any xattrs or acls
2466          */
2467         maybe_acls = acls_after_inode_item(leaf, path->slots[0], inode->i_ino);
2468         if (!maybe_acls)
2469                 cache_no_acl(inode);
2470
2471         BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2472                                                 alloc_group_block, 0);
2473         btrfs_free_path(path);
2474         inode_item = NULL;
2475
2476         switch (inode->i_mode & S_IFMT) {
2477         case S_IFREG:
2478                 inode->i_mapping->a_ops = &btrfs_aops;
2479                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2480                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2481                 inode->i_fop = &btrfs_file_operations;
2482                 inode->i_op = &btrfs_file_inode_operations;
2483                 break;
2484         case S_IFDIR:
2485                 inode->i_fop = &btrfs_dir_file_operations;
2486                 if (root == root->fs_info->tree_root)
2487                         inode->i_op = &btrfs_dir_ro_inode_operations;
2488                 else
2489                         inode->i_op = &btrfs_dir_inode_operations;
2490                 break;
2491         case S_IFLNK:
2492                 inode->i_op = &btrfs_symlink_inode_operations;
2493                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2494                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2495                 break;
2496         default:
2497                 inode->i_op = &btrfs_special_inode_operations;
2498                 init_special_inode(inode, inode->i_mode, rdev);
2499                 break;
2500         }
2501
2502         btrfs_update_iflags(inode);
2503         return;
2504
2505 make_bad:
2506         btrfs_free_path(path);
2507         make_bad_inode(inode);
2508 }
2509
2510 /*
2511  * given a leaf and an inode, copy the inode fields into the leaf
2512  */
2513 static void fill_inode_item(struct btrfs_trans_handle *trans,
2514                             struct extent_buffer *leaf,
2515                             struct btrfs_inode_item *item,
2516                             struct inode *inode)
2517 {
2518         btrfs_set_inode_uid(leaf, item, inode->i_uid);
2519         btrfs_set_inode_gid(leaf, item, inode->i_gid);
2520         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2521         btrfs_set_inode_mode(leaf, item, inode->i_mode);
2522         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2523
2524         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2525                                inode->i_atime.tv_sec);
2526         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2527                                 inode->i_atime.tv_nsec);
2528
2529         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2530                                inode->i_mtime.tv_sec);
2531         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2532                                 inode->i_mtime.tv_nsec);
2533
2534         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2535                                inode->i_ctime.tv_sec);
2536         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2537                                 inode->i_ctime.tv_nsec);
2538
2539         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2540         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2541         btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2542         btrfs_set_inode_transid(leaf, item, trans->transid);
2543         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2544         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2545         btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
2546 }
2547
2548 /*
2549  * copy everything in the in-memory inode into the btree.
2550  */
2551 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2552                                 struct btrfs_root *root, struct inode *inode)
2553 {
2554         struct btrfs_inode_item *inode_item;
2555         struct btrfs_path *path;
2556         struct extent_buffer *leaf;
2557         int ret;
2558
2559         path = btrfs_alloc_path();
2560         BUG_ON(!path);
2561         path->leave_spinning = 1;
2562         ret = btrfs_lookup_inode(trans, root, path,
2563                                  &BTRFS_I(inode)->location, 1);
2564         if (ret) {
2565                 if (ret > 0)
2566                         ret = -ENOENT;
2567                 goto failed;
2568         }
2569
2570         btrfs_unlock_up_safe(path, 1);
2571         leaf = path->nodes[0];
2572         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2573                                   struct btrfs_inode_item);
2574
2575         fill_inode_item(trans, leaf, inode_item, inode);
2576         btrfs_mark_buffer_dirty(leaf);
2577         btrfs_set_inode_last_trans(trans, inode);
2578         ret = 0;
2579 failed:
2580         btrfs_free_path(path);
2581         return ret;
2582 }
2583
2584
2585 /*
2586  * unlink helper that gets used here in inode.c and in the tree logging
2587  * recovery code.  It remove a link in a directory with a given name, and
2588  * also drops the back refs in the inode to the directory
2589  */
2590 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2591                        struct btrfs_root *root,
2592                        struct inode *dir, struct inode *inode,
2593                        const char *name, int name_len)
2594 {
2595         struct btrfs_path *path;
2596         int ret = 0;
2597         struct extent_buffer *leaf;
2598         struct btrfs_dir_item *di;
2599         struct btrfs_key key;
2600         u64 index;
2601
2602         path = btrfs_alloc_path();
2603         if (!path) {
2604                 ret = -ENOMEM;
2605                 goto err;
2606         }
2607
2608         path->leave_spinning = 1;
2609         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2610                                     name, name_len, -1);
2611         if (IS_ERR(di)) {
2612                 ret = PTR_ERR(di);
2613                 goto err;
2614         }
2615         if (!di) {
2616                 ret = -ENOENT;
2617                 goto err;
2618         }
2619         leaf = path->nodes[0];
2620         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2621         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2622         if (ret)
2623                 goto err;
2624         btrfs_release_path(root, path);
2625
2626         ret = btrfs_del_inode_ref(trans, root, name, name_len,
2627                                   inode->i_ino,
2628                                   dir->i_ino, &index);
2629         if (ret) {
2630                 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2631                        "inode %lu parent %lu\n", name_len, name,
2632                        inode->i_ino, dir->i_ino);
2633                 goto err;
2634         }
2635
2636         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2637                                          index, name, name_len, -1);
2638         if (IS_ERR(di)) {
2639                 ret = PTR_ERR(di);
2640                 goto err;
2641         }
2642         if (!di) {
2643                 ret = -ENOENT;
2644                 goto err;
2645         }
2646         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2647         btrfs_release_path(root, path);
2648
2649         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2650                                          inode, dir->i_ino);
2651         BUG_ON(ret != 0 && ret != -ENOENT);
2652
2653         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2654                                            dir, index);
2655         BUG_ON(ret);
2656 err:
2657         btrfs_free_path(path);
2658         if (ret)
2659                 goto out;
2660
2661         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2662         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2663         btrfs_update_inode(trans, root, dir);
2664         btrfs_drop_nlink(inode);
2665         ret = btrfs_update_inode(trans, root, inode);
2666 out:
2667         return ret;
2668 }
2669
2670 /* helper to check if there is any shared block in the path */
2671 static int check_path_shared(struct btrfs_root *root,
2672                              struct btrfs_path *path)
2673 {
2674         struct extent_buffer *eb;
2675         int level;
2676         int ret;
2677         u64 refs = 1;
2678
2679         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2680                 if (!path->nodes[level])
2681                         break;
2682                 eb = path->nodes[level];
2683                 if (!btrfs_block_can_be_shared(root, eb))
2684                         continue;
2685                 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2686                                                &refs, NULL);
2687                 if (refs > 1)
2688                         return 1;
2689         }
2690         return 0;
2691 }
2692
2693 /*
2694  * helper to start transaction for unlink and rmdir.
2695  *
2696  * unlink and rmdir are special in btrfs, they do not always free space.
2697  * so in enospc case, we should make sure they will free space before
2698  * allowing them to use the global metadata reservation.
2699  */
2700 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2701                                                        struct dentry *dentry)
2702 {
2703         struct btrfs_trans_handle *trans;
2704         struct btrfs_root *root = BTRFS_I(dir)->root;
2705         struct btrfs_path *path;
2706         struct btrfs_inode_ref *ref;
2707         struct btrfs_dir_item *di;
2708         struct inode *inode = dentry->d_inode;
2709         u64 index;
2710         int check_link = 1;
2711         int err = -ENOSPC;
2712         int ret;
2713
2714         trans = btrfs_start_transaction(root, 10);
2715         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2716                 return trans;
2717
2718         if (inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2719                 return ERR_PTR(-ENOSPC);
2720
2721         /* check if there is someone else holds reference */
2722         if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2723                 return ERR_PTR(-ENOSPC);
2724
2725         if (atomic_read(&inode->i_count) > 2)
2726                 return ERR_PTR(-ENOSPC);
2727
2728         if (xchg(&root->fs_info->enospc_unlink, 1))
2729                 return ERR_PTR(-ENOSPC);
2730
2731         path = btrfs_alloc_path();
2732         if (!path) {
2733                 root->fs_info->enospc_unlink = 0;
2734                 return ERR_PTR(-ENOMEM);
2735         }
2736
2737         trans = btrfs_start_transaction(root, 0);
2738         if (IS_ERR(trans)) {
2739                 btrfs_free_path(path);
2740                 root->fs_info->enospc_unlink = 0;
2741                 return trans;
2742         }
2743
2744         path->skip_locking = 1;
2745         path->search_commit_root = 1;
2746
2747         ret = btrfs_lookup_inode(trans, root, path,
2748                                 &BTRFS_I(dir)->location, 0);
2749         if (ret < 0) {
2750                 err = ret;
2751                 goto out;
2752         }
2753         if (ret == 0) {
2754                 if (check_path_shared(root, path))
2755                         goto out;
2756         } else {
2757                 check_link = 0;
2758         }
2759         btrfs_release_path(root, path);
2760
2761         ret = btrfs_lookup_inode(trans, root, path,
2762                                 &BTRFS_I(inode)->location, 0);
2763         if (ret < 0) {
2764                 err = ret;
2765                 goto out;
2766         }
2767         if (ret == 0) {
2768                 if (check_path_shared(root, path))
2769                         goto out;
2770         } else {
2771                 check_link = 0;
2772         }
2773         btrfs_release_path(root, path);
2774
2775         if (ret == 0 && S_ISREG(inode->i_mode)) {
2776                 ret = btrfs_lookup_file_extent(trans, root, path,
2777                                                inode->i_ino, (u64)-1, 0);
2778                 if (ret < 0) {
2779                         err = ret;
2780                         goto out;
2781                 }
2782                 BUG_ON(ret == 0);
2783                 if (check_path_shared(root, path))
2784                         goto out;
2785                 btrfs_release_path(root, path);
2786         }
2787
2788         if (!check_link) {
2789                 err = 0;
2790                 goto out;
2791         }
2792
2793         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2794                                 dentry->d_name.name, dentry->d_name.len, 0);
2795         if (IS_ERR(di)) {
2796                 err = PTR_ERR(di);
2797                 goto out;
2798         }
2799         if (di) {
2800                 if (check_path_shared(root, path))
2801                         goto out;
2802         } else {
2803                 err = 0;
2804                 goto out;
2805         }
2806         btrfs_release_path(root, path);
2807
2808         ref = btrfs_lookup_inode_ref(trans, root, path,
2809                                 dentry->d_name.name, dentry->d_name.len,
2810                                 inode->i_ino, dir->i_ino, 0);
2811         if (IS_ERR(ref)) {
2812                 err = PTR_ERR(ref);
2813                 goto out;
2814         }
2815         BUG_ON(!ref);
2816         if (check_path_shared(root, path))
2817                 goto out;
2818         index = btrfs_inode_ref_index(path->nodes[0], ref);
2819         btrfs_release_path(root, path);
2820
2821         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino, index,
2822                                 dentry->d_name.name, dentry->d_name.len, 0);
2823         if (IS_ERR(di)) {
2824                 err = PTR_ERR(di);
2825                 goto out;
2826         }
2827         BUG_ON(ret == -ENOENT);
2828         if (check_path_shared(root, path))
2829                 goto out;
2830
2831         err = 0;
2832 out:
2833         btrfs_free_path(path);
2834         if (err) {
2835                 btrfs_end_transaction(trans, root);
2836                 root->fs_info->enospc_unlink = 0;
2837                 return ERR_PTR(err);
2838         }
2839
2840         trans->block_rsv = &root->fs_info->global_block_rsv;
2841         return trans;
2842 }
2843
2844 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2845                                struct btrfs_root *root)
2846 {
2847         if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2848                 BUG_ON(!root->fs_info->enospc_unlink);
2849                 root->fs_info->enospc_unlink = 0;
2850         }
2851         btrfs_end_transaction_throttle(trans, root);
2852 }
2853
2854 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2855 {
2856         struct btrfs_root *root = BTRFS_I(dir)->root;
2857         struct btrfs_trans_handle *trans;
2858         struct inode *inode = dentry->d_inode;
2859         int ret;
2860         unsigned long nr = 0;
2861
2862         trans = __unlink_start_trans(dir, dentry);
2863         if (IS_ERR(trans))
2864                 return PTR_ERR(trans);
2865
2866         btrfs_set_trans_block_group(trans, dir);
2867
2868         btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2869
2870         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2871                                  dentry->d_name.name, dentry->d_name.len);
2872         BUG_ON(ret);
2873
2874         if (inode->i_nlink == 0) {
2875                 ret = btrfs_orphan_add(trans, inode);
2876                 BUG_ON(ret);
2877         }
2878
2879         nr = trans->blocks_used;
2880         __unlink_end_trans(trans, root);
2881         btrfs_btree_balance_dirty(root, nr);
2882         return ret;
2883 }
2884
2885 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2886                         struct btrfs_root *root,
2887                         struct inode *dir, u64 objectid,
2888                         const char *name, int name_len)
2889 {
2890         struct btrfs_path *path;
2891         struct extent_buffer *leaf;
2892         struct btrfs_dir_item *di;
2893         struct btrfs_key key;
2894         u64 index;
2895         int ret;
2896
2897         path = btrfs_alloc_path();
2898         if (!path)
2899                 return -ENOMEM;
2900
2901         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2902                                    name, name_len, -1);
2903         BUG_ON(!di || IS_ERR(di));
2904
2905         leaf = path->nodes[0];
2906         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2907         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2908         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2909         BUG_ON(ret);
2910         btrfs_release_path(root, path);
2911
2912         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2913                                  objectid, root->root_key.objectid,
2914                                  dir->i_ino, &index, name, name_len);
2915         if (ret < 0) {
2916                 BUG_ON(ret != -ENOENT);
2917                 di = btrfs_search_dir_index_item(root, path, dir->i_ino,
2918                                                  name, name_len);
2919                 BUG_ON(!di || IS_ERR(di));
2920
2921                 leaf = path->nodes[0];
2922                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2923                 btrfs_release_path(root, path);
2924                 index = key.offset;
2925         }
2926
2927         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2928                                          index, name, name_len, -1);
2929         BUG_ON(!di || IS_ERR(di));
2930
2931         leaf = path->nodes[0];
2932         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2933         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2934         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2935         BUG_ON(ret);
2936         btrfs_release_path(root, path);
2937
2938         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2939         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2940         ret = btrfs_update_inode(trans, root, dir);
2941         BUG_ON(ret);
2942
2943         btrfs_free_path(path);
2944         return 0;
2945 }
2946
2947 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2948 {
2949         struct inode *inode = dentry->d_inode;
2950         int err = 0;
2951         struct btrfs_root *root = BTRFS_I(dir)->root;
2952         struct btrfs_trans_handle *trans;
2953         unsigned long nr = 0;
2954
2955         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
2956             inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
2957                 return -ENOTEMPTY;
2958
2959         trans = __unlink_start_trans(dir, dentry);
2960         if (IS_ERR(trans))
2961                 return PTR_ERR(trans);
2962
2963         btrfs_set_trans_block_group(trans, dir);
2964
2965         if (unlikely(inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
2966                 err = btrfs_unlink_subvol(trans, root, dir,
2967                                           BTRFS_I(inode)->location.objectid,
2968                                           dentry->d_name.name,
2969                                           dentry->d_name.len);
2970                 goto out;
2971         }
2972
2973         err = btrfs_orphan_add(trans, inode);
2974         if (err)
2975                 goto out;
2976
2977         /* now the directory is empty */
2978         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2979                                  dentry->d_name.name, dentry->d_name.len);
2980         if (!err)
2981                 btrfs_i_size_write(inode, 0);
2982 out:
2983         nr = trans->blocks_used;
2984         __unlink_end_trans(trans, root);
2985         btrfs_btree_balance_dirty(root, nr);
2986
2987         return err;
2988 }
2989
2990 #if 0
2991 /*
2992  * when truncating bytes in a file, it is possible to avoid reading
2993  * the leaves that contain only checksum items.  This can be the
2994  * majority of the IO required to delete a large file, but it must
2995  * be done carefully.
2996  *
2997  * The keys in the level just above the leaves are checked to make sure
2998  * the lowest key in a given leaf is a csum key, and starts at an offset
2999  * after the new  size.
3000  *
3001  * Then the key for the next leaf is checked to make sure it also has
3002  * a checksum item for the same file.  If it does, we know our target leaf
3003  * contains only checksum items, and it can be safely freed without reading
3004  * it.
3005  *
3006  * This is just an optimization targeted at large files.  It may do
3007  * nothing.  It will return 0 unless things went badly.
3008  */
3009 static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
3010                                      struct btrfs_root *root,
3011                                      struct btrfs_path *path,
3012                                      struct inode *inode, u64 new_size)
3013 {
3014         struct btrfs_key key;
3015         int ret;
3016         int nritems;
3017         struct btrfs_key found_key;
3018         struct btrfs_key other_key;
3019         struct btrfs_leaf_ref *ref;
3020         u64 leaf_gen;
3021         u64 leaf_start;
3022
3023         path->lowest_level = 1;
3024         key.objectid = inode->i_ino;
3025         key.type = BTRFS_CSUM_ITEM_KEY;
3026         key.offset = new_size;
3027 again:
3028         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3029         if (ret < 0)
3030                 goto out;
3031
3032         if (path->nodes[1] == NULL) {
3033                 ret = 0;
3034                 goto out;
3035         }
3036         ret = 0;
3037         btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
3038         nritems = btrfs_header_nritems(path->nodes[1]);
3039
3040         if (!nritems)
3041                 goto out;
3042
3043         if (path->slots[1] >= nritems)
3044                 goto next_node;
3045
3046         /* did we find a key greater than anything we want to delete? */
3047         if (found_key.objectid > inode->i_ino ||
3048            (found_key.objectid == inode->i_ino && found_key.type > key.type))
3049                 goto out;
3050
3051         /* we check the next key in the node to make sure the leave contains
3052          * only checksum items.  This comparison doesn't work if our
3053          * leaf is the last one in the node
3054          */
3055         if (path->slots[1] + 1 >= nritems) {
3056 next_node:
3057                 /* search forward from the last key in the node, this
3058                  * will bring us into the next node in the tree
3059                  */
3060                 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
3061
3062                 /* unlikely, but we inc below, so check to be safe */
3063                 if (found_key.offset == (u64)-1)
3064                         goto out;
3065
3066                 /* search_forward needs a path with locks held, do the
3067                  * search again for the original key.  It is possible
3068                  * this will race with a balance and return a path that
3069                  * we could modify, but this drop is just an optimization
3070                  * and is allowed to miss some leaves.
3071                  */
3072                 btrfs_release_path(root, path);
3073                 found_key.offset++;
3074
3075                 /* setup a max key for search_forward */
3076                 other_key.offset = (u64)-1;
3077                 other_key.type = key.type;
3078                 other_key.objectid = key.objectid;
3079
3080                 path->keep_locks = 1;
3081                 ret = btrfs_search_forward(root, &found_key, &other_key,
3082                                            path, 0, 0);
3083                 path->keep_locks = 0;
3084                 if (ret || found_key.objectid != key.objectid ||
3085                     found_key.type != key.type) {
3086                         ret = 0;
3087                         goto out;
3088                 }
3089
3090                 key.offset = found_key.offset;
3091                 btrfs_release_path(root, path);
3092                 cond_resched();
3093                 goto again;
3094         }
3095
3096         /* we know there's one more slot after us in the tree,
3097          * read that key so we can verify it is also a checksum item
3098          */
3099         btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
3100
3101         if (found_key.objectid < inode->i_ino)
3102                 goto next_key;
3103
3104         if (found_key.type != key.type || found_key.offset < new_size)
3105                 goto next_key;
3106
3107         /*
3108          * if the key for the next leaf isn't a csum key from this objectid,
3109          * we can't be sure there aren't good items inside this leaf.
3110          * Bail out
3111          */
3112         if (other_key.objectid != inode->i_ino || other_key.type != key.type)
3113                 goto out;
3114
3115         leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
3116         leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
3117         /*
3118          * it is safe to delete this leaf, it contains only
3119          * csum items from this inode at an offset >= new_size
3120          */
3121         ret = btrfs_del_leaf(trans, root, path, leaf_start);
3122         BUG_ON(ret);
3123
3124         if (root->ref_cows && leaf_gen < trans->transid) {
3125                 ref = btrfs_alloc_leaf_ref(root, 0);
3126                 if (ref) {
3127                         ref->root_gen = root->root_key.offset;
3128                         ref->bytenr = leaf_start;
3129                         ref->owner = 0;
3130                         ref->generation = leaf_gen;
3131                         ref->nritems = 0;
3132
3133                         btrfs_sort_leaf_ref(ref);
3134
3135                         ret = btrfs_add_leaf_ref(root, ref, 0);
3136                         WARN_ON(ret);
3137                         btrfs_free_leaf_ref(root, ref);
3138                 } else {
3139                         WARN_ON(1);
3140                 }
3141         }
3142 next_key:
3143         btrfs_release_path(root, path);
3144
3145         if (other_key.objectid == inode->i_ino &&
3146             other_key.type == key.type && other_key.offset > key.offset) {
3147                 key.offset = other_key.offset;
3148                 cond_resched();
3149                 goto again;
3150         }
3151         ret = 0;
3152 out:
3153         /* fixup any changes we've made to the path */
3154         path->lowest_level = 0;
3155         path->keep_locks = 0;
3156         btrfs_release_path(root, path);
3157         return ret;
3158 }
3159
3160 #endif
3161
3162 /*
3163  * this can truncate away extent items, csum items and directory items.
3164  * It starts at a high offset and removes keys until it can't find
3165  * any higher than new_size
3166  *
3167  * csum items that cross the new i_size are truncated to the new size
3168  * as well.
3169  *
3170  * min_type is the minimum key type to truncate down to.  If set to 0, this
3171  * will kill all the items on this inode, including the INODE_ITEM_KEY.
3172  */
3173 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3174                                struct btrfs_root *root,
3175                                struct inode *inode,
3176                                u64 new_size, u32 min_type)
3177 {
3178         struct btrfs_path *path;
3179         struct extent_buffer *leaf;
3180         struct btrfs_file_extent_item *fi;
3181         struct btrfs_key key;
3182         struct btrfs_key found_key;
3183         u64 extent_start = 0;
3184         u64 extent_num_bytes = 0;
3185         u64 extent_offset = 0;
3186         u64 item_end = 0;
3187         u64 mask = root->sectorsize - 1;
3188         u32 found_type = (u8)-1;
3189         int found_extent;
3190         int del_item;
3191         int pending_del_nr = 0;
3192         int pending_del_slot = 0;
3193         int extent_type = -1;
3194         int encoding;
3195         int ret;
3196         int err = 0;
3197
3198         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3199
3200         if (root->ref_cows || root == root->fs_info->tree_root)
3201                 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3202
3203         path = btrfs_alloc_path();
3204         BUG_ON(!path);
3205         path->reada = -1;
3206
3207         key.objectid = inode->i_ino;
3208         key.offset = (u64)-1;
3209         key.type = (u8)-1;
3210
3211 search_again:
3212         path->leave_spinning = 1;
3213         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3214         if (ret < 0) {
3215                 err = ret;
3216                 goto out;
3217         }
3218
3219         if (ret > 0) {
3220                 /* there are no items in the tree for us to truncate, we're
3221                  * done
3222                  */
3223                 if (path->slots[0] == 0)
3224                         goto out;
3225                 path->slots[0]--;
3226         }
3227
3228         while (1) {
3229                 fi = NULL;
3230                 leaf = path->nodes[0];
3231                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3232                 found_type = btrfs_key_type(&found_key);
3233                 encoding = 0;
3234
3235                 if (found_key.objectid != inode->i_ino)
3236                         break;
3237
3238                 if (found_type < min_type)
3239                         break;
3240
3241                 item_end = found_key.offset;
3242                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3243                         fi = btrfs_item_ptr(leaf, path->slots[0],
3244                                             struct btrfs_file_extent_item);
3245                         extent_type = btrfs_file_extent_type(leaf, fi);
3246                         encoding = btrfs_file_extent_compression(leaf, fi);
3247                         encoding |= btrfs_file_extent_encryption(leaf, fi);
3248                         encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3249
3250                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3251                                 item_end +=
3252                                     btrfs_file_extent_num_bytes(leaf, fi);
3253                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3254                                 item_end += btrfs_file_extent_inline_len(leaf,
3255                                                                          fi);
3256                         }
3257                         item_end--;
3258                 }
3259                 if (found_type > min_type) {
3260                         del_item = 1;
3261                 } else {
3262                         if (item_end < new_size)
3263                                 break;
3264                         if (found_key.offset >= new_size)
3265                                 del_item = 1;
3266                         else
3267                                 del_item = 0;
3268                 }
3269                 found_extent = 0;
3270                 /* FIXME, shrink the extent if the ref count is only 1 */
3271                 if (found_type != BTRFS_EXTENT_DATA_KEY)
3272                         goto delete;
3273
3274                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3275                         u64 num_dec;
3276                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3277                         if (!del_item && !encoding) {
3278                                 u64 orig_num_bytes =
3279                                         btrfs_file_extent_num_bytes(leaf, fi);
3280                                 extent_num_bytes = new_size -
3281                                         found_key.offset + root->sectorsize - 1;
3282                                 extent_num_bytes = extent_num_bytes &
3283                                         ~((u64)root->sectorsize - 1);
3284                                 btrfs_set_file_extent_num_bytes(leaf, fi,
3285                                                          extent_num_bytes);
3286                                 num_dec = (orig_num_bytes -
3287                                            extent_num_bytes);
3288                                 if (root->ref_cows && extent_start != 0)
3289                                         inode_sub_bytes(inode, num_dec);
3290                                 btrfs_mark_buffer_dirty(leaf);
3291                         } else {
3292                                 extent_num_bytes =
3293                                         btrfs_file_extent_disk_num_bytes(leaf,
3294                                                                          fi);
3295                                 extent_offset = found_key.offset -
3296                                         btrfs_file_extent_offset(leaf, fi);
3297
3298                                 /* FIXME blocksize != 4096 */
3299                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3300                                 if (extent_start != 0) {
3301                                         found_extent = 1;
3302                                         if (root->ref_cows)
3303                                                 inode_sub_bytes(inode, num_dec);
3304                                 }
3305                         }
3306                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3307                         /*
3308                          * we can't truncate inline items that have had
3309                          * special encodings
3310                          */
3311                         if (!del_item &&
3312                             btrfs_file_extent_compression(leaf, fi) == 0 &&
3313                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
3314                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3315                                 u32 size = new_size - found_key.offset;
3316
3317                                 if (root->ref_cows) {
3318                                         inode_sub_bytes(inode, item_end + 1 -
3319                                                         new_size);
3320                                 }
3321                                 size =
3322                                     btrfs_file_extent_calc_inline_size(size);
3323                                 ret = btrfs_truncate_item(trans, root, path,
3324                                                           size, 1);
3325                                 BUG_ON(ret);
3326                         } else if (root->ref_cows) {
3327                                 inode_sub_bytes(inode, item_end + 1 -
3328                                                 found_key.offset);
3329                         }
3330                 }
3331 delete:
3332                 if (del_item) {
3333                         if (!pending_del_nr) {
3334                                 /* no pending yet, add ourselves */
3335                                 pending_del_slot = path->slots[0];
3336                                 pending_del_nr = 1;
3337                         } else if (pending_del_nr &&
3338                                    path->slots[0] + 1 == pending_del_slot) {
3339                                 /* hop on the pending chunk */
3340                                 pending_del_nr++;
3341                                 pending_del_slot = path->slots[0];
3342                         } else {
3343                                 BUG();
3344                         }
3345                 } else {
3346                         break;
3347                 }
3348                 if (found_extent && (root->ref_cows ||
3349                                      root == root->fs_info->tree_root)) {
3350                         btrfs_set_path_blocking(path);
3351                         ret = btrfs_free_extent(trans, root, extent_start,
3352                                                 extent_num_bytes, 0,
3353                                                 btrfs_header_owner(leaf),
3354                                                 inode->i_ino, extent_offset);
3355                         BUG_ON(ret);
3356                 }
3357
3358                 if (found_type == BTRFS_INODE_ITEM_KEY)
3359                         break;
3360
3361                 if (path->slots[0] == 0 ||
3362                     path->slots[0] != pending_del_slot) {
3363                         if (root->ref_cows) {
3364                                 err = -EAGAIN;
3365                                 goto out;
3366                         }
3367                         if (pending_del_nr) {
3368                                 ret = btrfs_del_items(trans, root, path,
3369                                                 pending_del_slot,
3370                                                 pending_del_nr);
3371                                 BUG_ON(ret);
3372                                 pending_del_nr = 0;
3373                         }
3374                         btrfs_release_path(root, path);
3375                         goto search_again;
3376                 } else {
3377                         path->slots[0]--;
3378                 }
3379         }
3380 out:
3381         if (pending_del_nr) {
3382                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3383                                       pending_del_nr);
3384                 BUG_ON(ret);
3385         }
3386         btrfs_free_path(path);
3387         return err;
3388 }
3389
3390 /*
3391  * taken from block_truncate_page, but does cow as it zeros out
3392  * any bytes left in the last page in the file.
3393  */
3394 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3395 {
3396         struct inode *inode = mapping->host;
3397         struct btrfs_root *root = BTRFS_I(inode)->root;
3398         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3399         struct btrfs_ordered_extent *ordered;
3400         struct extent_state *cached_state = NULL;
3401         char *kaddr;
3402         u32 blocksize = root->sectorsize;
3403         pgoff_t index = from >> PAGE_CACHE_SHIFT;
3404         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3405         struct page *page;
3406         int ret = 0;
3407         u64 page_start;
3408         u64 page_end;
3409
3410         if ((offset & (blocksize - 1)) == 0)
3411                 goto out;
3412         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3413         if (ret)
3414                 goto out;
3415
3416         ret = -ENOMEM;
3417 again:
3418         page = grab_cache_page(mapping, index);
3419         if (!page) {
3420                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3421                 goto out;
3422         }
3423
3424         page_start = page_offset(page);
3425         page_end = page_start + PAGE_CACHE_SIZE - 1;
3426
3427         if (!PageUptodate(page)) {
3428                 ret = btrfs_readpage(NULL, page);
3429                 lock_page(page);
3430                 if (page->mapping != mapping) {
3431                         unlock_page(page);
3432                         page_cache_release(page);
3433                         goto again;
3434                 }
3435                 if (!PageUptodate(page)) {
3436                         ret = -EIO;
3437                         goto out_unlock;
3438                 }
3439         }
3440         wait_on_page_writeback(page);
3441
3442         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3443                          GFP_NOFS);
3444         set_page_extent_mapped(page);
3445
3446         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3447         if (ordered) {
3448                 unlock_extent_cached(io_tree, page_start, page_end,
3449                                      &cached_state, GFP_NOFS);
3450                 unlock_page(page);
3451                 page_cache_release(page);
3452                 btrfs_start_ordered_extent(inode, ordered, 1);
3453                 btrfs_put_ordered_extent(ordered);
3454                 goto again;
3455         }
3456
3457         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3458                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3459                           0, 0, &cached_state, GFP_NOFS);
3460
3461         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3462                                         &cached_state);
3463         if (ret) {
3464                 unlock_extent_cached(io_tree, page_start, page_end,
3465                                      &cached_state, GFP_NOFS);
3466                 goto out_unlock;
3467         }
3468
3469         ret = 0;
3470         if (offset != PAGE_CACHE_SIZE) {
3471                 kaddr = kmap(page);
3472                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3473                 flush_dcache_page(page);
3474                 kunmap(page);
3475         }
3476         ClearPageChecked(page);
3477         set_page_dirty(page);
3478         unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3479                              GFP_NOFS);
3480
3481 out_unlock:
3482         if (ret)
3483                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3484         unlock_page(page);
3485         page_cache_release(page);
3486 out:
3487         return ret;
3488 }
3489
3490 int btrfs_cont_expand(struct inode *inode, loff_t size)
3491 {
3492         struct btrfs_trans_handle *trans;
3493         struct btrfs_root *root = BTRFS_I(inode)->root;
3494         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3495         struct extent_map *em = NULL;
3496         struct extent_state *cached_state = NULL;
3497         u64 mask = root->sectorsize - 1;
3498         u64 hole_start = (inode->i_size + mask) & ~mask;
3499         u64 block_end = (size + mask) & ~mask;
3500         u64 last_byte;
3501         u64 cur_offset;
3502         u64 hole_size;
3503         int err = 0;
3504
3505         if (size <= hole_start)
3506                 return 0;
3507
3508         while (1) {
3509                 struct btrfs_ordered_extent *ordered;
3510                 btrfs_wait_ordered_range(inode, hole_start,
3511                                          block_end - hole_start);
3512                 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3513                                  &cached_state, GFP_NOFS);
3514                 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3515                 if (!ordered)
3516                         break;
3517                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3518                                      &cached_state, GFP_NOFS);
3519                 btrfs_put_ordered_extent(ordered);
3520         }
3521
3522         cur_offset = hole_start;
3523         while (1) {
3524                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3525                                 block_end - cur_offset, 0);
3526                 BUG_ON(IS_ERR(em) || !em);
3527                 last_byte = min(extent_map_end(em), block_end);
3528                 last_byte = (last_byte + mask) & ~mask;
3529                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3530                         u64 hint_byte = 0;
3531                         hole_size = last_byte - cur_offset;
3532
3533                         trans = btrfs_start_transaction(root, 2);
3534                         if (IS_ERR(trans)) {
3535                                 err = PTR_ERR(trans);
3536                                 break;
3537                         }
3538                         btrfs_set_trans_block_group(trans, inode);
3539
3540                         err = btrfs_drop_extents(trans, inode, cur_offset,
3541                                                  cur_offset + hole_size,
3542                                                  &hint_byte, 1);
3543                         BUG_ON(err);
3544
3545                         err = btrfs_insert_file_extent(trans, root,
3546                                         inode->i_ino, cur_offset, 0,
3547                                         0, hole_size, 0, hole_size,
3548                                         0, 0, 0);
3549                         BUG_ON(err);
3550
3551                         btrfs_drop_extent_cache(inode, hole_start,
3552                                         last_byte - 1, 0);
3553
3554                         btrfs_end_transaction(trans, root);
3555                 }
3556                 free_extent_map(em);
3557                 em = NULL;
3558                 cur_offset = last_byte;
3559                 if (cur_offset >= block_end)
3560                         break;
3561         }
3562
3563         free_extent_map(em);
3564         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3565                              GFP_NOFS);
3566         return err;
3567 }
3568
3569 static int btrfs_setattr_size(struct inode *inode, struct iattr *attr)
3570 {
3571         struct btrfs_root *root = BTRFS_I(inode)->root;
3572         struct btrfs_trans_handle *trans;
3573         unsigned long nr;
3574         int ret;
3575
3576         if (attr->ia_size == inode->i_size)
3577                 return 0;
3578
3579         if (attr->ia_size > inode->i_size) {
3580                 unsigned long limit;
3581                 limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
3582                 if (attr->ia_size > inode->i_sb->s_maxbytes)
3583                         return -EFBIG;
3584                 if (limit != RLIM_INFINITY && attr->ia_size > limit) {
3585                         send_sig(SIGXFSZ, current, 0);
3586                         return -EFBIG;
3587                 }
3588         }
3589
3590         trans = btrfs_start_transaction(root, 5);
3591         if (IS_ERR(trans))
3592                 return PTR_ERR(trans);
3593
3594         btrfs_set_trans_block_group(trans, inode);
3595
3596         ret = btrfs_orphan_add(trans, inode);
3597         BUG_ON(ret);
3598
3599         nr = trans->blocks_used;
3600         btrfs_end_transaction(trans, root);
3601         btrfs_btree_balance_dirty(root, nr);
3602
3603         if (attr->ia_size > inode->i_size) {
3604                 ret = btrfs_cont_expand(inode, attr->ia_size);
3605                 if (ret) {
3606                         btrfs_truncate(inode);
3607                         return ret;
3608                 }
3609
3610                 i_size_write(inode, attr->ia_size);
3611                 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
3612
3613                 trans = btrfs_start_transaction(root, 0);
3614                 BUG_ON(IS_ERR(trans));
3615                 btrfs_set_trans_block_group(trans, inode);
3616                 trans->block_rsv = root->orphan_block_rsv;
3617                 BUG_ON(!trans->block_rsv);
3618
3619                 ret = btrfs_update_inode(trans, root, inode);
3620                 BUG_ON(ret);
3621                 if (inode->i_nlink > 0) {
3622                         ret = btrfs_orphan_del(trans, inode);
3623                         BUG_ON(ret);
3624                 }
3625                 nr = trans->blocks_used;
3626                 btrfs_end_transaction(trans, root);
3627                 btrfs_btree_balance_dirty(root, nr);
3628                 return 0;
3629         }
3630
3631         /*
3632          * We're truncating a file that used to have good data down to
3633          * zero. Make sure it gets into the ordered flush list so that
3634          * any new writes get down to disk quickly.
3635          */
3636         if (attr->ia_size == 0)
3637                 BTRFS_I(inode)->ordered_data_close = 1;
3638
3639         /* we don't support swapfiles, so vmtruncate shouldn't fail */
3640         ret = vmtruncate(inode, attr->ia_size);
3641         BUG_ON(ret);
3642
3643         return 0;
3644 }
3645
3646 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3647 {
3648         struct inode *inode = dentry->d_inode;
3649         int err;
3650
3651         err = inode_change_ok(inode, attr);
3652         if (err)
3653                 return err;
3654
3655         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3656                 err = btrfs_setattr_size(inode, attr);
3657                 if (err)
3658                         return err;
3659         }
3660
3661         if (attr->ia_valid) {
3662                 setattr_copy(inode, attr);
3663                 mark_inode_dirty(inode);
3664
3665                 if (attr->ia_valid & ATTR_MODE)
3666                         err = btrfs_acl_chmod(inode);
3667         }
3668
3669         return err;
3670 }
3671
3672 void btrfs_evict_inode(struct inode *inode)
3673 {
3674         struct btrfs_trans_handle *trans;
3675         struct btrfs_root *root = BTRFS_I(inode)->root;
3676         unsigned long nr;
3677         int ret;
3678
3679         truncate_inode_pages(&inode->i_data, 0);
3680         if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3681                                root == root->fs_info->tree_root))
3682                 goto no_delete;
3683
3684         if (is_bad_inode(inode)) {
3685                 btrfs_orphan_del(NULL, inode);
3686                 goto no_delete;
3687         }
3688         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3689         btrfs_wait_ordered_range(inode, 0, (u64)-1);
3690
3691         if (root->fs_info->log_root_recovering) {
3692                 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3693                 goto no_delete;
3694         }
3695
3696         if (inode->i_nlink > 0) {
3697                 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3698                 goto no_delete;
3699         }
3700
3701         btrfs_i_size_write(inode, 0);
3702
3703         while (1) {
3704                 trans = btrfs_start_transaction(root, 0);
3705                 BUG_ON(IS_ERR(trans));
3706                 btrfs_set_trans_block_group(trans, inode);
3707                 trans->block_rsv = root->orphan_block_rsv;
3708
3709                 ret = btrfs_block_rsv_check(trans, root,
3710                                             root->orphan_block_rsv, 0, 5);
3711                 if (ret) {
3712                         BUG_ON(ret != -EAGAIN);
3713                         ret = btrfs_commit_transaction(trans, root);
3714                         BUG_ON(ret);
3715                         continue;
3716                 }
3717
3718                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3719                 if (ret != -EAGAIN)
3720                         break;
3721
3722                 nr = trans->blocks_used;
3723                 btrfs_end_transaction(trans, root);
3724                 trans = NULL;
3725                 btrfs_btree_balance_dirty(root, nr);
3726
3727         }
3728
3729         if (ret == 0) {
3730                 ret = btrfs_orphan_del(trans, inode);
3731                 BUG_ON(ret);
3732         }
3733
3734         nr = trans->blocks_used;
3735         btrfs_end_transaction(trans, root);
3736         btrfs_btree_balance_dirty(root, nr);
3737 no_delete:
3738         end_writeback(inode);
3739         return;
3740 }
3741
3742 /*
3743  * this returns the key found in the dir entry in the location pointer.
3744  * If no dir entries were found, location->objectid is 0.
3745  */
3746 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3747                                struct btrfs_key *location)
3748 {
3749         const char *name = dentry->d_name.name;
3750         int namelen = dentry->d_name.len;
3751         struct btrfs_dir_item *di;
3752         struct btrfs_path *path;
3753         struct btrfs_root *root = BTRFS_I(dir)->root;
3754         int ret = 0;
3755
3756         path = btrfs_alloc_path();
3757         BUG_ON(!path);
3758
3759         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
3760                                     namelen, 0);
3761         if (IS_ERR(di))
3762                 ret = PTR_ERR(di);
3763
3764         if (!di || IS_ERR(di))
3765                 goto out_err;
3766
3767         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3768 out:
3769         btrfs_free_path(path);
3770         return ret;
3771 out_err:
3772         location->objectid = 0;
3773         goto out;
3774 }
3775
3776 /*
3777  * when we hit a tree root in a directory, the btrfs part of the inode
3778  * needs to be changed to reflect the root directory of the tree root.  This
3779  * is kind of like crossing a mount point.
3780  */
3781 static int fixup_tree_root_location(struct btrfs_root *root,
3782                                     struct inode *dir,
3783                                     struct dentry *dentry,
3784                                     struct btrfs_key *location,
3785                                     struct btrfs_root **sub_root)
3786 {
3787         struct btrfs_path *path;
3788         struct btrfs_root *new_root;
3789         struct btrfs_root_ref *ref;
3790         struct extent_buffer *leaf;
3791         int ret;
3792         int err = 0;
3793
3794         path = btrfs_alloc_path();
3795         if (!path) {
3796                 err = -ENOMEM;
3797                 goto out;
3798         }
3799
3800         err = -ENOENT;
3801         ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3802                                   BTRFS_I(dir)->root->root_key.objectid,
3803                                   location->objectid);
3804         if (ret) {
3805                 if (ret < 0)
3806                         err = ret;
3807                 goto out;
3808         }
3809
3810         leaf = path->nodes[0];
3811         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3812         if (btrfs_root_ref_dirid(leaf, ref) != dir->i_ino ||
3813             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3814                 goto out;
3815
3816         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3817                                    (unsigned long)(ref + 1),
3818                                    dentry->d_name.len);
3819         if (ret)
3820                 goto out;
3821
3822         btrfs_release_path(root->fs_info->tree_root, path);
3823
3824         new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3825         if (IS_ERR(new_root)) {
3826                 err = PTR_ERR(new_root);
3827                 goto out;
3828         }
3829
3830         if (btrfs_root_refs(&new_root->root_item) == 0) {
3831                 err = -ENOENT;
3832                 goto out;
3833         }
3834
3835         *sub_root = new_root;
3836         location->objectid = btrfs_root_dirid(&new_root->root_item);
3837         location->type = BTRFS_INODE_ITEM_KEY;
3838         location->offset = 0;
3839         err = 0;
3840 out:
3841         btrfs_free_path(path);
3842         return err;
3843 }
3844
3845 static void inode_tree_add(struct inode *inode)
3846 {
3847         struct btrfs_root *root = BTRFS_I(inode)->root;
3848         struct btrfs_inode *entry;
3849         struct rb_node **p;
3850         struct rb_node *parent;
3851 again:
3852         p = &root->inode_tree.rb_node;
3853         parent = NULL;
3854
3855         if (hlist_unhashed(&inode->i_hash))
3856                 return;
3857
3858         spin_lock(&root->inode_lock);
3859         while (*p) {
3860                 parent = *p;
3861                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3862
3863                 if (inode->i_ino < entry->vfs_inode.i_ino)
3864                         p = &parent->rb_left;
3865                 else if (inode->i_ino > entry->vfs_inode.i_ino)
3866                         p = &parent->rb_right;
3867                 else {
3868                         WARN_ON(!(entry->vfs_inode.i_state &
3869                                   (I_WILL_FREE | I_FREEING)));
3870                         rb_erase(parent, &root->inode_tree);
3871                         RB_CLEAR_NODE(parent);
3872                         spin_unlock(&root->inode_lock);
3873                         goto again;
3874                 }
3875         }
3876         rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3877         rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3878         spin_unlock(&root->inode_lock);
3879 }
3880
3881 static void inode_tree_del(struct inode *inode)
3882 {
3883         struct btrfs_root *root = BTRFS_I(inode)->root;
3884         int empty = 0;
3885
3886         spin_lock(&root->inode_lock);
3887         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3888                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3889                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3890                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3891         }
3892         spin_unlock(&root->inode_lock);
3893
3894         /*
3895          * Free space cache has inodes in the tree root, but the tree root has a
3896          * root_refs of 0, so this could end up dropping the tree root as a
3897          * snapshot, so we need the extra !root->fs_info->tree_root check to
3898          * make sure we don't drop it.
3899          */
3900         if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3901             root != root->fs_info->tree_root) {
3902                 synchronize_srcu(&root->fs_info->subvol_srcu);
3903                 spin_lock(&root->inode_lock);
3904                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3905                 spin_unlock(&root->inode_lock);
3906                 if (empty)
3907                         btrfs_add_dead_root(root);
3908         }
3909 }
3910
3911 int btrfs_invalidate_inodes(struct btrfs_root *root)
3912 {
3913         struct rb_node *node;
3914         struct rb_node *prev;
3915         struct btrfs_inode *entry;
3916         struct inode *inode;
3917         u64 objectid = 0;
3918
3919         WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3920
3921         spin_lock(&root->inode_lock);
3922 again:
3923         node = root->inode_tree.rb_node;
3924         prev = NULL;
3925         while (node) {
3926                 prev = node;
3927                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3928
3929                 if (objectid < entry->vfs_inode.i_ino)
3930                         node = node->rb_left;
3931                 else if (objectid > entry->vfs_inode.i_ino)
3932                         node = node->rb_right;
3933                 else
3934                         break;
3935         }
3936         if (!node) {
3937                 while (prev) {
3938                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
3939                         if (objectid <= entry->vfs_inode.i_ino) {
3940                                 node = prev;
3941                                 break;
3942                         }
3943                         prev = rb_next(prev);
3944                 }
3945         }
3946         while (node) {
3947                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3948                 objectid = entry->vfs_inode.i_ino + 1;
3949                 inode = igrab(&entry->vfs_inode);
3950                 if (inode) {
3951                         spin_unlock(&root->inode_lock);
3952                         if (atomic_read(&inode->i_count) > 1)
3953                                 d_prune_aliases(inode);
3954                         /*
3955                          * btrfs_drop_inode will have it removed from
3956                          * the inode cache when its usage count
3957                          * hits zero.
3958                          */
3959                         iput(inode);
3960                         cond_resched();
3961                         spin_lock(&root->inode_lock);
3962                         goto again;
3963                 }
3964
3965                 if (cond_resched_lock(&root->inode_lock))
3966                         goto again;
3967
3968                 node = rb_next(node);
3969         }
3970         spin_unlock(&root->inode_lock);
3971         return 0;
3972 }
3973
3974 static int btrfs_init_locked_inode(struct inode *inode, void *p)
3975 {
3976         struct btrfs_iget_args *args = p;
3977         inode->i_ino = args->ino;
3978         BTRFS_I(inode)->root = args->root;
3979         btrfs_set_inode_space_info(args->root, inode);
3980         return 0;
3981 }
3982
3983 static int btrfs_find_actor(struct inode *inode, void *opaque)
3984 {
3985         struct btrfs_iget_args *args = opaque;
3986         return args->ino == inode->i_ino &&
3987                 args->root == BTRFS_I(inode)->root;
3988 }
3989
3990 static struct inode *btrfs_iget_locked(struct super_block *s,
3991                                        u64 objectid,
3992                                        struct btrfs_root *root)
3993 {
3994         struct inode *inode;
3995         struct btrfs_iget_args args;
3996         args.ino = objectid;
3997         args.root = root;
3998
3999         inode = iget5_locked(s, objectid, btrfs_find_actor,
4000                              btrfs_init_locked_inode,
4001                              (void *)&args);
4002         return inode;
4003 }
4004
4005 /* Get an inode object given its location and corresponding root.
4006  * Returns in *is_new if the inode was read from disk
4007  */
4008 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4009                          struct btrfs_root *root, int *new)
4010 {
4011         struct inode *inode;
4012
4013         inode = btrfs_iget_locked(s, location->objectid, root);
4014         if (!inode)
4015                 return ERR_PTR(-ENOMEM);
4016
4017         if (inode->i_state & I_NEW) {
4018                 BTRFS_I(inode)->root = root;
4019                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4020                 btrfs_read_locked_inode(inode);
4021
4022                 inode_tree_add(inode);
4023                 unlock_new_inode(inode);
4024                 if (new)
4025                         *new = 1;
4026         }
4027
4028         return inode;
4029 }
4030
4031 static struct inode *new_simple_dir(struct super_block *s,
4032                                     struct btrfs_key *key,
4033                                     struct btrfs_root *root)
4034 {
4035         struct inode *inode = new_inode(s);
4036
4037         if (!inode)
4038                 return ERR_PTR(-ENOMEM);
4039
4040         BTRFS_I(inode)->root = root;
4041         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4042         BTRFS_I(inode)->dummy_inode = 1;
4043
4044         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4045         inode->i_op = &simple_dir_inode_operations;
4046         inode->i_fop = &simple_dir_operations;
4047         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4048         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4049
4050         return inode;
4051 }
4052
4053 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4054 {
4055         struct inode *inode;
4056         struct btrfs_root *root = BTRFS_I(dir)->root;
4057         struct btrfs_root *sub_root = root;
4058         struct btrfs_key location;
4059         int index;
4060         int ret;
4061
4062         dentry->d_op = &btrfs_dentry_operations;
4063
4064         if (dentry->d_name.len > BTRFS_NAME_LEN)
4065                 return ERR_PTR(-ENAMETOOLONG);
4066
4067         ret = btrfs_inode_by_name(dir, dentry, &location);
4068
4069         if (ret < 0)
4070                 return ERR_PTR(ret);
4071
4072         if (location.objectid == 0)
4073                 return NULL;
4074
4075         if (location.type == BTRFS_INODE_ITEM_KEY) {
4076                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4077                 return inode;
4078         }
4079
4080         BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4081
4082         index = srcu_read_lock(&root->fs_info->subvol_srcu);
4083         ret = fixup_tree_root_location(root, dir, dentry,
4084                                        &location, &sub_root);
4085         if (ret < 0) {
4086                 if (ret != -ENOENT)
4087                         inode = ERR_PTR(ret);
4088                 else
4089                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
4090         } else {
4091                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4092         }
4093         srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4094
4095         if (root != sub_root) {
4096                 down_read(&root->fs_info->cleanup_work_sem);
4097                 if (!(inode->i_sb->s_flags & MS_RDONLY))
4098                         btrfs_orphan_cleanup(sub_root);
4099                 up_read(&root->fs_info->cleanup_work_sem);
4100         }
4101
4102         return inode;
4103 }
4104
4105 static int btrfs_dentry_delete(struct dentry *dentry)
4106 {
4107         struct btrfs_root *root;
4108
4109         if (!dentry->d_inode && !IS_ROOT(dentry))
4110                 dentry = dentry->d_parent;
4111
4112         if (dentry->d_inode) {
4113                 root = BTRFS_I(dentry->d_inode)->root;
4114                 if (btrfs_root_refs(&root->root_item) == 0)
4115                         return 1;
4116         }
4117         return 0;
4118 }
4119
4120 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4121                                    struct nameidata *nd)
4122 {
4123         struct inode *inode;
4124
4125         inode = btrfs_lookup_dentry(dir, dentry);
4126         if (IS_ERR(inode))
4127                 return ERR_CAST(inode);
4128
4129         return d_splice_alias(inode, dentry);
4130 }
4131
4132 static unsigned char btrfs_filetype_table[] = {
4133         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4134 };
4135
4136 static int btrfs_real_readdir(struct file *filp, void *dirent,
4137                               filldir_t filldir)
4138 {
4139         struct inode *inode = filp->f_dentry->d_inode;
4140         struct btrfs_root *root = BTRFS_I(inode)->root;
4141         struct btrfs_item *item;
4142         struct btrfs_dir_item *di;
4143         struct btrfs_key key;
4144         struct btrfs_key found_key;
4145         struct btrfs_path *path;
4146         int ret;
4147         u32 nritems;
4148         struct extent_buffer *leaf;
4149         int slot;
4150         int advance;
4151         unsigned char d_type;
4152         int over = 0;
4153         u32 di_cur;
4154         u32 di_total;
4155         u32 di_len;
4156         int key_type = BTRFS_DIR_INDEX_KEY;
4157         char tmp_name[32];
4158         char *name_ptr;
4159         int name_len;
4160
4161         /* FIXME, use a real flag for deciding about the key type */
4162         if (root->fs_info->tree_root == root)
4163                 key_type = BTRFS_DIR_ITEM_KEY;
4164
4165         /* special case for "." */
4166         if (filp->f_pos == 0) {
4167                 over = filldir(dirent, ".", 1,
4168                                1, inode->i_ino,
4169                                DT_DIR);
4170                 if (over)
4171                         return 0;
4172                 filp->f_pos = 1;
4173         }
4174         /* special case for .., just use the back ref */
4175         if (filp->f_pos == 1) {
4176                 u64 pino = parent_ino(filp->f_path.dentry);
4177                 over = filldir(dirent, "..", 2,
4178                                2, pino, DT_DIR);
4179                 if (over)
4180                         return 0;
4181                 filp->f_pos = 2;
4182         }
4183         path = btrfs_alloc_path();
4184         path->reada = 2;
4185
4186         btrfs_set_key_type(&key, key_type);
4187         key.offset = filp->f_pos;
4188         key.objectid = inode->i_ino;
4189
4190         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4191         if (ret < 0)
4192                 goto err;
4193         advance = 0;
4194
4195         while (1) {
4196                 leaf = path->nodes[0];
4197                 nritems = btrfs_header_nritems(leaf);
4198                 slot = path->slots[0];
4199                 if (advance || slot >= nritems) {
4200                         if (slot >= nritems - 1) {
4201                                 ret = btrfs_next_leaf(root, path);
4202                                 if (ret)
4203                                         break;
4204                                 leaf = path->nodes[0];
4205                                 nritems = btrfs_header_nritems(leaf);
4206                                 slot = path->slots[0];
4207                         } else {
4208                                 slot++;
4209                                 path->slots[0]++;
4210                         }
4211                 }
4212
4213                 advance = 1;
4214                 item = btrfs_item_nr(leaf, slot);
4215                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4216
4217                 if (found_key.objectid != key.objectid)
4218                         break;
4219                 if (btrfs_key_type(&found_key) != key_type)
4220                         break;
4221                 if (found_key.offset < filp->f_pos)
4222                         continue;
4223
4224                 filp->f_pos = found_key.offset;
4225
4226                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4227                 di_cur = 0;
4228                 di_total = btrfs_item_size(leaf, item);
4229
4230                 while (di_cur < di_total) {
4231                         struct btrfs_key location;
4232
4233                         name_len = btrfs_dir_name_len(leaf, di);
4234                         if (name_len <= sizeof(tmp_name)) {
4235                                 name_ptr = tmp_name;
4236                         } else {
4237                                 name_ptr = kmalloc(name_len, GFP_NOFS);
4238                                 if (!name_ptr) {
4239                                         ret = -ENOMEM;
4240                                         goto err;
4241                                 }
4242                         }
4243                         read_extent_buffer(leaf, name_ptr,
4244                                            (unsigned long)(di + 1), name_len);
4245
4246                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4247                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
4248
4249                         /* is this a reference to our own snapshot? If so
4250                          * skip it
4251                          */
4252                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
4253                             location.objectid == root->root_key.objectid) {
4254                                 over = 0;
4255                                 goto skip;
4256                         }
4257                         over = filldir(dirent, name_ptr, name_len,
4258                                        found_key.offset, location.objectid,
4259                                        d_type);
4260
4261 skip:
4262                         if (name_ptr != tmp_name)
4263                                 kfree(name_ptr);
4264
4265                         if (over)
4266                                 goto nopos;
4267                         di_len = btrfs_dir_name_len(leaf, di) +
4268                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
4269                         di_cur += di_len;
4270                         di = (struct btrfs_dir_item *)((char *)di + di_len);
4271                 }
4272         }
4273
4274         /* Reached end of directory/root. Bump pos past the last item. */
4275         if (key_type == BTRFS_DIR_INDEX_KEY)
4276                 /*
4277                  * 32-bit glibc will use getdents64, but then strtol -
4278                  * so the last number we can serve is this.
4279                  */
4280                 filp->f_pos = 0x7fffffff;
4281         else
4282                 filp->f_pos++;
4283 nopos:
4284         ret = 0;
4285 err:
4286         btrfs_free_path(path);
4287         return ret;
4288 }
4289
4290 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4291 {
4292         struct btrfs_root *root = BTRFS_I(inode)->root;
4293         struct btrfs_trans_handle *trans;
4294         int ret = 0;
4295         bool nolock = false;
4296
4297         if (BTRFS_I(inode)->dummy_inode)
4298                 return 0;
4299
4300         smp_mb();
4301         nolock = (root->fs_info->closing && root == root->fs_info->tree_root);
4302
4303         if (wbc->sync_mode == WB_SYNC_ALL) {
4304                 if (nolock)
4305                         trans = btrfs_join_transaction_nolock(root, 1);
4306                 else
4307                         trans = btrfs_join_transaction(root, 1);
4308                 btrfs_set_trans_block_group(trans, inode);
4309                 if (nolock)
4310                         ret = btrfs_end_transaction_nolock(trans, root);
4311                 else
4312                         ret = btrfs_commit_transaction(trans, root);
4313         }
4314         return ret;
4315 }
4316
4317 /*
4318  * This is somewhat expensive, updating the tree every time the
4319  * inode changes.  But, it is most likely to find the inode in cache.
4320  * FIXME, needs more benchmarking...there are no reasons other than performance
4321  * to keep or drop this code.
4322  */
4323 void btrfs_dirty_inode(struct inode *inode)
4324 {
4325         struct btrfs_root *root = BTRFS_I(inode)->root;
4326         struct btrfs_trans_handle *trans;
4327         int ret;
4328
4329         if (BTRFS_I(inode)->dummy_inode)
4330                 return;
4331
4332         trans = btrfs_join_transaction(root, 1);
4333         btrfs_set_trans_block_group(trans, inode);
4334
4335         ret = btrfs_update_inode(trans, root, inode);
4336         if (ret && ret == -ENOSPC) {
4337                 /* whoops, lets try again with the full transaction */
4338                 btrfs_end_transaction(trans, root);
4339                 trans = btrfs_start_transaction(root, 1);
4340                 if (IS_ERR(trans)) {
4341                         if (printk_ratelimit()) {
4342                                 printk(KERN_ERR "btrfs: fail to "
4343                                        "dirty  inode %lu error %ld\n",
4344                                        inode->i_ino, PTR_ERR(trans));
4345                         }
4346                         return;
4347                 }
4348                 btrfs_set_trans_block_group(trans, inode);
4349
4350                 ret = btrfs_update_inode(trans, root, inode);
4351                 if (ret) {
4352                         if (printk_ratelimit()) {
4353                                 printk(KERN_ERR "btrfs: fail to "
4354                                        "dirty  inode %lu error %d\n",
4355                                        inode->i_ino, ret);
4356                         }
4357                 }
4358         }
4359         btrfs_end_transaction(trans, root);
4360 }
4361
4362 /*
4363  * find the highest existing sequence number in a directory
4364  * and then set the in-memory index_cnt variable to reflect
4365  * free sequence numbers
4366  */
4367 static int btrfs_set_inode_index_count(struct inode *inode)
4368 {
4369         struct btrfs_root *root = BTRFS_I(inode)->root;
4370         struct btrfs_key key, found_key;
4371         struct btrfs_path *path;
4372         struct extent_buffer *leaf;
4373         int ret;
4374
4375         key.objectid = inode->i_ino;
4376         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4377         key.offset = (u64)-1;
4378
4379         path = btrfs_alloc_path();
4380         if (!path)
4381                 return -ENOMEM;
4382
4383         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4384         if (ret < 0)
4385                 goto out;
4386         /* FIXME: we should be able to handle this */
4387         if (ret == 0)
4388                 goto out;
4389         ret = 0;
4390
4391         /*
4392          * MAGIC NUMBER EXPLANATION:
4393          * since we search a directory based on f_pos we have to start at 2
4394          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4395          * else has to start at 2
4396          */
4397         if (path->slots[0] == 0) {
4398                 BTRFS_I(inode)->index_cnt = 2;
4399                 goto out;
4400         }
4401
4402         path->slots[0]--;
4403
4404         leaf = path->nodes[0];
4405         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4406
4407         if (found_key.objectid != inode->i_ino ||
4408             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4409                 BTRFS_I(inode)->index_cnt = 2;
4410                 goto out;
4411         }
4412
4413         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4414 out:
4415         btrfs_free_path(path);
4416         return ret;
4417 }
4418
4419 /*
4420  * helper to find a free sequence number in a given directory.  This current
4421  * code is very simple, later versions will do smarter things in the btree
4422  */
4423 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4424 {
4425         int ret = 0;
4426
4427         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4428                 ret = btrfs_set_inode_index_count(dir);
4429                 if (ret)
4430                         return ret;
4431         }
4432
4433         *index = BTRFS_I(dir)->index_cnt;
4434         BTRFS_I(dir)->index_cnt++;
4435
4436         return ret;
4437 }
4438
4439 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4440                                      struct btrfs_root *root,
4441                                      struct inode *dir,
4442                                      const char *name, int name_len,
4443                                      u64 ref_objectid, u64 objectid,
4444                                      u64 alloc_hint, int mode, u64 *index)
4445 {
4446         struct inode *inode;
4447         struct btrfs_inode_item *inode_item;
4448         struct btrfs_key *location;
4449         struct btrfs_path *path;
4450         struct btrfs_inode_ref *ref;
4451         struct btrfs_key key[2];
4452         u32 sizes[2];
4453         unsigned long ptr;
4454         int ret;
4455         int owner;
4456
4457         path = btrfs_alloc_path();
4458         BUG_ON(!path);
4459
4460         inode = new_inode(root->fs_info->sb);
4461         if (!inode)
4462                 return ERR_PTR(-ENOMEM);
4463
4464         if (dir) {
4465                 ret = btrfs_set_inode_index(dir, index);
4466                 if (ret) {
4467                         iput(inode);
4468                         return ERR_PTR(ret);
4469                 }
4470         }
4471         /*
4472          * index_cnt is ignored for everything but a dir,
4473          * btrfs_get_inode_index_count has an explanation for the magic
4474          * number
4475          */
4476         BTRFS_I(inode)->index_cnt = 2;
4477         BTRFS_I(inode)->root = root;
4478         BTRFS_I(inode)->generation = trans->transid;
4479         btrfs_set_inode_space_info(root, inode);
4480
4481         if (mode & S_IFDIR)
4482                 owner = 0;
4483         else
4484                 owner = 1;
4485         BTRFS_I(inode)->block_group =
4486                         btrfs_find_block_group(root, 0, alloc_hint, owner);
4487
4488         key[0].objectid = objectid;
4489         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4490         key[0].offset = 0;
4491
4492         key[1].objectid = objectid;
4493         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4494         key[1].offset = ref_objectid;
4495
4496         sizes[0] = sizeof(struct btrfs_inode_item);
4497         sizes[1] = name_len + sizeof(*ref);
4498
4499         path->leave_spinning = 1;
4500         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4501         if (ret != 0)
4502                 goto fail;
4503
4504         inode_init_owner(inode, dir, mode);
4505         inode->i_ino = objectid;
4506         inode_set_bytes(inode, 0);
4507         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4508         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4509                                   struct btrfs_inode_item);
4510         fill_inode_item(trans, path->nodes[0], inode_item, inode);
4511
4512         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4513                              struct btrfs_inode_ref);
4514         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4515         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4516         ptr = (unsigned long)(ref + 1);
4517         write_extent_buffer(path->nodes[0], name, ptr, name_len);
4518
4519         btrfs_mark_buffer_dirty(path->nodes[0]);
4520         btrfs_free_path(path);
4521
4522         location = &BTRFS_I(inode)->location;
4523         location->objectid = objectid;
4524         location->offset = 0;
4525         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4526
4527         btrfs_inherit_iflags(inode, dir);
4528
4529         if ((mode & S_IFREG)) {
4530                 if (btrfs_test_opt(root, NODATASUM))
4531                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4532                 if (btrfs_test_opt(root, NODATACOW))
4533                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4534         }
4535
4536         insert_inode_hash(inode);
4537         inode_tree_add(inode);
4538         return inode;
4539 fail:
4540         if (dir)
4541                 BTRFS_I(dir)->index_cnt--;
4542         btrfs_free_path(path);
4543         iput(inode);
4544         return ERR_PTR(ret);
4545 }
4546
4547 static inline u8 btrfs_inode_type(struct inode *inode)
4548 {
4549         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4550 }
4551
4552 /*
4553  * utility function to add 'inode' into 'parent_inode' with
4554  * a give name and a given sequence number.
4555  * if 'add_backref' is true, also insert a backref from the
4556  * inode to the parent directory.
4557  */
4558 int btrfs_add_link(struct btrfs_trans_handle *trans,
4559                    struct inode *parent_inode, struct inode *inode,
4560                    const char *name, int name_len, int add_backref, u64 index)
4561 {
4562         int ret = 0;
4563         struct btrfs_key key;
4564         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4565
4566         if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4567                 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4568         } else {
4569                 key.objectid = inode->i_ino;
4570                 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4571                 key.offset = 0;
4572         }
4573
4574         if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4575                 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4576                                          key.objectid, root->root_key.objectid,
4577                                          parent_inode->i_ino,
4578                                          index, name, name_len);
4579         } else if (add_backref) {
4580                 ret = btrfs_insert_inode_ref(trans, root,
4581                                              name, name_len, inode->i_ino,
4582                                              parent_inode->i_ino, index);
4583         }
4584
4585         if (ret == 0) {
4586                 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4587                                             parent_inode->i_ino, &key,
4588                                             btrfs_inode_type(inode), index);
4589                 BUG_ON(ret);
4590
4591                 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4592                                    name_len * 2);
4593                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4594                 ret = btrfs_update_inode(trans, root, parent_inode);
4595         }
4596         return ret;
4597 }
4598
4599 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4600                             struct dentry *dentry, struct inode *inode,
4601                             int backref, u64 index)
4602 {
4603         int err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4604                                  inode, dentry->d_name.name,
4605                                  dentry->d_name.len, backref, index);
4606         if (!err) {
4607                 d_instantiate(dentry, inode);
4608                 return 0;
4609         }
4610         if (err > 0)
4611                 err = -EEXIST;
4612         return err;
4613 }
4614
4615 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4616                         int mode, dev_t rdev)
4617 {
4618         struct btrfs_trans_handle *trans;
4619         struct btrfs_root *root = BTRFS_I(dir)->root;
4620         struct inode *inode = NULL;
4621         int err;
4622         int drop_inode = 0;
4623         u64 objectid;
4624         unsigned long nr = 0;
4625         u64 index = 0;
4626
4627         if (!new_valid_dev(rdev))
4628                 return -EINVAL;
4629
4630         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4631         if (err)
4632                 return err;
4633
4634         /*
4635          * 2 for inode item and ref
4636          * 2 for dir items
4637          * 1 for xattr if selinux is on
4638          */
4639         trans = btrfs_start_transaction(root, 5);
4640         if (IS_ERR(trans))
4641                 return PTR_ERR(trans);
4642
4643         btrfs_set_trans_block_group(trans, dir);
4644
4645         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4646                                 dentry->d_name.len,
4647                                 dentry->d_parent->d_inode->i_ino, objectid,
4648                                 BTRFS_I(dir)->block_group, mode, &index);
4649         err = PTR_ERR(inode);
4650         if (IS_ERR(inode))
4651                 goto out_unlock;
4652
4653         err = btrfs_init_inode_security(trans, inode, dir);
4654         if (err) {
4655                 drop_inode = 1;
4656                 goto out_unlock;
4657         }
4658
4659         btrfs_set_trans_block_group(trans, inode);
4660         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4661         if (err)
4662                 drop_inode = 1;
4663         else {
4664                 inode->i_op = &btrfs_special_inode_operations;
4665                 init_special_inode(inode, inode->i_mode, rdev);
4666                 btrfs_update_inode(trans, root, inode);
4667         }
4668         btrfs_update_inode_block_group(trans, inode);
4669         btrfs_update_inode_block_group(trans, dir);
4670 out_unlock:
4671         nr = trans->blocks_used;
4672         btrfs_end_transaction_throttle(trans, root);
4673         btrfs_btree_balance_dirty(root, nr);
4674         if (drop_inode) {
4675                 inode_dec_link_count(inode);
4676                 iput(inode);
4677         }
4678         return err;
4679 }
4680
4681 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4682                         int mode, struct nameidata *nd)
4683 {
4684         struct btrfs_trans_handle *trans;
4685         struct btrfs_root *root = BTRFS_I(dir)->root;
4686         struct inode *inode = NULL;
4687         int drop_inode = 0;
4688         int err;
4689         unsigned long nr = 0;
4690         u64 objectid;
4691         u64 index = 0;
4692
4693         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4694         if (err)
4695                 return err;
4696         /*
4697          * 2 for inode item and ref
4698          * 2 for dir items
4699          * 1 for xattr if selinux is on
4700          */
4701         trans = btrfs_start_transaction(root, 5);
4702         if (IS_ERR(trans))
4703                 return PTR_ERR(trans);
4704
4705         btrfs_set_trans_block_group(trans, dir);
4706
4707         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4708                                 dentry->d_name.len,
4709                                 dentry->d_parent->d_inode->i_ino,
4710                                 objectid, BTRFS_I(dir)->block_group, mode,
4711                                 &index);
4712         err = PTR_ERR(inode);
4713         if (IS_ERR(inode))
4714                 goto out_unlock;
4715
4716         err = btrfs_init_inode_security(trans, inode, dir);
4717         if (err) {
4718                 drop_inode = 1;
4719                 goto out_unlock;
4720         }
4721
4722         btrfs_set_trans_block_group(trans, inode);
4723         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4724         if (err)
4725                 drop_inode = 1;
4726         else {
4727                 inode->i_mapping->a_ops = &btrfs_aops;
4728                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4729                 inode->i_fop = &btrfs_file_operations;
4730                 inode->i_op = &btrfs_file_inode_operations;
4731                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4732         }
4733         btrfs_update_inode_block_group(trans, inode);
4734         btrfs_update_inode_block_group(trans, dir);
4735 out_unlock:
4736         nr = trans->blocks_used;
4737         btrfs_end_transaction_throttle(trans, root);
4738         if (drop_inode) {
4739                 inode_dec_link_count(inode);
4740                 iput(inode);
4741         }
4742         btrfs_btree_balance_dirty(root, nr);
4743         return err;
4744 }
4745
4746 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4747                       struct dentry *dentry)
4748 {
4749         struct btrfs_trans_handle *trans;
4750         struct btrfs_root *root = BTRFS_I(dir)->root;
4751         struct inode *inode = old_dentry->d_inode;
4752         u64 index;
4753         unsigned long nr = 0;
4754         int err;
4755         int drop_inode = 0;
4756
4757         if (inode->i_nlink == 0)
4758                 return -ENOENT;
4759
4760         /* do not allow sys_link's with other subvols of the same device */
4761         if (root->objectid != BTRFS_I(inode)->root->objectid)
4762                 return -EPERM;
4763
4764         btrfs_inc_nlink(inode);
4765
4766         err = btrfs_set_inode_index(dir, &index);
4767         if (err)
4768                 goto fail;
4769
4770         /*
4771          * 1 item for inode ref
4772          * 2 items for dir items
4773          */
4774         trans = btrfs_start_transaction(root, 3);
4775         if (IS_ERR(trans)) {
4776                 err = PTR_ERR(trans);
4777                 goto fail;
4778         }
4779
4780         btrfs_set_trans_block_group(trans, dir);
4781         atomic_inc(&inode->i_count);
4782
4783         err = btrfs_add_nondir(trans, dentry, inode, 1, index);
4784
4785         if (err) {
4786                 drop_inode = 1;
4787         } else {
4788                 btrfs_update_inode_block_group(trans, dir);
4789                 err = btrfs_update_inode(trans, root, inode);
4790                 BUG_ON(err);
4791                 btrfs_log_new_name(trans, inode, NULL, dentry->d_parent);
4792         }
4793
4794         nr = trans->blocks_used;
4795         btrfs_end_transaction_throttle(trans, root);
4796 fail:
4797         if (drop_inode) {
4798                 inode_dec_link_count(inode);
4799                 iput(inode);
4800         }
4801         btrfs_btree_balance_dirty(root, nr);
4802         return err;
4803 }
4804
4805 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4806 {
4807         struct inode *inode = NULL;
4808         struct btrfs_trans_handle *trans;
4809         struct btrfs_root *root = BTRFS_I(dir)->root;
4810         int err = 0;
4811         int drop_on_err = 0;
4812         u64 objectid = 0;
4813         u64 index = 0;
4814         unsigned long nr = 1;
4815
4816         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4817         if (err)
4818                 return err;
4819
4820         /*
4821          * 2 items for inode and ref
4822          * 2 items for dir items
4823          * 1 for xattr if selinux is on
4824          */
4825         trans = btrfs_start_transaction(root, 5);
4826         if (IS_ERR(trans))
4827                 return PTR_ERR(trans);
4828         btrfs_set_trans_block_group(trans, dir);
4829
4830         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4831                                 dentry->d_name.len,
4832                                 dentry->d_parent->d_inode->i_ino, objectid,
4833                                 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4834                                 &index);
4835         if (IS_ERR(inode)) {
4836                 err = PTR_ERR(inode);
4837                 goto out_fail;
4838         }
4839
4840         drop_on_err = 1;
4841
4842         err = btrfs_init_inode_security(trans, inode, dir);
4843         if (err)
4844                 goto out_fail;
4845
4846         inode->i_op = &btrfs_dir_inode_operations;
4847         inode->i_fop = &btrfs_dir_file_operations;
4848         btrfs_set_trans_block_group(trans, inode);
4849
4850         btrfs_i_size_write(inode, 0);
4851         err = btrfs_update_inode(trans, root, inode);
4852         if (err)
4853                 goto out_fail;
4854
4855         err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4856                                  inode, dentry->d_name.name,
4857                                  dentry->d_name.len, 0, index);
4858         if (err)
4859                 goto out_fail;
4860
4861         d_instantiate(dentry, inode);
4862         drop_on_err = 0;
4863         btrfs_update_inode_block_group(trans, inode);
4864         btrfs_update_inode_block_group(trans, dir);
4865
4866 out_fail:
4867         nr = trans->blocks_used;
4868         btrfs_end_transaction_throttle(trans, root);
4869         if (drop_on_err)
4870                 iput(inode);
4871         btrfs_btree_balance_dirty(root, nr);
4872         return err;
4873 }
4874
4875 /* helper for btfs_get_extent.  Given an existing extent in the tree,
4876  * and an extent that you want to insert, deal with overlap and insert
4877  * the new extent into the tree.
4878  */
4879 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4880                                 struct extent_map *existing,
4881                                 struct extent_map *em,
4882                                 u64 map_start, u64 map_len)
4883 {
4884         u64 start_diff;
4885
4886         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4887         start_diff = map_start - em->start;
4888         em->start = map_start;
4889         em->len = map_len;
4890         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4891             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4892                 em->block_start += start_diff;
4893                 em->block_len -= start_diff;
4894         }
4895         return add_extent_mapping(em_tree, em);
4896 }
4897
4898 static noinline int uncompress_inline(struct btrfs_path *path,
4899                                       struct inode *inode, struct page *page,
4900                                       size_t pg_offset, u64 extent_offset,
4901                                       struct btrfs_file_extent_item *item)
4902 {
4903         int ret;
4904         struct extent_buffer *leaf = path->nodes[0];
4905         char *tmp;
4906         size_t max_size;
4907         unsigned long inline_size;
4908         unsigned long ptr;
4909
4910         WARN_ON(pg_offset != 0);
4911         max_size = btrfs_file_extent_ram_bytes(leaf, item);
4912         inline_size = btrfs_file_extent_inline_item_len(leaf,
4913                                         btrfs_item_nr(leaf, path->slots[0]));
4914         tmp = kmalloc(inline_size, GFP_NOFS);
4915         ptr = btrfs_file_extent_inline_start(item);
4916
4917         read_extent_buffer(leaf, tmp, ptr, inline_size);
4918
4919         max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4920         ret = btrfs_zlib_decompress(tmp, page, extent_offset,
4921                                     inline_size, max_size);
4922         if (ret) {
4923                 char *kaddr = kmap_atomic(page, KM_USER0);
4924                 unsigned long copy_size = min_t(u64,
4925                                   PAGE_CACHE_SIZE - pg_offset,
4926                                   max_size - extent_offset);
4927                 memset(kaddr + pg_offset, 0, copy_size);
4928                 kunmap_atomic(kaddr, KM_USER0);
4929         }
4930         kfree(tmp);
4931         return 0;
4932 }
4933
4934 /*
4935  * a bit scary, this does extent mapping from logical file offset to the disk.
4936  * the ugly parts come from merging extents from the disk with the in-ram
4937  * representation.  This gets more complex because of the data=ordered code,
4938  * where the in-ram extents might be locked pending data=ordered completion.
4939  *
4940  * This also copies inline extents directly into the page.
4941  */
4942
4943 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4944                                     size_t pg_offset, u64 start, u64 len,
4945                                     int create)
4946 {
4947         int ret;
4948         int err = 0;
4949         u64 bytenr;
4950         u64 extent_start = 0;
4951         u64 extent_end = 0;
4952         u64 objectid = inode->i_ino;
4953         u32 found_type;
4954         struct btrfs_path *path = NULL;
4955         struct btrfs_root *root = BTRFS_I(inode)->root;
4956         struct btrfs_file_extent_item *item;
4957         struct extent_buffer *leaf;
4958         struct btrfs_key found_key;
4959         struct extent_map *em = NULL;
4960         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4961         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4962         struct btrfs_trans_handle *trans = NULL;
4963         int compressed;
4964
4965 again:
4966         read_lock(&em_tree->lock);
4967         em = lookup_extent_mapping(em_tree, start, len);
4968         if (em)
4969                 em->bdev = root->fs_info->fs_devices->latest_bdev;
4970         read_unlock(&em_tree->lock);
4971
4972         if (em) {
4973                 if (em->start > start || em->start + em->len <= start)
4974                         free_extent_map(em);
4975                 else if (em->block_start == EXTENT_MAP_INLINE && page)
4976                         free_extent_map(em);
4977                 else
4978                         goto out;
4979         }
4980         em = alloc_extent_map(GFP_NOFS);
4981         if (!em) {
4982                 err = -ENOMEM;
4983                 goto out;
4984         }
4985         em->bdev = root->fs_info->fs_devices->latest_bdev;
4986         em->start = EXTENT_MAP_HOLE;
4987         em->orig_start = EXTENT_MAP_HOLE;
4988         em->len = (u64)-1;
4989         em->block_len = (u64)-1;
4990
4991         if (!path) {
4992                 path = btrfs_alloc_path();
4993                 BUG_ON(!path);
4994         }
4995
4996         ret = btrfs_lookup_file_extent(trans, root, path,
4997                                        objectid, start, trans != NULL);
4998         if (ret < 0) {
4999                 err = ret;
5000                 goto out;
5001         }
5002
5003         if (ret != 0) {
5004                 if (path->slots[0] == 0)
5005                         goto not_found;
5006                 path->slots[0]--;
5007         }
5008
5009         leaf = path->nodes[0];
5010         item = btrfs_item_ptr(leaf, path->slots[0],
5011                               struct btrfs_file_extent_item);
5012         /* are we inside the extent that was found? */
5013         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5014         found_type = btrfs_key_type(&found_key);
5015         if (found_key.objectid != objectid ||
5016             found_type != BTRFS_EXTENT_DATA_KEY) {
5017                 goto not_found;
5018         }
5019
5020         found_type = btrfs_file_extent_type(leaf, item);
5021         extent_start = found_key.offset;
5022         compressed = btrfs_file_extent_compression(leaf, item);
5023         if (found_type == BTRFS_FILE_EXTENT_REG ||
5024             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5025                 extent_end = extent_start +
5026                        btrfs_file_extent_num_bytes(leaf, item);
5027         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5028                 size_t size;
5029                 size = btrfs_file_extent_inline_len(leaf, item);
5030                 extent_end = (extent_start + size + root->sectorsize - 1) &
5031                         ~((u64)root->sectorsize - 1);
5032         }
5033
5034         if (start >= extent_end) {
5035                 path->slots[0]++;
5036                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5037                         ret = btrfs_next_leaf(root, path);
5038                         if (ret < 0) {
5039                                 err = ret;
5040                                 goto out;
5041                         }
5042                         if (ret > 0)
5043                                 goto not_found;
5044                         leaf = path->nodes[0];
5045                 }
5046                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5047                 if (found_key.objectid != objectid ||
5048                     found_key.type != BTRFS_EXTENT_DATA_KEY)
5049                         goto not_found;
5050                 if (start + len <= found_key.offset)
5051                         goto not_found;
5052                 em->start = start;
5053                 em->len = found_key.offset - start;
5054                 goto not_found_em;
5055         }
5056
5057         if (found_type == BTRFS_FILE_EXTENT_REG ||
5058             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5059                 em->start = extent_start;
5060                 em->len = extent_end - extent_start;
5061                 em->orig_start = extent_start -
5062                                  btrfs_file_extent_offset(leaf, item);
5063                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5064                 if (bytenr == 0) {
5065                         em->block_start = EXTENT_MAP_HOLE;
5066                         goto insert;
5067                 }
5068                 if (compressed) {
5069                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5070                         em->block_start = bytenr;
5071                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5072                                                                          item);
5073                 } else {
5074                         bytenr += btrfs_file_extent_offset(leaf, item);
5075                         em->block_start = bytenr;
5076                         em->block_len = em->len;
5077                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5078                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5079                 }
5080                 goto insert;
5081         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5082                 unsigned long ptr;
5083                 char *map;
5084                 size_t size;
5085                 size_t extent_offset;
5086                 size_t copy_size;
5087
5088                 em->block_start = EXTENT_MAP_INLINE;
5089                 if (!page || create) {
5090                         em->start = extent_start;
5091                         em->len = extent_end - extent_start;
5092                         goto out;
5093                 }
5094
5095                 size = btrfs_file_extent_inline_len(leaf, item);
5096                 extent_offset = page_offset(page) + pg_offset - extent_start;
5097                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5098                                 size - extent_offset);
5099                 em->start = extent_start + extent_offset;
5100                 em->len = (copy_size + root->sectorsize - 1) &
5101                         ~((u64)root->sectorsize - 1);
5102                 em->orig_start = EXTENT_MAP_INLINE;
5103                 if (compressed)
5104                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5105                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5106                 if (create == 0 && !PageUptodate(page)) {
5107                         if (btrfs_file_extent_compression(leaf, item) ==
5108                             BTRFS_COMPRESS_ZLIB) {
5109                                 ret = uncompress_inline(path, inode, page,
5110                                                         pg_offset,
5111                                                         extent_offset, item);
5112                                 BUG_ON(ret);
5113                         } else {
5114                                 map = kmap(page);
5115                                 read_extent_buffer(leaf, map + pg_offset, ptr,
5116                                                    copy_size);
5117                                 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5118                                         memset(map + pg_offset + copy_size, 0,
5119                                                PAGE_CACHE_SIZE - pg_offset -
5120                                                copy_size);
5121                                 }
5122                                 kunmap(page);
5123                         }
5124                         flush_dcache_page(page);
5125                 } else if (create && PageUptodate(page)) {
5126                         WARN_ON(1);
5127                         if (!trans) {
5128                                 kunmap(page);
5129                                 free_extent_map(em);
5130                                 em = NULL;
5131                                 btrfs_release_path(root, path);
5132                                 trans = btrfs_join_transaction(root, 1);
5133                                 goto again;
5134                         }
5135                         map = kmap(page);
5136                         write_extent_buffer(leaf, map + pg_offset, ptr,
5137                                             copy_size);
5138                         kunmap(page);
5139                         btrfs_mark_buffer_dirty(leaf);
5140                 }
5141                 set_extent_uptodate(io_tree, em->start,
5142                                     extent_map_end(em) - 1, GFP_NOFS);
5143                 goto insert;
5144         } else {
5145                 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5146                 WARN_ON(1);
5147         }
5148 not_found:
5149         em->start = start;
5150         em->len = len;
5151 not_found_em:
5152         em->block_start = EXTENT_MAP_HOLE;
5153         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5154 insert:
5155         btrfs_release_path(root, path);
5156         if (em->start > start || extent_map_end(em) <= start) {
5157                 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5158                        "[%llu %llu]\n", (unsigned long long)em->start,
5159                        (unsigned long long)em->len,
5160                        (unsigned long long)start,
5161                        (unsigned long long)len);
5162                 err = -EIO;
5163                 goto out;
5164         }
5165
5166         err = 0;
5167         write_lock(&em_tree->lock);
5168         ret = add_extent_mapping(em_tree, em);
5169         /* it is possible that someone inserted the extent into the tree
5170          * while we had the lock dropped.  It is also possible that
5171          * an overlapping map exists in the tree
5172          */
5173         if (ret == -EEXIST) {
5174                 struct extent_map *existing;
5175
5176                 ret = 0;
5177
5178                 existing = lookup_extent_mapping(em_tree, start, len);
5179                 if (existing && (existing->start > start ||
5180                     existing->start + existing->len <= start)) {
5181                         free_extent_map(existing);
5182                         existing = NULL;
5183                 }
5184                 if (!existing) {
5185                         existing = lookup_extent_mapping(em_tree, em->start,
5186                                                          em->len);
5187                         if (existing) {
5188                                 err = merge_extent_mapping(em_tree, existing,
5189                                                            em, start,
5190                                                            root->sectorsize);
5191                                 free_extent_map(existing);
5192                                 if (err) {
5193                                         free_extent_map(em);
5194                                         em = NULL;
5195                                 }
5196                         } else {
5197                                 err = -EIO;
5198                                 free_extent_map(em);
5199                                 em = NULL;
5200                         }
5201                 } else {
5202                         free_extent_map(em);
5203                         em = existing;
5204                         err = 0;
5205                 }
5206         }
5207         write_unlock(&em_tree->lock);
5208 out:
5209         if (path)
5210                 btrfs_free_path(path);
5211         if (trans) {
5212                 ret = btrfs_end_transaction(trans, root);
5213                 if (!err)
5214                         err = ret;
5215         }
5216         if (err) {
5217                 free_extent_map(em);
5218                 return ERR_PTR(err);
5219         }
5220         return em;
5221 }
5222
5223 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5224                                                   u64 start, u64 len)
5225 {
5226         struct btrfs_root *root = BTRFS_I(inode)->root;
5227         struct btrfs_trans_handle *trans;
5228         struct extent_map *em;
5229         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5230         struct btrfs_key ins;
5231         u64 alloc_hint;
5232         int ret;
5233
5234         btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5235
5236         trans = btrfs_join_transaction(root, 0);
5237         if (!trans)
5238                 return ERR_PTR(-ENOMEM);
5239
5240         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5241
5242         alloc_hint = get_extent_allocation_hint(inode, start, len);
5243         ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5244                                    alloc_hint, (u64)-1, &ins, 1);
5245         if (ret) {
5246                 em = ERR_PTR(ret);
5247                 goto out;
5248         }
5249
5250         em = alloc_extent_map(GFP_NOFS);
5251         if (!em) {
5252                 em = ERR_PTR(-ENOMEM);
5253                 goto out;
5254         }
5255
5256         em->start = start;
5257         em->orig_start = em->start;
5258         em->len = ins.offset;
5259
5260         em->block_start = ins.objectid;
5261         em->block_len = ins.offset;
5262         em->bdev = root->fs_info->fs_devices->latest_bdev;
5263         set_bit(EXTENT_FLAG_PINNED, &em->flags);
5264
5265         while (1) {
5266                 write_lock(&em_tree->lock);
5267                 ret = add_extent_mapping(em_tree, em);
5268                 write_unlock(&em_tree->lock);
5269                 if (ret != -EEXIST)
5270                         break;
5271                 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5272         }
5273
5274         ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5275                                            ins.offset, ins.offset, 0);
5276         if (ret) {
5277                 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5278                 em = ERR_PTR(ret);
5279         }
5280 out:
5281         btrfs_end_transaction(trans, root);
5282         return em;
5283 }
5284
5285 /*
5286  * returns 1 when the nocow is safe, < 1 on error, 0 if the
5287  * block must be cow'd
5288  */
5289 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5290                                       struct inode *inode, u64 offset, u64 len)
5291 {
5292         struct btrfs_path *path;
5293         int ret;
5294         struct extent_buffer *leaf;
5295         struct btrfs_root *root = BTRFS_I(inode)->root;
5296         struct btrfs_file_extent_item *fi;
5297         struct btrfs_key key;
5298         u64 disk_bytenr;
5299         u64 backref_offset;
5300         u64 extent_end;
5301         u64 num_bytes;
5302         int slot;
5303         int found_type;
5304
5305         path = btrfs_alloc_path();
5306         if (!path)
5307                 return -ENOMEM;
5308
5309         ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
5310                                        offset, 0);
5311         if (ret < 0)
5312                 goto out;
5313
5314         slot = path->slots[0];
5315         if (ret == 1) {
5316                 if (slot == 0) {
5317                         /* can't find the item, must cow */
5318                         ret = 0;
5319                         goto out;
5320                 }
5321                 slot--;
5322         }
5323         ret = 0;
5324         leaf = path->nodes[0];
5325         btrfs_item_key_to_cpu(leaf, &key, slot);
5326         if (key.objectid != inode->i_ino ||
5327             key.type != BTRFS_EXTENT_DATA_KEY) {
5328                 /* not our file or wrong item type, must cow */
5329                 goto out;
5330         }
5331
5332         if (key.offset > offset) {
5333                 /* Wrong offset, must cow */
5334                 goto out;
5335         }
5336
5337         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5338         found_type = btrfs_file_extent_type(leaf, fi);
5339         if (found_type != BTRFS_FILE_EXTENT_REG &&
5340             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5341                 /* not a regular extent, must cow */
5342                 goto out;
5343         }
5344         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5345         backref_offset = btrfs_file_extent_offset(leaf, fi);
5346
5347         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5348         if (extent_end < offset + len) {
5349                 /* extent doesn't include our full range, must cow */
5350                 goto out;
5351         }
5352
5353         if (btrfs_extent_readonly(root, disk_bytenr))
5354                 goto out;
5355
5356         /*
5357          * look for other files referencing this extent, if we
5358          * find any we must cow
5359          */
5360         if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
5361                                   key.offset - backref_offset, disk_bytenr))
5362                 goto out;
5363
5364         /*
5365          * adjust disk_bytenr and num_bytes to cover just the bytes
5366          * in this extent we are about to write.  If there
5367          * are any csums in that range we have to cow in order
5368          * to keep the csums correct
5369          */
5370         disk_bytenr += backref_offset;
5371         disk_bytenr += offset - key.offset;
5372         num_bytes = min(offset + len, extent_end) - offset;
5373         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5374                                 goto out;
5375         /*
5376          * all of the above have passed, it is safe to overwrite this extent
5377          * without cow
5378          */
5379         ret = 1;
5380 out:
5381         btrfs_free_path(path);
5382         return ret;
5383 }
5384
5385 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5386                                    struct buffer_head *bh_result, int create)
5387 {
5388         struct extent_map *em;
5389         struct btrfs_root *root = BTRFS_I(inode)->root;
5390         u64 start = iblock << inode->i_blkbits;
5391         u64 len = bh_result->b_size;
5392         struct btrfs_trans_handle *trans;
5393
5394         em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5395         if (IS_ERR(em))
5396                 return PTR_ERR(em);
5397
5398         /*
5399          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5400          * io.  INLINE is special, and we could probably kludge it in here, but
5401          * it's still buffered so for safety lets just fall back to the generic
5402          * buffered path.
5403          *
5404          * For COMPRESSED we _have_ to read the entire extent in so we can
5405          * decompress it, so there will be buffering required no matter what we
5406          * do, so go ahead and fallback to buffered.
5407          *
5408          * We return -ENOTBLK because thats what makes DIO go ahead and go back
5409          * to buffered IO.  Don't blame me, this is the price we pay for using
5410          * the generic code.
5411          */
5412         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5413             em->block_start == EXTENT_MAP_INLINE) {
5414                 free_extent_map(em);
5415                 return -ENOTBLK;
5416         }
5417
5418         /* Just a good old fashioned hole, return */
5419         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5420                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5421                 free_extent_map(em);
5422                 /* DIO will do one hole at a time, so just unlock a sector */
5423                 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5424                               start + root->sectorsize - 1, GFP_NOFS);
5425                 return 0;
5426         }
5427
5428         /*
5429          * We don't allocate a new extent in the following cases
5430          *
5431          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
5432          * existing extent.
5433          * 2) The extent is marked as PREALLOC.  We're good to go here and can
5434          * just use the extent.
5435          *
5436          */
5437         if (!create) {
5438                 len = em->len - (start - em->start);
5439                 goto map;
5440         }
5441
5442         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5443             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5444              em->block_start != EXTENT_MAP_HOLE)) {
5445                 int type;
5446                 int ret;
5447                 u64 block_start;
5448
5449                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5450                         type = BTRFS_ORDERED_PREALLOC;
5451                 else
5452                         type = BTRFS_ORDERED_NOCOW;
5453                 len = min(len, em->len - (start - em->start));
5454                 block_start = em->block_start + (start - em->start);
5455
5456                 /*
5457                  * we're not going to log anything, but we do need
5458                  * to make sure the current transaction stays open
5459                  * while we look for nocow cross refs
5460                  */
5461                 trans = btrfs_join_transaction(root, 0);
5462                 if (!trans)
5463                         goto must_cow;
5464
5465                 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5466                         ret = btrfs_add_ordered_extent_dio(inode, start,
5467                                            block_start, len, len, type);
5468                         btrfs_end_transaction(trans, root);
5469                         if (ret) {
5470                                 free_extent_map(em);
5471                                 return ret;
5472                         }
5473                         goto unlock;
5474                 }
5475                 btrfs_end_transaction(trans, root);
5476         }
5477 must_cow:
5478         /*
5479          * this will cow the extent, reset the len in case we changed
5480          * it above
5481          */
5482         len = bh_result->b_size;
5483         free_extent_map(em);
5484         em = btrfs_new_extent_direct(inode, start, len);
5485         if (IS_ERR(em))
5486                 return PTR_ERR(em);
5487         len = min(len, em->len - (start - em->start));
5488 unlock:
5489         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5490                           EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5491                           0, NULL, GFP_NOFS);
5492 map:
5493         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5494                 inode->i_blkbits;
5495         bh_result->b_size = len;
5496         bh_result->b_bdev = em->bdev;
5497         set_buffer_mapped(bh_result);
5498         if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5499                 set_buffer_new(bh_result);
5500
5501         free_extent_map(em);
5502
5503         return 0;
5504 }
5505
5506 struct btrfs_dio_private {
5507         struct inode *inode;
5508         u64 logical_offset;
5509         u64 disk_bytenr;
5510         u64 bytes;
5511         u32 *csums;
5512         void *private;
5513 };
5514
5515 static void btrfs_endio_direct_read(struct bio *bio, int err)
5516 {
5517         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5518         struct bio_vec *bvec = bio->bi_io_vec;
5519         struct btrfs_dio_private *dip = bio->bi_private;
5520         struct inode *inode = dip->inode;
5521         struct btrfs_root *root = BTRFS_I(inode)->root;
5522         u64 start;
5523         u32 *private = dip->csums;
5524
5525         start = dip->logical_offset;
5526         do {
5527                 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5528                         struct page *page = bvec->bv_page;
5529                         char *kaddr;
5530                         u32 csum = ~(u32)0;
5531                         unsigned long flags;
5532
5533                         local_irq_save(flags);
5534                         kaddr = kmap_atomic(page, KM_IRQ0);
5535                         csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5536                                                csum, bvec->bv_len);
5537                         btrfs_csum_final(csum, (char *)&csum);
5538                         kunmap_atomic(kaddr, KM_IRQ0);
5539                         local_irq_restore(flags);
5540
5541                         flush_dcache_page(bvec->bv_page);
5542                         if (csum != *private) {
5543                                 printk(KERN_ERR "btrfs csum failed ino %lu off"
5544                                       " %llu csum %u private %u\n",
5545                                       inode->i_ino, (unsigned long long)start,
5546                                       csum, *private);
5547                                 err = -EIO;
5548                         }
5549                 }
5550
5551                 start += bvec->bv_len;
5552                 private++;
5553                 bvec++;
5554         } while (bvec <= bvec_end);
5555
5556         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5557                       dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5558         bio->bi_private = dip->private;
5559
5560         kfree(dip->csums);
5561         kfree(dip);
5562         dio_end_io(bio, err);
5563 }
5564
5565 static void btrfs_endio_direct_write(struct bio *bio, int err)
5566 {
5567         struct btrfs_dio_private *dip = bio->bi_private;
5568         struct inode *inode = dip->inode;
5569         struct btrfs_root *root = BTRFS_I(inode)->root;
5570         struct btrfs_trans_handle *trans;
5571         struct btrfs_ordered_extent *ordered = NULL;
5572         struct extent_state *cached_state = NULL;
5573         int ret;
5574
5575         if (err)
5576                 goto out_done;
5577
5578         ret = btrfs_dec_test_ordered_pending(inode, &ordered,
5579                                              dip->logical_offset, dip->bytes);
5580         if (!ret)
5581                 goto out_done;
5582
5583         BUG_ON(!ordered);
5584
5585         trans = btrfs_join_transaction(root, 1);
5586         if (!trans) {
5587                 err = -ENOMEM;
5588                 goto out;
5589         }
5590         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5591
5592         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5593                 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5594                 if (!ret)
5595                         ret = btrfs_update_inode(trans, root, inode);
5596                 err = ret;
5597                 goto out;
5598         }
5599
5600         lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5601                          ordered->file_offset + ordered->len - 1, 0,
5602                          &cached_state, GFP_NOFS);
5603
5604         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5605                 ret = btrfs_mark_extent_written(trans, inode,
5606                                                 ordered->file_offset,
5607                                                 ordered->file_offset +
5608                                                 ordered->len);
5609                 if (ret) {
5610                         err = ret;
5611                         goto out_unlock;
5612                 }
5613         } else {
5614                 ret = insert_reserved_file_extent(trans, inode,
5615                                                   ordered->file_offset,
5616                                                   ordered->start,
5617                                                   ordered->disk_len,
5618                                                   ordered->len,
5619                                                   ordered->len,
5620                                                   0, 0, 0,
5621                                                   BTRFS_FILE_EXTENT_REG);
5622                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5623                                    ordered->file_offset, ordered->len);
5624                 if (ret) {
5625                         err = ret;
5626                         WARN_ON(1);
5627                         goto out_unlock;
5628                 }
5629         }
5630
5631         add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5632         btrfs_ordered_update_i_size(inode, 0, ordered);
5633         btrfs_update_inode(trans, root, inode);
5634 out_unlock:
5635         unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5636                              ordered->file_offset + ordered->len - 1,
5637                              &cached_state, GFP_NOFS);
5638 out:
5639         btrfs_delalloc_release_metadata(inode, ordered->len);
5640         btrfs_end_transaction(trans, root);
5641         btrfs_put_ordered_extent(ordered);
5642         btrfs_put_ordered_extent(ordered);
5643 out_done:
5644         bio->bi_private = dip->private;
5645
5646         kfree(dip->csums);
5647         kfree(dip);
5648         dio_end_io(bio, err);
5649 }
5650
5651 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5652                                     struct bio *bio, int mirror_num,
5653                                     unsigned long bio_flags, u64 offset)
5654 {
5655         int ret;
5656         struct btrfs_root *root = BTRFS_I(inode)->root;
5657         ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5658         BUG_ON(ret);
5659         return 0;
5660 }
5661
5662 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
5663                                 loff_t file_offset)
5664 {
5665         struct btrfs_root *root = BTRFS_I(inode)->root;
5666         struct btrfs_dio_private *dip;
5667         struct bio_vec *bvec = bio->bi_io_vec;
5668         u64 start;
5669         int skip_sum;
5670         int write = rw & REQ_WRITE;
5671         int ret = 0;
5672
5673         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
5674
5675         dip = kmalloc(sizeof(*dip), GFP_NOFS);
5676         if (!dip) {
5677                 ret = -ENOMEM;
5678                 goto free_ordered;
5679         }
5680         dip->csums = NULL;
5681
5682         if (!skip_sum) {
5683                 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
5684                 if (!dip->csums) {
5685                         ret = -ENOMEM;
5686                         goto free_ordered;
5687                 }
5688         }
5689
5690         dip->private = bio->bi_private;
5691         dip->inode = inode;
5692         dip->logical_offset = file_offset;
5693
5694         start = dip->logical_offset;
5695         dip->bytes = 0;
5696         do {
5697                 dip->bytes += bvec->bv_len;
5698                 bvec++;
5699         } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
5700
5701         dip->disk_bytenr = (u64)bio->bi_sector << 9;
5702         bio->bi_private = dip;
5703
5704         if (write)
5705                 bio->bi_end_io = btrfs_endio_direct_write;
5706         else
5707                 bio->bi_end_io = btrfs_endio_direct_read;
5708
5709         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5710         if (ret)
5711                 goto out_err;
5712
5713         if (write && !skip_sum) {
5714                 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
5715                                    inode, rw, bio, 0, 0,
5716                                    dip->logical_offset,
5717                                    __btrfs_submit_bio_start_direct_io,
5718                                    __btrfs_submit_bio_done);
5719                 if (ret)
5720                         goto out_err;
5721                 return;
5722         } else if (!skip_sum)
5723                 btrfs_lookup_bio_sums_dio(root, inode, bio,
5724                                           dip->logical_offset, dip->csums);
5725
5726         ret = btrfs_map_bio(root, rw, bio, 0, 1);
5727         if (ret)
5728                 goto out_err;
5729         return;
5730 out_err:
5731         kfree(dip->csums);
5732         kfree(dip);
5733 free_ordered:
5734         /*
5735          * If this is a write, we need to clean up the reserved space and kill
5736          * the ordered extent.
5737          */
5738         if (write) {
5739                 struct btrfs_ordered_extent *ordered;
5740                 ordered = btrfs_lookup_ordered_extent(inode,
5741                                                       dip->logical_offset);
5742                 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
5743                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
5744                         btrfs_free_reserved_extent(root, ordered->start,
5745                                                    ordered->disk_len);
5746                 btrfs_put_ordered_extent(ordered);
5747                 btrfs_put_ordered_extent(ordered);
5748         }
5749         bio_endio(bio, ret);
5750 }
5751
5752 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
5753                         const struct iovec *iov, loff_t offset,
5754                         unsigned long nr_segs)
5755 {
5756         int seg;
5757         size_t size;
5758         unsigned long addr;
5759         unsigned blocksize_mask = root->sectorsize - 1;
5760         ssize_t retval = -EINVAL;
5761         loff_t end = offset;
5762
5763         if (offset & blocksize_mask)
5764                 goto out;
5765
5766         /* Check the memory alignment.  Blocks cannot straddle pages */
5767         for (seg = 0; seg < nr_segs; seg++) {
5768                 addr = (unsigned long)iov[seg].iov_base;
5769                 size = iov[seg].iov_len;
5770                 end += size;
5771                 if ((addr & blocksize_mask) || (size & blocksize_mask)) 
5772                         goto out;
5773         }
5774         retval = 0;
5775 out:
5776         return retval;
5777 }
5778 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
5779                         const struct iovec *iov, loff_t offset,
5780                         unsigned long nr_segs)
5781 {
5782         struct file *file = iocb->ki_filp;
5783         struct inode *inode = file->f_mapping->host;
5784         struct btrfs_ordered_extent *ordered;
5785         struct extent_state *cached_state = NULL;
5786         u64 lockstart, lockend;
5787         ssize_t ret;
5788         int writing = rw & WRITE;
5789         int write_bits = 0;
5790         size_t count = iov_length(iov, nr_segs);
5791
5792         if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
5793                             offset, nr_segs)) {
5794                 return 0;
5795         }
5796
5797         lockstart = offset;
5798         lockend = offset + count - 1;
5799
5800         if (writing) {
5801                 ret = btrfs_delalloc_reserve_space(inode, count);
5802                 if (ret)
5803                         goto out;
5804         }
5805
5806         while (1) {
5807                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5808                                  0, &cached_state, GFP_NOFS);
5809                 /*
5810                  * We're concerned with the entire range that we're going to be
5811                  * doing DIO to, so we need to make sure theres no ordered
5812                  * extents in this range.
5813                  */
5814                 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5815                                                      lockend - lockstart + 1);
5816                 if (!ordered)
5817                         break;
5818                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5819                                      &cached_state, GFP_NOFS);
5820                 btrfs_start_ordered_extent(inode, ordered, 1);
5821                 btrfs_put_ordered_extent(ordered);
5822                 cond_resched();
5823         }
5824
5825         /*
5826          * we don't use btrfs_set_extent_delalloc because we don't want
5827          * the dirty or uptodate bits
5828          */
5829         if (writing) {
5830                 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
5831                 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5832                                      EXTENT_DELALLOC, 0, NULL, &cached_state,
5833                                      GFP_NOFS);
5834                 if (ret) {
5835                         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
5836                                          lockend, EXTENT_LOCKED | write_bits,
5837                                          1, 0, &cached_state, GFP_NOFS);
5838                         goto out;
5839                 }
5840         }
5841
5842         free_extent_state(cached_state);
5843         cached_state = NULL;
5844
5845         ret = __blockdev_direct_IO(rw, iocb, inode,
5846                    BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
5847                    iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
5848                    btrfs_submit_direct, 0);
5849
5850         if (ret < 0 && ret != -EIOCBQUEUED) {
5851                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
5852                               offset + iov_length(iov, nr_segs) - 1,
5853                               EXTENT_LOCKED | write_bits, 1, 0,
5854                               &cached_state, GFP_NOFS);
5855         } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
5856                 /*
5857                  * We're falling back to buffered, unlock the section we didn't
5858                  * do IO on.
5859                  */
5860                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
5861                               offset + iov_length(iov, nr_segs) - 1,
5862                               EXTENT_LOCKED | write_bits, 1, 0,
5863                               &cached_state, GFP_NOFS);
5864         }
5865 out:
5866         free_extent_state(cached_state);
5867         return ret;
5868 }
5869
5870 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5871                 __u64 start, __u64 len)
5872 {
5873         return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent);
5874 }
5875
5876 int btrfs_readpage(struct file *file, struct page *page)
5877 {
5878         struct extent_io_tree *tree;
5879         tree = &BTRFS_I(page->mapping->host)->io_tree;
5880         return extent_read_full_page(tree, page, btrfs_get_extent);
5881 }
5882
5883 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
5884 {
5885         struct extent_io_tree *tree;
5886
5887
5888         if (current->flags & PF_MEMALLOC) {
5889                 redirty_page_for_writepage(wbc, page);
5890                 unlock_page(page);
5891                 return 0;
5892         }
5893         tree = &BTRFS_I(page->mapping->host)->io_tree;
5894         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
5895 }
5896
5897 int btrfs_writepages(struct address_space *mapping,
5898                      struct writeback_control *wbc)
5899 {
5900         struct extent_io_tree *tree;
5901
5902         tree = &BTRFS_I(mapping->host)->io_tree;
5903         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
5904 }
5905
5906 static int
5907 btrfs_readpages(struct file *file, struct address_space *mapping,
5908                 struct list_head *pages, unsigned nr_pages)
5909 {
5910         struct extent_io_tree *tree;
5911         tree = &BTRFS_I(mapping->host)->io_tree;
5912         return extent_readpages(tree, mapping, pages, nr_pages,
5913                                 btrfs_get_extent);
5914 }
5915 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
5916 {
5917         struct extent_io_tree *tree;
5918         struct extent_map_tree *map;
5919         int ret;
5920
5921         tree = &BTRFS_I(page->mapping->host)->io_tree;
5922         map = &BTRFS_I(page->mapping->host)->extent_tree;
5923         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
5924         if (ret == 1) {
5925                 ClearPagePrivate(page);
5926                 set_page_private(page, 0);
5927                 page_cache_release(page);
5928         }
5929         return ret;
5930 }
5931
5932 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
5933 {
5934         if (PageWriteback(page) || PageDirty(page))
5935                 return 0;
5936         return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
5937 }
5938
5939 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
5940 {
5941         struct extent_io_tree *tree;
5942         struct btrfs_ordered_extent *ordered;
5943         struct extent_state *cached_state = NULL;
5944         u64 page_start = page_offset(page);
5945         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
5946
5947
5948         /*
5949          * we have the page locked, so new writeback can't start,
5950          * and the dirty bit won't be cleared while we are here.
5951          *
5952          * Wait for IO on this page so that we can safely clear
5953          * the PagePrivate2 bit and do ordered accounting
5954          */
5955         wait_on_page_writeback(page);
5956
5957         tree = &BTRFS_I(page->mapping->host)->io_tree;
5958         if (offset) {
5959                 btrfs_releasepage(page, GFP_NOFS);
5960                 return;
5961         }
5962         lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
5963                          GFP_NOFS);
5964         ordered = btrfs_lookup_ordered_extent(page->mapping->host,
5965                                            page_offset(page));
5966         if (ordered) {
5967                 /*
5968                  * IO on this page will never be started, so we need
5969                  * to account for any ordered extents now
5970                  */
5971                 clear_extent_bit(tree, page_start, page_end,
5972                                  EXTENT_DIRTY | EXTENT_DELALLOC |
5973                                  EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
5974                                  &cached_state, GFP_NOFS);
5975                 /*
5976                  * whoever cleared the private bit is responsible
5977                  * for the finish_ordered_io
5978                  */
5979                 if (TestClearPagePrivate2(page)) {
5980                         btrfs_finish_ordered_io(page->mapping->host,
5981                                                 page_start, page_end);
5982                 }
5983                 btrfs_put_ordered_extent(ordered);
5984                 cached_state = NULL;
5985                 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
5986                                  GFP_NOFS);
5987         }
5988         clear_extent_bit(tree, page_start, page_end,
5989                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
5990                  EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
5991         __btrfs_releasepage(page, GFP_NOFS);
5992
5993         ClearPageChecked(page);
5994         if (PagePrivate(page)) {
5995                 ClearPagePrivate(page);
5996                 set_page_private(page, 0);
5997                 page_cache_release(page);
5998         }
5999 }
6000
6001 /*
6002  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6003  * called from a page fault handler when a page is first dirtied. Hence we must
6004  * be careful to check for EOF conditions here. We set the page up correctly
6005  * for a written page which means we get ENOSPC checking when writing into
6006  * holes and correct delalloc and unwritten extent mapping on filesystems that
6007  * support these features.
6008  *
6009  * We are not allowed to take the i_mutex here so we have to play games to
6010  * protect against truncate races as the page could now be beyond EOF.  Because
6011  * vmtruncate() writes the inode size before removing pages, once we have the
6012  * page lock we can determine safely if the page is beyond EOF. If it is not
6013  * beyond EOF, then the page is guaranteed safe against truncation until we
6014  * unlock the page.
6015  */
6016 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6017 {
6018         struct page *page = vmf->page;
6019         struct inode *inode = fdentry(vma->vm_file)->d_inode;
6020         struct btrfs_root *root = BTRFS_I(inode)->root;
6021         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6022         struct btrfs_ordered_extent *ordered;
6023         struct extent_state *cached_state = NULL;
6024         char *kaddr;
6025         unsigned long zero_start;
6026         loff_t size;
6027         int ret;
6028         u64 page_start;
6029         u64 page_end;
6030
6031         ret  = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6032         if (ret) {
6033                 if (ret == -ENOMEM)
6034                         ret = VM_FAULT_OOM;
6035                 else /* -ENOSPC, -EIO, etc */
6036                         ret = VM_FAULT_SIGBUS;
6037                 goto out;
6038         }
6039
6040         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6041 again:
6042         lock_page(page);
6043         size = i_size_read(inode);
6044         page_start = page_offset(page);
6045         page_end = page_start + PAGE_CACHE_SIZE - 1;
6046
6047         if ((page->mapping != inode->i_mapping) ||
6048             (page_start >= size)) {
6049                 /* page got truncated out from underneath us */
6050                 goto out_unlock;
6051         }
6052         wait_on_page_writeback(page);
6053
6054         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6055                          GFP_NOFS);
6056         set_page_extent_mapped(page);
6057
6058         /*
6059          * we can't set the delalloc bits if there are pending ordered
6060          * extents.  Drop our locks and wait for them to finish
6061          */
6062         ordered = btrfs_lookup_ordered_extent(inode, page_start);
6063         if (ordered) {
6064                 unlock_extent_cached(io_tree, page_start, page_end,
6065                                      &cached_state, GFP_NOFS);
6066                 unlock_page(page);
6067                 btrfs_start_ordered_extent(inode, ordered, 1);
6068                 btrfs_put_ordered_extent(ordered);
6069                 goto again;
6070         }
6071
6072         /*
6073          * XXX - page_mkwrite gets called every time the page is dirtied, even
6074          * if it was already dirty, so for space accounting reasons we need to
6075          * clear any delalloc bits for the range we are fixing to save.  There
6076          * is probably a better way to do this, but for now keep consistent with
6077          * prepare_pages in the normal write path.
6078          */
6079         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6080                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6081                           0, 0, &cached_state, GFP_NOFS);
6082
6083         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6084                                         &cached_state);
6085         if (ret) {
6086                 unlock_extent_cached(io_tree, page_start, page_end,
6087                                      &cached_state, GFP_NOFS);
6088                 ret = VM_FAULT_SIGBUS;
6089                 goto out_unlock;
6090         }
6091         ret = 0;
6092
6093         /* page is wholly or partially inside EOF */
6094         if (page_start + PAGE_CACHE_SIZE > size)
6095                 zero_start = size & ~PAGE_CACHE_MASK;
6096         else
6097                 zero_start = PAGE_CACHE_SIZE;
6098
6099         if (zero_start != PAGE_CACHE_SIZE) {
6100                 kaddr = kmap(page);
6101                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6102                 flush_dcache_page(page);
6103                 kunmap(page);
6104         }
6105         ClearPageChecked(page);
6106         set_page_dirty(page);
6107         SetPageUptodate(page);
6108
6109         BTRFS_I(inode)->last_trans = root->fs_info->generation;
6110         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6111
6112         unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6113
6114 out_unlock:
6115         if (!ret)
6116                 return VM_FAULT_LOCKED;
6117         unlock_page(page);
6118         btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6119 out:
6120         return ret;
6121 }
6122
6123 static void btrfs_truncate(struct inode *inode)
6124 {
6125         struct btrfs_root *root = BTRFS_I(inode)->root;
6126         int ret;
6127         struct btrfs_trans_handle *trans;
6128         unsigned long nr;
6129         u64 mask = root->sectorsize - 1;
6130
6131         if (!S_ISREG(inode->i_mode)) {
6132                 WARN_ON(1);
6133                 return;
6134         }
6135
6136         ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6137         if (ret)
6138                 return;
6139
6140         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6141         btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6142
6143         trans = btrfs_start_transaction(root, 0);
6144         BUG_ON(IS_ERR(trans));
6145         btrfs_set_trans_block_group(trans, inode);
6146         trans->block_rsv = root->orphan_block_rsv;
6147
6148         /*
6149          * setattr is responsible for setting the ordered_data_close flag,
6150          * but that is only tested during the last file release.  That
6151          * could happen well after the next commit, leaving a great big
6152          * window where new writes may get lost if someone chooses to write
6153          * to this file after truncating to zero
6154          *
6155          * The inode doesn't have any dirty data here, and so if we commit
6156          * this is a noop.  If someone immediately starts writing to the inode
6157          * it is very likely we'll catch some of their writes in this
6158          * transaction, and the commit will find this file on the ordered
6159          * data list with good things to send down.
6160          *
6161          * This is a best effort solution, there is still a window where
6162          * using truncate to replace the contents of the file will
6163          * end up with a zero length file after a crash.
6164          */
6165         if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6166                 btrfs_add_ordered_operation(trans, root, inode);
6167
6168         while (1) {
6169                 if (!trans) {
6170                         trans = btrfs_start_transaction(root, 0);
6171                         BUG_ON(IS_ERR(trans));
6172                         btrfs_set_trans_block_group(trans, inode);
6173                         trans->block_rsv = root->orphan_block_rsv;
6174                 }
6175
6176                 ret = btrfs_block_rsv_check(trans, root,
6177                                             root->orphan_block_rsv, 0, 5);
6178                 if (ret) {
6179                         BUG_ON(ret != -EAGAIN);
6180                         ret = btrfs_commit_transaction(trans, root);
6181                         BUG_ON(ret);
6182                         trans = NULL;
6183                         continue;
6184                 }
6185
6186                 ret = btrfs_truncate_inode_items(trans, root, inode,
6187                                                  inode->i_size,
6188                                                  BTRFS_EXTENT_DATA_KEY);
6189                 if (ret != -EAGAIN)
6190                         break;
6191
6192                 ret = btrfs_update_inode(trans, root, inode);
6193                 BUG_ON(ret);
6194
6195                 nr = trans->blocks_used;
6196                 btrfs_end_transaction(trans, root);
6197                 trans = NULL;
6198                 btrfs_btree_balance_dirty(root, nr);
6199         }
6200
6201         if (ret == 0 && inode->i_nlink > 0) {
6202                 ret = btrfs_orphan_del(trans, inode);
6203                 BUG_ON(ret);
6204         }
6205
6206         ret = btrfs_update_inode(trans, root, inode);
6207         BUG_ON(ret);
6208
6209         nr = trans->blocks_used;
6210         ret = btrfs_end_transaction_throttle(trans, root);
6211         BUG_ON(ret);
6212         btrfs_btree_balance_dirty(root, nr);
6213 }
6214
6215 /*
6216  * create a new subvolume directory/inode (helper for the ioctl).
6217  */
6218 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6219                              struct btrfs_root *new_root,
6220                              u64 new_dirid, u64 alloc_hint)
6221 {
6222         struct inode *inode;
6223         int err;
6224         u64 index = 0;
6225
6226         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6227                                 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
6228         if (IS_ERR(inode))
6229                 return PTR_ERR(inode);
6230         inode->i_op = &btrfs_dir_inode_operations;
6231         inode->i_fop = &btrfs_dir_file_operations;
6232
6233         inode->i_nlink = 1;
6234         btrfs_i_size_write(inode, 0);
6235
6236         err = btrfs_update_inode(trans, new_root, inode);
6237         BUG_ON(err);
6238
6239         iput(inode);
6240         return 0;
6241 }
6242
6243 /* helper function for file defrag and space balancing.  This
6244  * forces readahead on a given range of bytes in an inode
6245  */
6246 unsigned long btrfs_force_ra(struct address_space *mapping,
6247                               struct file_ra_state *ra, struct file *file,
6248                               pgoff_t offset, pgoff_t last_index)
6249 {
6250         pgoff_t req_size = last_index - offset + 1;
6251
6252         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
6253         return offset + req_size;
6254 }
6255
6256 struct inode *btrfs_alloc_inode(struct super_block *sb)
6257 {
6258         struct btrfs_inode *ei;
6259         struct inode *inode;
6260
6261         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6262         if (!ei)
6263                 return NULL;
6264
6265         ei->root = NULL;
6266         ei->space_info = NULL;
6267         ei->generation = 0;
6268         ei->sequence = 0;
6269         ei->last_trans = 0;
6270         ei->last_sub_trans = 0;
6271         ei->logged_trans = 0;
6272         ei->delalloc_bytes = 0;
6273         ei->reserved_bytes = 0;
6274         ei->disk_i_size = 0;
6275         ei->flags = 0;
6276         ei->index_cnt = (u64)-1;
6277         ei->last_unlink_trans = 0;
6278
6279         spin_lock_init(&ei->accounting_lock);
6280         atomic_set(&ei->outstanding_extents, 0);
6281         ei->reserved_extents = 0;
6282
6283         ei->ordered_data_close = 0;
6284         ei->orphan_meta_reserved = 0;
6285         ei->dummy_inode = 0;
6286         ei->force_compress = 0;
6287
6288         inode = &ei->vfs_inode;
6289         extent_map_tree_init(&ei->extent_tree, GFP_NOFS);
6290         extent_io_tree_init(&ei->io_tree, &inode->i_data, GFP_NOFS);
6291         extent_io_tree_init(&ei->io_failure_tree, &inode->i_data, GFP_NOFS);
6292         mutex_init(&ei->log_mutex);
6293         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6294         INIT_LIST_HEAD(&ei->i_orphan);
6295         INIT_LIST_HEAD(&ei->delalloc_inodes);
6296         INIT_LIST_HEAD(&ei->ordered_operations);
6297         RB_CLEAR_NODE(&ei->rb_node);
6298
6299         return inode;
6300 }
6301
6302 void btrfs_destroy_inode(struct inode *inode)
6303 {
6304         struct btrfs_ordered_extent *ordered;
6305         struct btrfs_root *root = BTRFS_I(inode)->root;
6306
6307         WARN_ON(!list_empty(&inode->i_dentry));
6308         WARN_ON(inode->i_data.nrpages);
6309         WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents));
6310         WARN_ON(BTRFS_I(inode)->reserved_extents);
6311
6312         /*
6313          * This can happen where we create an inode, but somebody else also
6314          * created the same inode and we need to destroy the one we already
6315          * created.
6316          */
6317         if (!root)
6318                 goto free;
6319
6320         /*
6321          * Make sure we're properly removed from the ordered operation
6322          * lists.
6323          */
6324         smp_mb();
6325         if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6326                 spin_lock(&root->fs_info->ordered_extent_lock);
6327                 list_del_init(&BTRFS_I(inode)->ordered_operations);
6328                 spin_unlock(&root->fs_info->ordered_extent_lock);
6329         }
6330
6331         if (root == root->fs_info->tree_root) {
6332                 struct btrfs_block_group_cache *block_group;
6333
6334                 block_group = btrfs_lookup_block_group(root->fs_info,
6335                                                 BTRFS_I(inode)->block_group);
6336                 if (block_group && block_group->inode == inode) {
6337                         spin_lock(&block_group->lock);
6338                         block_group->inode = NULL;
6339                         spin_unlock(&block_group->lock);
6340                         btrfs_put_block_group(block_group);
6341                 } else if (block_group) {
6342                         btrfs_put_block_group(block_group);
6343                 }
6344         }
6345
6346         spin_lock(&root->orphan_lock);
6347         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6348                 printk(KERN_INFO "BTRFS: inode %lu still on the orphan list\n",
6349                        inode->i_ino);
6350                 list_del_init(&BTRFS_I(inode)->i_orphan);
6351         }
6352         spin_unlock(&root->orphan_lock);
6353
6354         while (1) {
6355                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6356                 if (!ordered)
6357                         break;
6358                 else {
6359                         printk(KERN_ERR "btrfs found ordered "
6360                                "extent %llu %llu on inode cleanup\n",
6361                                (unsigned long long)ordered->file_offset,
6362                                (unsigned long long)ordered->len);
6363                         btrfs_remove_ordered_extent(inode, ordered);
6364                         btrfs_put_ordered_extent(ordered);
6365                         btrfs_put_ordered_extent(ordered);
6366                 }
6367         }
6368         inode_tree_del(inode);
6369         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6370 free:
6371         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6372 }
6373
6374 int btrfs_drop_inode(struct inode *inode)
6375 {
6376         struct btrfs_root *root = BTRFS_I(inode)->root;
6377
6378         if (btrfs_root_refs(&root->root_item) == 0 &&
6379             root != root->fs_info->tree_root)
6380                 return 1;
6381         else
6382                 return generic_drop_inode(inode);
6383 }
6384
6385 static void init_once(void *foo)
6386 {
6387         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6388
6389         inode_init_once(&ei->vfs_inode);
6390 }
6391
6392 void btrfs_destroy_cachep(void)
6393 {
6394         if (btrfs_inode_cachep)
6395                 kmem_cache_destroy(btrfs_inode_cachep);
6396         if (btrfs_trans_handle_cachep)
6397                 kmem_cache_destroy(btrfs_trans_handle_cachep);
6398         if (btrfs_transaction_cachep)
6399                 kmem_cache_destroy(btrfs_transaction_cachep);
6400         if (btrfs_path_cachep)
6401                 kmem_cache_destroy(btrfs_path_cachep);
6402 }
6403
6404 int btrfs_init_cachep(void)
6405 {
6406         btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6407                         sizeof(struct btrfs_inode), 0,
6408                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6409         if (!btrfs_inode_cachep)
6410                 goto fail;
6411
6412         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6413                         sizeof(struct btrfs_trans_handle), 0,
6414                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6415         if (!btrfs_trans_handle_cachep)
6416                 goto fail;
6417
6418         btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6419                         sizeof(struct btrfs_transaction), 0,
6420                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6421         if (!btrfs_transaction_cachep)
6422                 goto fail;
6423
6424         btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6425                         sizeof(struct btrfs_path), 0,
6426                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6427         if (!btrfs_path_cachep)
6428                 goto fail;
6429
6430         return 0;
6431 fail:
6432         btrfs_destroy_cachep();
6433         return -ENOMEM;
6434 }
6435
6436 static int btrfs_getattr(struct vfsmount *mnt,
6437                          struct dentry *dentry, struct kstat *stat)
6438 {
6439         struct inode *inode = dentry->d_inode;
6440         generic_fillattr(inode, stat);
6441         stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
6442         stat->blksize = PAGE_CACHE_SIZE;
6443         stat->blocks = (inode_get_bytes(inode) +
6444                         BTRFS_I(inode)->delalloc_bytes) >> 9;
6445         return 0;
6446 }
6447
6448 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6449                            struct inode *new_dir, struct dentry *new_dentry)
6450 {
6451         struct btrfs_trans_handle *trans;
6452         struct btrfs_root *root = BTRFS_I(old_dir)->root;
6453         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6454         struct inode *new_inode = new_dentry->d_inode;
6455         struct inode *old_inode = old_dentry->d_inode;
6456         struct timespec ctime = CURRENT_TIME;
6457         u64 index = 0;
6458         u64 root_objectid;
6459         int ret;
6460
6461         if (new_dir->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6462                 return -EPERM;
6463
6464         /* we only allow rename subvolume link between subvolumes */
6465         if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6466                 return -EXDEV;
6467
6468         if (old_inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6469             (new_inode && new_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID))
6470                 return -ENOTEMPTY;
6471
6472         if (S_ISDIR(old_inode->i_mode) && new_inode &&
6473             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6474                 return -ENOTEMPTY;
6475         /*
6476          * we're using rename to replace one file with another.
6477          * and the replacement file is large.  Start IO on it now so
6478          * we don't add too much work to the end of the transaction
6479          */
6480         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6481             old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6482                 filemap_flush(old_inode->i_mapping);
6483
6484         /* close the racy window with snapshot create/destroy ioctl */
6485         if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6486                 down_read(&root->fs_info->subvol_sem);
6487         /*
6488          * We want to reserve the absolute worst case amount of items.  So if
6489          * both inodes are subvols and we need to unlink them then that would
6490          * require 4 item modifications, but if they are both normal inodes it
6491          * would require 5 item modifications, so we'll assume their normal
6492          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6493          * should cover the worst case number of items we'll modify.
6494          */
6495         trans = btrfs_start_transaction(root, 20);
6496         if (IS_ERR(trans))
6497                 return PTR_ERR(trans);
6498
6499         btrfs_set_trans_block_group(trans, new_dir);
6500
6501         if (dest != root)
6502                 btrfs_record_root_in_trans(trans, dest);
6503
6504         ret = btrfs_set_inode_index(new_dir, &index);
6505         if (ret)
6506                 goto out_fail;
6507
6508         if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6509                 /* force full log commit if subvolume involved. */
6510                 root->fs_info->last_trans_log_full_commit = trans->transid;
6511         } else {
6512                 ret = btrfs_insert_inode_ref(trans, dest,
6513                                              new_dentry->d_name.name,
6514                                              new_dentry->d_name.len,
6515                                              old_inode->i_ino,
6516                                              new_dir->i_ino, index);
6517                 if (ret)
6518                         goto out_fail;
6519                 /*
6520                  * this is an ugly little race, but the rename is required
6521                  * to make sure that if we crash, the inode is either at the
6522                  * old name or the new one.  pinning the log transaction lets
6523                  * us make sure we don't allow a log commit to come in after
6524                  * we unlink the name but before we add the new name back in.
6525                  */
6526                 btrfs_pin_log_trans(root);
6527         }
6528         /*
6529          * make sure the inode gets flushed if it is replacing
6530          * something.
6531          */
6532         if (new_inode && new_inode->i_size &&
6533             old_inode && S_ISREG(old_inode->i_mode)) {
6534                 btrfs_add_ordered_operation(trans, root, old_inode);
6535         }
6536
6537         old_dir->i_ctime = old_dir->i_mtime = ctime;
6538         new_dir->i_ctime = new_dir->i_mtime = ctime;
6539         old_inode->i_ctime = ctime;
6540
6541         if (old_dentry->d_parent != new_dentry->d_parent)
6542                 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6543
6544         if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6545                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6546                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6547                                         old_dentry->d_name.name,
6548                                         old_dentry->d_name.len);
6549         } else {
6550                 btrfs_inc_nlink(old_dentry->d_inode);
6551                 ret = btrfs_unlink_inode(trans, root, old_dir,
6552                                          old_dentry->d_inode,
6553                                          old_dentry->d_name.name,
6554                                          old_dentry->d_name.len);
6555         }
6556         BUG_ON(ret);
6557
6558         if (new_inode) {
6559                 new_inode->i_ctime = CURRENT_TIME;
6560                 if (unlikely(new_inode->i_ino ==
6561                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6562                         root_objectid = BTRFS_I(new_inode)->location.objectid;
6563                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
6564                                                 root_objectid,
6565                                                 new_dentry->d_name.name,
6566                                                 new_dentry->d_name.len);
6567                         BUG_ON(new_inode->i_nlink == 0);
6568                 } else {
6569                         ret = btrfs_unlink_inode(trans, dest, new_dir,
6570                                                  new_dentry->d_inode,
6571                                                  new_dentry->d_name.name,
6572                                                  new_dentry->d_name.len);
6573                 }
6574                 BUG_ON(ret);
6575                 if (new_inode->i_nlink == 0) {
6576                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
6577                         BUG_ON(ret);
6578                 }
6579         }
6580
6581         ret = btrfs_add_link(trans, new_dir, old_inode,
6582                              new_dentry->d_name.name,
6583                              new_dentry->d_name.len, 0, index);
6584         BUG_ON(ret);
6585
6586         if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
6587                 btrfs_log_new_name(trans, old_inode, old_dir,
6588                                    new_dentry->d_parent);
6589                 btrfs_end_log_trans(root);
6590         }
6591 out_fail:
6592         btrfs_end_transaction_throttle(trans, root);
6593
6594         if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6595                 up_read(&root->fs_info->subvol_sem);
6596
6597         return ret;
6598 }
6599
6600 /*
6601  * some fairly slow code that needs optimization. This walks the list
6602  * of all the inodes with pending delalloc and forces them to disk.
6603  */
6604 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
6605 {
6606         struct list_head *head = &root->fs_info->delalloc_inodes;
6607         struct btrfs_inode *binode;
6608         struct inode *inode;
6609
6610         if (root->fs_info->sb->s_flags & MS_RDONLY)
6611                 return -EROFS;
6612
6613         spin_lock(&root->fs_info->delalloc_lock);
6614         while (!list_empty(head)) {
6615                 binode = list_entry(head->next, struct btrfs_inode,
6616                                     delalloc_inodes);
6617                 inode = igrab(&binode->vfs_inode);
6618                 if (!inode)
6619                         list_del_init(&binode->delalloc_inodes);
6620                 spin_unlock(&root->fs_info->delalloc_lock);
6621                 if (inode) {
6622                         filemap_flush(inode->i_mapping);
6623                         if (delay_iput)
6624                                 btrfs_add_delayed_iput(inode);
6625                         else
6626                                 iput(inode);
6627                 }
6628                 cond_resched();
6629                 spin_lock(&root->fs_info->delalloc_lock);
6630         }
6631         spin_unlock(&root->fs_info->delalloc_lock);
6632
6633         /* the filemap_flush will queue IO into the worker threads, but
6634          * we have to make sure the IO is actually started and that
6635          * ordered extents get created before we return
6636          */
6637         atomic_inc(&root->fs_info->async_submit_draining);
6638         while (atomic_read(&root->fs_info->nr_async_submits) ||
6639               atomic_read(&root->fs_info->async_delalloc_pages)) {
6640                 wait_event(root->fs_info->async_submit_wait,
6641                    (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
6642                     atomic_read(&root->fs_info->async_delalloc_pages) == 0));
6643         }
6644         atomic_dec(&root->fs_info->async_submit_draining);
6645         return 0;
6646 }
6647
6648 int btrfs_start_one_delalloc_inode(struct btrfs_root *root, int delay_iput)
6649 {
6650         struct btrfs_inode *binode;
6651         struct inode *inode = NULL;
6652
6653         spin_lock(&root->fs_info->delalloc_lock);
6654         while (!list_empty(&root->fs_info->delalloc_inodes)) {
6655                 binode = list_entry(root->fs_info->delalloc_inodes.next,
6656                                     struct btrfs_inode, delalloc_inodes);
6657                 inode = igrab(&binode->vfs_inode);
6658                 if (inode) {
6659                         list_move_tail(&binode->delalloc_inodes,
6660                                        &root->fs_info->delalloc_inodes);
6661                         break;
6662                 }
6663
6664                 list_del_init(&binode->delalloc_inodes);
6665                 cond_resched_lock(&root->fs_info->delalloc_lock);
6666         }
6667         spin_unlock(&root->fs_info->delalloc_lock);
6668
6669         if (inode) {
6670                 write_inode_now(inode, 0);
6671                 if (delay_iput)
6672                         btrfs_add_delayed_iput(inode);
6673                 else
6674                         iput(inode);
6675                 return 1;
6676         }
6677         return 0;
6678 }
6679
6680 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
6681                          const char *symname)
6682 {
6683         struct btrfs_trans_handle *trans;
6684         struct btrfs_root *root = BTRFS_I(dir)->root;
6685         struct btrfs_path *path;
6686         struct btrfs_key key;
6687         struct inode *inode = NULL;
6688         int err;
6689         int drop_inode = 0;
6690         u64 objectid;
6691         u64 index = 0 ;
6692         int name_len;
6693         int datasize;
6694         unsigned long ptr;
6695         struct btrfs_file_extent_item *ei;
6696         struct extent_buffer *leaf;
6697         unsigned long nr = 0;
6698
6699         name_len = strlen(symname) + 1;
6700         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
6701                 return -ENAMETOOLONG;
6702
6703         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
6704         if (err)
6705                 return err;
6706         /*
6707          * 2 items for inode item and ref
6708          * 2 items for dir items
6709          * 1 item for xattr if selinux is on
6710          */
6711         trans = btrfs_start_transaction(root, 5);
6712         if (IS_ERR(trans))
6713                 return PTR_ERR(trans);
6714
6715         btrfs_set_trans_block_group(trans, dir);
6716
6717         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6718                                 dentry->d_name.len,
6719                                 dentry->d_parent->d_inode->i_ino, objectid,
6720                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
6721                                 &index);
6722         err = PTR_ERR(inode);
6723         if (IS_ERR(inode))
6724                 goto out_unlock;
6725
6726         err = btrfs_init_inode_security(trans, inode, dir);
6727         if (err) {
6728                 drop_inode = 1;
6729                 goto out_unlock;
6730         }
6731
6732         btrfs_set_trans_block_group(trans, inode);
6733         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
6734         if (err)
6735                 drop_inode = 1;
6736         else {
6737                 inode->i_mapping->a_ops = &btrfs_aops;
6738                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6739                 inode->i_fop = &btrfs_file_operations;
6740                 inode->i_op = &btrfs_file_inode_operations;
6741                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6742         }
6743         btrfs_update_inode_block_group(trans, inode);
6744         btrfs_update_inode_block_group(trans, dir);
6745         if (drop_inode)
6746                 goto out_unlock;
6747
6748         path = btrfs_alloc_path();
6749         BUG_ON(!path);
6750         key.objectid = inode->i_ino;
6751         key.offset = 0;
6752         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
6753         datasize = btrfs_file_extent_calc_inline_size(name_len);
6754         err = btrfs_insert_empty_item(trans, root, path, &key,
6755                                       datasize);
6756         if (err) {
6757                 drop_inode = 1;
6758                 goto out_unlock;
6759         }
6760         leaf = path->nodes[0];
6761         ei = btrfs_item_ptr(leaf, path->slots[0],
6762                             struct btrfs_file_extent_item);
6763         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
6764         btrfs_set_file_extent_type(leaf, ei,
6765                                    BTRFS_FILE_EXTENT_INLINE);
6766         btrfs_set_file_extent_encryption(leaf, ei, 0);
6767         btrfs_set_file_extent_compression(leaf, ei, 0);
6768         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
6769         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
6770
6771         ptr = btrfs_file_extent_inline_start(ei);
6772         write_extent_buffer(leaf, symname, ptr, name_len);
6773         btrfs_mark_buffer_dirty(leaf);
6774         btrfs_free_path(path);
6775
6776         inode->i_op = &btrfs_symlink_inode_operations;
6777         inode->i_mapping->a_ops = &btrfs_symlink_aops;
6778         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6779         inode_set_bytes(inode, name_len);
6780         btrfs_i_size_write(inode, name_len - 1);
6781         err = btrfs_update_inode(trans, root, inode);
6782         if (err)
6783                 drop_inode = 1;
6784
6785 out_unlock:
6786         nr = trans->blocks_used;
6787         btrfs_end_transaction_throttle(trans, root);
6788         if (drop_inode) {
6789                 inode_dec_link_count(inode);
6790                 iput(inode);
6791         }
6792         btrfs_btree_balance_dirty(root, nr);
6793         return err;
6794 }
6795
6796 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
6797                                        u64 start, u64 num_bytes, u64 min_size,
6798                                        loff_t actual_len, u64 *alloc_hint,
6799                                        struct btrfs_trans_handle *trans)
6800 {
6801         struct btrfs_root *root = BTRFS_I(inode)->root;
6802         struct btrfs_key ins;
6803         u64 cur_offset = start;
6804         int ret = 0;
6805         bool own_trans = true;
6806
6807         if (trans)
6808                 own_trans = false;
6809         while (num_bytes > 0) {
6810                 if (own_trans) {
6811                         trans = btrfs_start_transaction(root, 3);
6812                         if (IS_ERR(trans)) {
6813                                 ret = PTR_ERR(trans);
6814                                 break;
6815                         }
6816                 }
6817
6818                 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
6819                                            0, *alloc_hint, (u64)-1, &ins, 1);
6820                 if (ret) {
6821                         if (own_trans)
6822                                 btrfs_end_transaction(trans, root);
6823                         break;
6824                 }
6825
6826                 ret = insert_reserved_file_extent(trans, inode,
6827                                                   cur_offset, ins.objectid,
6828                                                   ins.offset, ins.offset,
6829                                                   ins.offset, 0, 0, 0,
6830                                                   BTRFS_FILE_EXTENT_PREALLOC);
6831                 BUG_ON(ret);
6832                 btrfs_drop_extent_cache(inode, cur_offset,
6833                                         cur_offset + ins.offset -1, 0);
6834
6835                 num_bytes -= ins.offset;
6836                 cur_offset += ins.offset;
6837                 *alloc_hint = ins.objectid + ins.offset;
6838
6839                 inode->i_ctime = CURRENT_TIME;
6840                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
6841                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
6842                     (actual_len > inode->i_size) &&
6843                     (cur_offset > inode->i_size)) {
6844                         if (cur_offset > actual_len)
6845                                 i_size_write(inode, actual_len);
6846                         else
6847                                 i_size_write(inode, cur_offset);
6848                         i_size_write(inode, cur_offset);
6849                         btrfs_ordered_update_i_size(inode, cur_offset, NULL);
6850                 }
6851
6852                 ret = btrfs_update_inode(trans, root, inode);
6853                 BUG_ON(ret);
6854
6855                 if (own_trans)
6856                         btrfs_end_transaction(trans, root);
6857         }
6858         return ret;
6859 }
6860
6861 int btrfs_prealloc_file_range(struct inode *inode, int mode,
6862                               u64 start, u64 num_bytes, u64 min_size,
6863                               loff_t actual_len, u64 *alloc_hint)
6864 {
6865         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
6866                                            min_size, actual_len, alloc_hint,
6867                                            NULL);
6868 }
6869
6870 int btrfs_prealloc_file_range_trans(struct inode *inode,
6871                                     struct btrfs_trans_handle *trans, int mode,
6872                                     u64 start, u64 num_bytes, u64 min_size,
6873                                     loff_t actual_len, u64 *alloc_hint)
6874 {
6875         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
6876                                            min_size, actual_len, alloc_hint, trans);
6877 }
6878
6879 static long btrfs_fallocate(struct inode *inode, int mode,
6880                             loff_t offset, loff_t len)
6881 {
6882         struct extent_state *cached_state = NULL;
6883         u64 cur_offset;
6884         u64 last_byte;
6885         u64 alloc_start;
6886         u64 alloc_end;
6887         u64 alloc_hint = 0;
6888         u64 locked_end;
6889         u64 mask = BTRFS_I(inode)->root->sectorsize - 1;
6890         struct extent_map *em;
6891         int ret;
6892
6893         alloc_start = offset & ~mask;
6894         alloc_end =  (offset + len + mask) & ~mask;
6895
6896         /*
6897          * wait for ordered IO before we have any locks.  We'll loop again
6898          * below with the locks held.
6899          */
6900         btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
6901
6902         mutex_lock(&inode->i_mutex);
6903         if (alloc_start > inode->i_size) {
6904                 ret = btrfs_cont_expand(inode, alloc_start);
6905                 if (ret)
6906                         goto out;
6907         }
6908
6909         ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
6910         if (ret)
6911                 goto out;
6912
6913         locked_end = alloc_end - 1;
6914         while (1) {
6915                 struct btrfs_ordered_extent *ordered;
6916
6917                 /* the extent lock is ordered inside the running
6918                  * transaction
6919                  */
6920                 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
6921                                  locked_end, 0, &cached_state, GFP_NOFS);
6922                 ordered = btrfs_lookup_first_ordered_extent(inode,
6923                                                             alloc_end - 1);
6924                 if (ordered &&
6925                     ordered->file_offset + ordered->len > alloc_start &&
6926                     ordered->file_offset < alloc_end) {
6927                         btrfs_put_ordered_extent(ordered);
6928                         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
6929                                              alloc_start, locked_end,
6930                                              &cached_state, GFP_NOFS);
6931                         /*
6932                          * we can't wait on the range with the transaction
6933                          * running or with the extent lock held
6934                          */
6935                         btrfs_wait_ordered_range(inode, alloc_start,
6936                                                  alloc_end - alloc_start);
6937                 } else {
6938                         if (ordered)
6939                                 btrfs_put_ordered_extent(ordered);
6940                         break;
6941                 }
6942         }
6943
6944         cur_offset = alloc_start;
6945         while (1) {
6946                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
6947                                       alloc_end - cur_offset, 0);
6948                 BUG_ON(IS_ERR(em) || !em);
6949                 last_byte = min(extent_map_end(em), alloc_end);
6950                 last_byte = (last_byte + mask) & ~mask;
6951                 if (em->block_start == EXTENT_MAP_HOLE ||
6952                     (cur_offset >= inode->i_size &&
6953                      !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6954                         ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
6955                                                         last_byte - cur_offset,
6956                                                         1 << inode->i_blkbits,
6957                                                         offset + len,
6958                                                         &alloc_hint);
6959                         if (ret < 0) {
6960                                 free_extent_map(em);
6961                                 break;
6962                         }
6963                 }
6964                 free_extent_map(em);
6965
6966                 cur_offset = last_byte;
6967                 if (cur_offset >= alloc_end) {
6968                         ret = 0;
6969                         break;
6970                 }
6971         }
6972         unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
6973                              &cached_state, GFP_NOFS);
6974
6975         btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
6976 out:
6977         mutex_unlock(&inode->i_mutex);
6978         return ret;
6979 }
6980
6981 static int btrfs_set_page_dirty(struct page *page)
6982 {
6983         return __set_page_dirty_nobuffers(page);
6984 }
6985
6986 static int btrfs_permission(struct inode *inode, int mask)
6987 {
6988         if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
6989                 return -EACCES;
6990         return generic_permission(inode, mask, btrfs_check_acl);
6991 }
6992
6993 static const struct inode_operations btrfs_dir_inode_operations = {
6994         .getattr        = btrfs_getattr,
6995         .lookup         = btrfs_lookup,
6996         .create         = btrfs_create,
6997         .unlink         = btrfs_unlink,
6998         .link           = btrfs_link,
6999         .mkdir          = btrfs_mkdir,
7000         .rmdir          = btrfs_rmdir,
7001         .rename         = btrfs_rename,
7002         .symlink        = btrfs_symlink,
7003         .setattr        = btrfs_setattr,
7004         .mknod          = btrfs_mknod,
7005         .setxattr       = btrfs_setxattr,
7006         .getxattr       = btrfs_getxattr,
7007         .listxattr      = btrfs_listxattr,
7008         .removexattr    = btrfs_removexattr,
7009         .permission     = btrfs_permission,
7010 };
7011 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7012         .lookup         = btrfs_lookup,
7013         .permission     = btrfs_permission,
7014 };
7015
7016 static const struct file_operations btrfs_dir_file_operations = {
7017         .llseek         = generic_file_llseek,
7018         .read           = generic_read_dir,
7019         .readdir        = btrfs_real_readdir,
7020         .unlocked_ioctl = btrfs_ioctl,
7021 #ifdef CONFIG_COMPAT
7022         .compat_ioctl   = btrfs_ioctl,
7023 #endif
7024         .release        = btrfs_release_file,
7025         .fsync          = btrfs_sync_file,
7026 };
7027
7028 static struct extent_io_ops btrfs_extent_io_ops = {
7029         .fill_delalloc = run_delalloc_range,
7030         .submit_bio_hook = btrfs_submit_bio_hook,
7031         .merge_bio_hook = btrfs_merge_bio_hook,
7032         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7033         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7034         .writepage_start_hook = btrfs_writepage_start_hook,
7035         .readpage_io_failed_hook = btrfs_io_failed_hook,
7036         .set_bit_hook = btrfs_set_bit_hook,
7037         .clear_bit_hook = btrfs_clear_bit_hook,
7038         .merge_extent_hook = btrfs_merge_extent_hook,
7039         .split_extent_hook = btrfs_split_extent_hook,
7040 };
7041
7042 /*
7043  * btrfs doesn't support the bmap operation because swapfiles
7044  * use bmap to make a mapping of extents in the file.  They assume
7045  * these extents won't change over the life of the file and they
7046  * use the bmap result to do IO directly to the drive.
7047  *
7048  * the btrfs bmap call would return logical addresses that aren't
7049  * suitable for IO and they also will change frequently as COW
7050  * operations happen.  So, swapfile + btrfs == corruption.
7051  *
7052  * For now we're avoiding this by dropping bmap.
7053  */
7054 static const struct address_space_operations btrfs_aops = {
7055         .readpage       = btrfs_readpage,
7056         .writepage      = btrfs_writepage,
7057         .writepages     = btrfs_writepages,
7058         .readpages      = btrfs_readpages,
7059         .sync_page      = block_sync_page,
7060         .direct_IO      = btrfs_direct_IO,
7061         .invalidatepage = btrfs_invalidatepage,
7062         .releasepage    = btrfs_releasepage,
7063         .set_page_dirty = btrfs_set_page_dirty,
7064         .error_remove_page = generic_error_remove_page,
7065 };
7066
7067 static const struct address_space_operations btrfs_symlink_aops = {
7068         .readpage       = btrfs_readpage,
7069         .writepage      = btrfs_writepage,
7070         .invalidatepage = btrfs_invalidatepage,
7071         .releasepage    = btrfs_releasepage,
7072 };
7073
7074 static const struct inode_operations btrfs_file_inode_operations = {
7075         .truncate       = btrfs_truncate,
7076         .getattr        = btrfs_getattr,
7077         .setattr        = btrfs_setattr,
7078         .setxattr       = btrfs_setxattr,
7079         .getxattr       = btrfs_getxattr,
7080         .listxattr      = btrfs_listxattr,
7081         .removexattr    = btrfs_removexattr,
7082         .permission     = btrfs_permission,
7083         .fallocate      = btrfs_fallocate,
7084         .fiemap         = btrfs_fiemap,
7085 };
7086 static const struct inode_operations btrfs_special_inode_operations = {
7087         .getattr        = btrfs_getattr,
7088         .setattr        = btrfs_setattr,
7089         .permission     = btrfs_permission,
7090         .setxattr       = btrfs_setxattr,
7091         .getxattr       = btrfs_getxattr,
7092         .listxattr      = btrfs_listxattr,
7093         .removexattr    = btrfs_removexattr,
7094 };
7095 static const struct inode_operations btrfs_symlink_inode_operations = {
7096         .readlink       = generic_readlink,
7097         .follow_link    = page_follow_link_light,
7098         .put_link       = page_put_link,
7099         .permission     = btrfs_permission,
7100         .setxattr       = btrfs_setxattr,
7101         .getxattr       = btrfs_getxattr,
7102         .listxattr      = btrfs_listxattr,
7103         .removexattr    = btrfs_removexattr,
7104 };
7105
7106 const struct dentry_operations btrfs_dentry_operations = {
7107         .d_delete       = btrfs_dentry_delete,
7108 };