Btrfs: add basic DIO read/write support
[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 {
1390         struct btrfs_root *root = BTRFS_I(inode)->root;
1391         int ret = 0;
1392
1393         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1394         BUG_ON(ret);
1395         return 0;
1396 }
1397
1398 /*
1399  * in order to insert checksums into the metadata in large chunks,
1400  * we wait until bio submission time.   All the pages in the bio are
1401  * checksummed and sums are attached onto the ordered extent record.
1402  *
1403  * At IO completion time the cums attached on the ordered extent record
1404  * are inserted into the btree
1405  */
1406 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1407                           int mirror_num, unsigned long bio_flags)
1408 {
1409         struct btrfs_root *root = BTRFS_I(inode)->root;
1410         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1411 }
1412
1413 /*
1414  * extent_io.c submission hook. This does the right thing for csum calculation
1415  * on write, or reading the csums from the tree before a read
1416  */
1417 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1418                           int mirror_num, unsigned long bio_flags)
1419 {
1420         struct btrfs_root *root = BTRFS_I(inode)->root;
1421         int ret = 0;
1422         int skip_sum;
1423
1424         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1425
1426         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1427         BUG_ON(ret);
1428
1429         if (!(rw & (1 << BIO_RW))) {
1430                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1431                         return btrfs_submit_compressed_read(inode, bio,
1432                                                     mirror_num, bio_flags);
1433                 } else if (!skip_sum)
1434                         btrfs_lookup_bio_sums(root, inode, bio, NULL);
1435                 goto mapit;
1436         } else if (!skip_sum) {
1437                 /* csum items have already been cloned */
1438                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1439                         goto mapit;
1440                 /* we're doing a write, do the async checksumming */
1441                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1442                                    inode, rw, bio, mirror_num,
1443                                    bio_flags, __btrfs_submit_bio_start,
1444                                    __btrfs_submit_bio_done);
1445         }
1446
1447 mapit:
1448         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1449 }
1450
1451 /*
1452  * given a list of ordered sums record them in the inode.  This happens
1453  * at IO completion time based on sums calculated at bio submission time.
1454  */
1455 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1456                              struct inode *inode, u64 file_offset,
1457                              struct list_head *list)
1458 {
1459         struct btrfs_ordered_sum *sum;
1460
1461         btrfs_set_trans_block_group(trans, inode);
1462
1463         list_for_each_entry(sum, list, list) {
1464                 btrfs_csum_file_blocks(trans,
1465                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1466         }
1467         return 0;
1468 }
1469
1470 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1471                               struct extent_state **cached_state)
1472 {
1473         if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1474                 WARN_ON(1);
1475         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1476                                    cached_state, GFP_NOFS);
1477 }
1478
1479 /* see btrfs_writepage_start_hook for details on why this is required */
1480 struct btrfs_writepage_fixup {
1481         struct page *page;
1482         struct btrfs_work work;
1483 };
1484
1485 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1486 {
1487         struct btrfs_writepage_fixup *fixup;
1488         struct btrfs_ordered_extent *ordered;
1489         struct extent_state *cached_state = NULL;
1490         struct page *page;
1491         struct inode *inode;
1492         u64 page_start;
1493         u64 page_end;
1494
1495         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1496         page = fixup->page;
1497 again:
1498         lock_page(page);
1499         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1500                 ClearPageChecked(page);
1501                 goto out_page;
1502         }
1503
1504         inode = page->mapping->host;
1505         page_start = page_offset(page);
1506         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1507
1508         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1509                          &cached_state, GFP_NOFS);
1510
1511         /* already ordered? We're done */
1512         if (PagePrivate2(page))
1513                 goto out;
1514
1515         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1516         if (ordered) {
1517                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1518                                      page_end, &cached_state, GFP_NOFS);
1519                 unlock_page(page);
1520                 btrfs_start_ordered_extent(inode, ordered, 1);
1521                 goto again;
1522         }
1523
1524         BUG();
1525         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1526         ClearPageChecked(page);
1527 out:
1528         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1529                              &cached_state, GFP_NOFS);
1530 out_page:
1531         unlock_page(page);
1532         page_cache_release(page);
1533 }
1534
1535 /*
1536  * There are a few paths in the higher layers of the kernel that directly
1537  * set the page dirty bit without asking the filesystem if it is a
1538  * good idea.  This causes problems because we want to make sure COW
1539  * properly happens and the data=ordered rules are followed.
1540  *
1541  * In our case any range that doesn't have the ORDERED bit set
1542  * hasn't been properly setup for IO.  We kick off an async process
1543  * to fix it up.  The async helper will wait for ordered extents, set
1544  * the delalloc bit and make it safe to write the page.
1545  */
1546 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1547 {
1548         struct inode *inode = page->mapping->host;
1549         struct btrfs_writepage_fixup *fixup;
1550         struct btrfs_root *root = BTRFS_I(inode)->root;
1551
1552         /* this page is properly in the ordered list */
1553         if (TestClearPagePrivate2(page))
1554                 return 0;
1555
1556         if (PageChecked(page))
1557                 return -EAGAIN;
1558
1559         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1560         if (!fixup)
1561                 return -EAGAIN;
1562
1563         SetPageChecked(page);
1564         page_cache_get(page);
1565         fixup->work.func = btrfs_writepage_fixup_worker;
1566         fixup->page = page;
1567         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1568         return -EAGAIN;
1569 }
1570
1571 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1572                                        struct inode *inode, u64 file_pos,
1573                                        u64 disk_bytenr, u64 disk_num_bytes,
1574                                        u64 num_bytes, u64 ram_bytes,
1575                                        u8 compression, u8 encryption,
1576                                        u16 other_encoding, int extent_type)
1577 {
1578         struct btrfs_root *root = BTRFS_I(inode)->root;
1579         struct btrfs_file_extent_item *fi;
1580         struct btrfs_path *path;
1581         struct extent_buffer *leaf;
1582         struct btrfs_key ins;
1583         u64 hint;
1584         int ret;
1585
1586         path = btrfs_alloc_path();
1587         BUG_ON(!path);
1588
1589         path->leave_spinning = 1;
1590
1591         /*
1592          * we may be replacing one extent in the tree with another.
1593          * The new extent is pinned in the extent map, and we don't want
1594          * to drop it from the cache until it is completely in the btree.
1595          *
1596          * So, tell btrfs_drop_extents to leave this extent in the cache.
1597          * the caller is expected to unpin it and allow it to be merged
1598          * with the others.
1599          */
1600         ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1601                                  &hint, 0);
1602         BUG_ON(ret);
1603
1604         ins.objectid = inode->i_ino;
1605         ins.offset = file_pos;
1606         ins.type = BTRFS_EXTENT_DATA_KEY;
1607         ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1608         BUG_ON(ret);
1609         leaf = path->nodes[0];
1610         fi = btrfs_item_ptr(leaf, path->slots[0],
1611                             struct btrfs_file_extent_item);
1612         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1613         btrfs_set_file_extent_type(leaf, fi, extent_type);
1614         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1615         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1616         btrfs_set_file_extent_offset(leaf, fi, 0);
1617         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1618         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1619         btrfs_set_file_extent_compression(leaf, fi, compression);
1620         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1621         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1622
1623         btrfs_unlock_up_safe(path, 1);
1624         btrfs_set_lock_blocking(leaf);
1625
1626         btrfs_mark_buffer_dirty(leaf);
1627
1628         inode_add_bytes(inode, num_bytes);
1629
1630         ins.objectid = disk_bytenr;
1631         ins.offset = disk_num_bytes;
1632         ins.type = BTRFS_EXTENT_ITEM_KEY;
1633         ret = btrfs_alloc_reserved_file_extent(trans, root,
1634                                         root->root_key.objectid,
1635                                         inode->i_ino, file_pos, &ins);
1636         BUG_ON(ret);
1637         btrfs_free_path(path);
1638
1639         return 0;
1640 }
1641
1642 /*
1643  * helper function for btrfs_finish_ordered_io, this
1644  * just reads in some of the csum leaves to prime them into ram
1645  * before we start the transaction.  It limits the amount of btree
1646  * reads required while inside the transaction.
1647  */
1648 /* as ordered data IO finishes, this gets called so we can finish
1649  * an ordered extent if the range of bytes in the file it covers are
1650  * fully written.
1651  */
1652 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1653 {
1654         struct btrfs_root *root = BTRFS_I(inode)->root;
1655         struct btrfs_trans_handle *trans = NULL;
1656         struct btrfs_ordered_extent *ordered_extent = NULL;
1657         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1658         struct extent_state *cached_state = NULL;
1659         int compressed = 0;
1660         int ret;
1661
1662         ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1663                                              end - start + 1);
1664         if (!ret)
1665                 return 0;
1666         BUG_ON(!ordered_extent);
1667
1668         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1669                 BUG_ON(!list_empty(&ordered_extent->list));
1670                 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1671                 if (!ret) {
1672                         trans = btrfs_join_transaction(root, 1);
1673                         btrfs_set_trans_block_group(trans, inode);
1674                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1675                         ret = btrfs_update_inode(trans, root, inode);
1676                         BUG_ON(ret);
1677                 }
1678                 goto out;
1679         }
1680
1681         lock_extent_bits(io_tree, ordered_extent->file_offset,
1682                          ordered_extent->file_offset + ordered_extent->len - 1,
1683                          0, &cached_state, GFP_NOFS);
1684
1685         trans = btrfs_join_transaction(root, 1);
1686         btrfs_set_trans_block_group(trans, inode);
1687         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1688
1689         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1690                 compressed = 1;
1691         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1692                 BUG_ON(compressed);
1693                 ret = btrfs_mark_extent_written(trans, inode,
1694                                                 ordered_extent->file_offset,
1695                                                 ordered_extent->file_offset +
1696                                                 ordered_extent->len);
1697                 BUG_ON(ret);
1698         } else {
1699                 ret = insert_reserved_file_extent(trans, inode,
1700                                                 ordered_extent->file_offset,
1701                                                 ordered_extent->start,
1702                                                 ordered_extent->disk_len,
1703                                                 ordered_extent->len,
1704                                                 ordered_extent->len,
1705                                                 compressed, 0, 0,
1706                                                 BTRFS_FILE_EXTENT_REG);
1707                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1708                                    ordered_extent->file_offset,
1709                                    ordered_extent->len);
1710                 BUG_ON(ret);
1711         }
1712         unlock_extent_cached(io_tree, ordered_extent->file_offset,
1713                              ordered_extent->file_offset +
1714                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
1715
1716         add_pending_csums(trans, inode, ordered_extent->file_offset,
1717                           &ordered_extent->list);
1718
1719         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1720         ret = btrfs_update_inode(trans, root, inode);
1721         BUG_ON(ret);
1722 out:
1723         btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1724         if (trans)
1725                 btrfs_end_transaction(trans, root);
1726         /* once for us */
1727         btrfs_put_ordered_extent(ordered_extent);
1728         /* once for the tree */
1729         btrfs_put_ordered_extent(ordered_extent);
1730
1731         return 0;
1732 }
1733
1734 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1735                                 struct extent_state *state, int uptodate)
1736 {
1737         ClearPagePrivate2(page);
1738         return btrfs_finish_ordered_io(page->mapping->host, start, end);
1739 }
1740
1741 /*
1742  * When IO fails, either with EIO or csum verification fails, we
1743  * try other mirrors that might have a good copy of the data.  This
1744  * io_failure_record is used to record state as we go through all the
1745  * mirrors.  If another mirror has good data, the page is set up to date
1746  * and things continue.  If a good mirror can't be found, the original
1747  * bio end_io callback is called to indicate things have failed.
1748  */
1749 struct io_failure_record {
1750         struct page *page;
1751         u64 start;
1752         u64 len;
1753         u64 logical;
1754         unsigned long bio_flags;
1755         int last_mirror;
1756 };
1757
1758 static int btrfs_io_failed_hook(struct bio *failed_bio,
1759                          struct page *page, u64 start, u64 end,
1760                          struct extent_state *state)
1761 {
1762         struct io_failure_record *failrec = NULL;
1763         u64 private;
1764         struct extent_map *em;
1765         struct inode *inode = page->mapping->host;
1766         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1767         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1768         struct bio *bio;
1769         int num_copies;
1770         int ret;
1771         int rw;
1772         u64 logical;
1773
1774         ret = get_state_private(failure_tree, start, &private);
1775         if (ret) {
1776                 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1777                 if (!failrec)
1778                         return -ENOMEM;
1779                 failrec->start = start;
1780                 failrec->len = end - start + 1;
1781                 failrec->last_mirror = 0;
1782                 failrec->bio_flags = 0;
1783
1784                 read_lock(&em_tree->lock);
1785                 em = lookup_extent_mapping(em_tree, start, failrec->len);
1786                 if (em->start > start || em->start + em->len < start) {
1787                         free_extent_map(em);
1788                         em = NULL;
1789                 }
1790                 read_unlock(&em_tree->lock);
1791
1792                 if (!em || IS_ERR(em)) {
1793                         kfree(failrec);
1794                         return -EIO;
1795                 }
1796                 logical = start - em->start;
1797                 logical = em->block_start + logical;
1798                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1799                         logical = em->block_start;
1800                         failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1801                 }
1802                 failrec->logical = logical;
1803                 free_extent_map(em);
1804                 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1805                                 EXTENT_DIRTY, GFP_NOFS);
1806                 set_state_private(failure_tree, start,
1807                                  (u64)(unsigned long)failrec);
1808         } else {
1809                 failrec = (struct io_failure_record *)(unsigned long)private;
1810         }
1811         num_copies = btrfs_num_copies(
1812                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
1813                               failrec->logical, failrec->len);
1814         failrec->last_mirror++;
1815         if (!state) {
1816                 spin_lock(&BTRFS_I(inode)->io_tree.lock);
1817                 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1818                                                     failrec->start,
1819                                                     EXTENT_LOCKED);
1820                 if (state && state->start != failrec->start)
1821                         state = NULL;
1822                 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1823         }
1824         if (!state || failrec->last_mirror > num_copies) {
1825                 set_state_private(failure_tree, failrec->start, 0);
1826                 clear_extent_bits(failure_tree, failrec->start,
1827                                   failrec->start + failrec->len - 1,
1828                                   EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1829                 kfree(failrec);
1830                 return -EIO;
1831         }
1832         bio = bio_alloc(GFP_NOFS, 1);
1833         bio->bi_private = state;
1834         bio->bi_end_io = failed_bio->bi_end_io;
1835         bio->bi_sector = failrec->logical >> 9;
1836         bio->bi_bdev = failed_bio->bi_bdev;
1837         bio->bi_size = 0;
1838
1839         bio_add_page(bio, page, failrec->len, start - page_offset(page));
1840         if (failed_bio->bi_rw & (1 << BIO_RW))
1841                 rw = WRITE;
1842         else
1843                 rw = READ;
1844
1845         BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1846                                                       failrec->last_mirror,
1847                                                       failrec->bio_flags);
1848         return 0;
1849 }
1850
1851 /*
1852  * each time an IO finishes, we do a fast check in the IO failure tree
1853  * to see if we need to process or clean up an io_failure_record
1854  */
1855 static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1856 {
1857         u64 private;
1858         u64 private_failure;
1859         struct io_failure_record *failure;
1860         int ret;
1861
1862         private = 0;
1863         if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1864                              (u64)-1, 1, EXTENT_DIRTY)) {
1865                 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1866                                         start, &private_failure);
1867                 if (ret == 0) {
1868                         failure = (struct io_failure_record *)(unsigned long)
1869                                    private_failure;
1870                         set_state_private(&BTRFS_I(inode)->io_failure_tree,
1871                                           failure->start, 0);
1872                         clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1873                                           failure->start,
1874                                           failure->start + failure->len - 1,
1875                                           EXTENT_DIRTY | EXTENT_LOCKED,
1876                                           GFP_NOFS);
1877                         kfree(failure);
1878                 }
1879         }
1880         return 0;
1881 }
1882
1883 /*
1884  * when reads are done, we need to check csums to verify the data is correct
1885  * if there's a match, we allow the bio to finish.  If not, we go through
1886  * the io_failure_record routines to find good copies
1887  */
1888 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1889                                struct extent_state *state)
1890 {
1891         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1892         struct inode *inode = page->mapping->host;
1893         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1894         char *kaddr;
1895         u64 private = ~(u32)0;
1896         int ret;
1897         struct btrfs_root *root = BTRFS_I(inode)->root;
1898         u32 csum = ~(u32)0;
1899
1900         if (PageChecked(page)) {
1901                 ClearPageChecked(page);
1902                 goto good;
1903         }
1904
1905         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1906                 return 0;
1907
1908         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1909             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1910                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1911                                   GFP_NOFS);
1912                 return 0;
1913         }
1914
1915         if (state && state->start == start) {
1916                 private = state->private;
1917                 ret = 0;
1918         } else {
1919                 ret = get_state_private(io_tree, start, &private);
1920         }
1921         kaddr = kmap_atomic(page, KM_USER0);
1922         if (ret)
1923                 goto zeroit;
1924
1925         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
1926         btrfs_csum_final(csum, (char *)&csum);
1927         if (csum != private)
1928                 goto zeroit;
1929
1930         kunmap_atomic(kaddr, KM_USER0);
1931 good:
1932         /* if the io failure tree for this inode is non-empty,
1933          * check to see if we've recovered from a failed IO
1934          */
1935         btrfs_clean_io_failures(inode, start);
1936         return 0;
1937
1938 zeroit:
1939         if (printk_ratelimit()) {
1940                 printk(KERN_INFO "btrfs csum failed ino %lu off %llu csum %u "
1941                        "private %llu\n", page->mapping->host->i_ino,
1942                        (unsigned long long)start, csum,
1943                        (unsigned long long)private);
1944         }
1945         memset(kaddr + offset, 1, end - start + 1);
1946         flush_dcache_page(page);
1947         kunmap_atomic(kaddr, KM_USER0);
1948         if (private == 0)
1949                 return 0;
1950         return -EIO;
1951 }
1952
1953 struct delayed_iput {
1954         struct list_head list;
1955         struct inode *inode;
1956 };
1957
1958 void btrfs_add_delayed_iput(struct inode *inode)
1959 {
1960         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1961         struct delayed_iput *delayed;
1962
1963         if (atomic_add_unless(&inode->i_count, -1, 1))
1964                 return;
1965
1966         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
1967         delayed->inode = inode;
1968
1969         spin_lock(&fs_info->delayed_iput_lock);
1970         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
1971         spin_unlock(&fs_info->delayed_iput_lock);
1972 }
1973
1974 void btrfs_run_delayed_iputs(struct btrfs_root *root)
1975 {
1976         LIST_HEAD(list);
1977         struct btrfs_fs_info *fs_info = root->fs_info;
1978         struct delayed_iput *delayed;
1979         int empty;
1980
1981         spin_lock(&fs_info->delayed_iput_lock);
1982         empty = list_empty(&fs_info->delayed_iputs);
1983         spin_unlock(&fs_info->delayed_iput_lock);
1984         if (empty)
1985                 return;
1986
1987         down_read(&root->fs_info->cleanup_work_sem);
1988         spin_lock(&fs_info->delayed_iput_lock);
1989         list_splice_init(&fs_info->delayed_iputs, &list);
1990         spin_unlock(&fs_info->delayed_iput_lock);
1991
1992         while (!list_empty(&list)) {
1993                 delayed = list_entry(list.next, struct delayed_iput, list);
1994                 list_del(&delayed->list);
1995                 iput(delayed->inode);
1996                 kfree(delayed);
1997         }
1998         up_read(&root->fs_info->cleanup_work_sem);
1999 }
2000
2001 /*
2002  * calculate extra metadata reservation when snapshotting a subvolume
2003  * contains orphan files.
2004  */
2005 void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2006                                 struct btrfs_pending_snapshot *pending,
2007                                 u64 *bytes_to_reserve)
2008 {
2009         struct btrfs_root *root;
2010         struct btrfs_block_rsv *block_rsv;
2011         u64 num_bytes;
2012         int index;
2013
2014         root = pending->root;
2015         if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2016                 return;
2017
2018         block_rsv = root->orphan_block_rsv;
2019
2020         /* orphan block reservation for the snapshot */
2021         num_bytes = block_rsv->size;
2022
2023         /*
2024          * after the snapshot is created, COWing tree blocks may use more
2025          * space than it frees. So we should make sure there is enough
2026          * reserved space.
2027          */
2028         index = trans->transid & 0x1;
2029         if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2030                 num_bytes += block_rsv->size -
2031                              (block_rsv->reserved + block_rsv->freed[index]);
2032         }
2033
2034         *bytes_to_reserve += num_bytes;
2035 }
2036
2037 void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2038                                 struct btrfs_pending_snapshot *pending)
2039 {
2040         struct btrfs_root *root = pending->root;
2041         struct btrfs_root *snap = pending->snap;
2042         struct btrfs_block_rsv *block_rsv;
2043         u64 num_bytes;
2044         int index;
2045         int ret;
2046
2047         if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2048                 return;
2049
2050         /* refill source subvolume's orphan block reservation */
2051         block_rsv = root->orphan_block_rsv;
2052         index = trans->transid & 0x1;
2053         if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2054                 num_bytes = block_rsv->size -
2055                             (block_rsv->reserved + block_rsv->freed[index]);
2056                 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2057                                               root->orphan_block_rsv,
2058                                               num_bytes);
2059                 BUG_ON(ret);
2060         }
2061
2062         /* setup orphan block reservation for the snapshot */
2063         block_rsv = btrfs_alloc_block_rsv(snap);
2064         BUG_ON(!block_rsv);
2065
2066         btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2067         snap->orphan_block_rsv = block_rsv;
2068
2069         num_bytes = root->orphan_block_rsv->size;
2070         ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2071                                       block_rsv, num_bytes);
2072         BUG_ON(ret);
2073
2074 #if 0
2075         /* insert orphan item for the snapshot */
2076         WARN_ON(!root->orphan_item_inserted);
2077         ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2078                                        snap->root_key.objectid);
2079         BUG_ON(ret);
2080         snap->orphan_item_inserted = 1;
2081 #endif
2082 }
2083
2084 enum btrfs_orphan_cleanup_state {
2085         ORPHAN_CLEANUP_STARTED  = 1,
2086         ORPHAN_CLEANUP_DONE     = 2,
2087 };
2088
2089 /*
2090  * This is called in transaction commmit time. If there are no orphan
2091  * files in the subvolume, it removes orphan item and frees block_rsv
2092  * structure.
2093  */
2094 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2095                               struct btrfs_root *root)
2096 {
2097         int ret;
2098
2099         if (!list_empty(&root->orphan_list) ||
2100             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2101                 return;
2102
2103         if (root->orphan_item_inserted &&
2104             btrfs_root_refs(&root->root_item) > 0) {
2105                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2106                                             root->root_key.objectid);
2107                 BUG_ON(ret);
2108                 root->orphan_item_inserted = 0;
2109         }
2110
2111         if (root->orphan_block_rsv) {
2112                 WARN_ON(root->orphan_block_rsv->size > 0);
2113                 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2114                 root->orphan_block_rsv = NULL;
2115         }
2116 }
2117
2118 /*
2119  * This creates an orphan entry for the given inode in case something goes
2120  * wrong in the middle of an unlink/truncate.
2121  *
2122  * NOTE: caller of this function should reserve 5 units of metadata for
2123  *       this function.
2124  */
2125 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2126 {
2127         struct btrfs_root *root = BTRFS_I(inode)->root;
2128         struct btrfs_block_rsv *block_rsv = NULL;
2129         int reserve = 0;
2130         int insert = 0;
2131         int ret;
2132
2133         if (!root->orphan_block_rsv) {
2134                 block_rsv = btrfs_alloc_block_rsv(root);
2135                 BUG_ON(!block_rsv);
2136         }
2137
2138         spin_lock(&root->orphan_lock);
2139         if (!root->orphan_block_rsv) {
2140                 root->orphan_block_rsv = block_rsv;
2141         } else if (block_rsv) {
2142                 btrfs_free_block_rsv(root, block_rsv);
2143                 block_rsv = NULL;
2144         }
2145
2146         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2147                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2148 #if 0
2149                 /*
2150                  * For proper ENOSPC handling, we should do orphan
2151                  * cleanup when mounting. But this introduces backward
2152                  * compatibility issue.
2153                  */
2154                 if (!xchg(&root->orphan_item_inserted, 1))
2155                         insert = 2;
2156                 else
2157                         insert = 1;
2158 #endif
2159                 insert = 1;
2160         } else {
2161                 WARN_ON(!BTRFS_I(inode)->orphan_meta_reserved);
2162         }
2163
2164         if (!BTRFS_I(inode)->orphan_meta_reserved) {
2165                 BTRFS_I(inode)->orphan_meta_reserved = 1;
2166                 reserve = 1;
2167         }
2168         spin_unlock(&root->orphan_lock);
2169
2170         if (block_rsv)
2171                 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2172
2173         /* grab metadata reservation from transaction handle */
2174         if (reserve) {
2175                 ret = btrfs_orphan_reserve_metadata(trans, inode);
2176                 BUG_ON(ret);
2177         }
2178
2179         /* insert an orphan item to track this unlinked/truncated file */
2180         if (insert >= 1) {
2181                 ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
2182                 BUG_ON(ret);
2183         }
2184
2185         /* insert an orphan item to track subvolume contains orphan files */
2186         if (insert >= 2) {
2187                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2188                                                root->root_key.objectid);
2189                 BUG_ON(ret);
2190         }
2191         return 0;
2192 }
2193
2194 /*
2195  * We have done the truncate/delete so we can go ahead and remove the orphan
2196  * item for this particular inode.
2197  */
2198 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2199 {
2200         struct btrfs_root *root = BTRFS_I(inode)->root;
2201         int delete_item = 0;
2202         int release_rsv = 0;
2203         int ret = 0;
2204
2205         spin_lock(&root->orphan_lock);
2206         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2207                 list_del_init(&BTRFS_I(inode)->i_orphan);
2208                 delete_item = 1;
2209         }
2210
2211         if (BTRFS_I(inode)->orphan_meta_reserved) {
2212                 BTRFS_I(inode)->orphan_meta_reserved = 0;
2213                 release_rsv = 1;
2214         }
2215         spin_unlock(&root->orphan_lock);
2216
2217         if (trans && delete_item) {
2218                 ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
2219                 BUG_ON(ret);
2220         }
2221
2222         if (release_rsv)
2223                 btrfs_orphan_release_metadata(inode);
2224
2225         return 0;
2226 }
2227
2228 /*
2229  * this cleans up any orphans that may be left on the list from the last use
2230  * of this root.
2231  */
2232 void btrfs_orphan_cleanup(struct btrfs_root *root)
2233 {
2234         struct btrfs_path *path;
2235         struct extent_buffer *leaf;
2236         struct btrfs_item *item;
2237         struct btrfs_key key, found_key;
2238         struct btrfs_trans_handle *trans;
2239         struct inode *inode;
2240         int ret = 0, nr_unlink = 0, nr_truncate = 0;
2241
2242         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2243                 return;
2244
2245         path = btrfs_alloc_path();
2246         BUG_ON(!path);
2247         path->reada = -1;
2248
2249         key.objectid = BTRFS_ORPHAN_OBJECTID;
2250         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2251         key.offset = (u64)-1;
2252
2253         while (1) {
2254                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2255                 if (ret < 0) {
2256                         printk(KERN_ERR "Error searching slot for orphan: %d"
2257                                "\n", ret);
2258                         break;
2259                 }
2260
2261                 /*
2262                  * if ret == 0 means we found what we were searching for, which
2263                  * is weird, but possible, so only screw with path if we didnt
2264                  * find the key and see if we have stuff that matches
2265                  */
2266                 if (ret > 0) {
2267                         if (path->slots[0] == 0)
2268                                 break;
2269                         path->slots[0]--;
2270                 }
2271
2272                 /* pull out the item */
2273                 leaf = path->nodes[0];
2274                 item = btrfs_item_nr(leaf, path->slots[0]);
2275                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2276
2277                 /* make sure the item matches what we want */
2278                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2279                         break;
2280                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2281                         break;
2282
2283                 /* release the path since we're done with it */
2284                 btrfs_release_path(root, path);
2285
2286                 /*
2287                  * this is where we are basically btrfs_lookup, without the
2288                  * crossing root thing.  we store the inode number in the
2289                  * offset of the orphan item.
2290                  */
2291                 found_key.objectid = found_key.offset;
2292                 found_key.type = BTRFS_INODE_ITEM_KEY;
2293                 found_key.offset = 0;
2294                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2295                 BUG_ON(IS_ERR(inode));
2296
2297                 /*
2298                  * add this inode to the orphan list so btrfs_orphan_del does
2299                  * the proper thing when we hit it
2300                  */
2301                 spin_lock(&root->orphan_lock);
2302                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2303                 spin_unlock(&root->orphan_lock);
2304
2305                 /*
2306                  * if this is a bad inode, means we actually succeeded in
2307                  * removing the inode, but not the orphan record, which means
2308                  * we need to manually delete the orphan since iput will just
2309                  * do a destroy_inode
2310                  */
2311                 if (is_bad_inode(inode)) {
2312                         trans = btrfs_start_transaction(root, 0);
2313                         btrfs_orphan_del(trans, inode);
2314                         btrfs_end_transaction(trans, root);
2315                         iput(inode);
2316                         continue;
2317                 }
2318
2319                 /* if we have links, this was a truncate, lets do that */
2320                 if (inode->i_nlink) {
2321                         nr_truncate++;
2322                         btrfs_truncate(inode);
2323                 } else {
2324                         nr_unlink++;
2325                 }
2326
2327                 /* this will do delete_inode and everything for us */
2328                 iput(inode);
2329         }
2330         btrfs_free_path(path);
2331
2332         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2333
2334         if (root->orphan_block_rsv)
2335                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2336                                         (u64)-1);
2337
2338         if (root->orphan_block_rsv || root->orphan_item_inserted) {
2339                 trans = btrfs_join_transaction(root, 1);
2340                 btrfs_end_transaction(trans, root);
2341         }
2342
2343         if (nr_unlink)
2344                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2345         if (nr_truncate)
2346                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2347 }
2348
2349 /*
2350  * very simple check to peek ahead in the leaf looking for xattrs.  If we
2351  * don't find any xattrs, we know there can't be any acls.
2352  *
2353  * slot is the slot the inode is in, objectid is the objectid of the inode
2354  */
2355 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2356                                           int slot, u64 objectid)
2357 {
2358         u32 nritems = btrfs_header_nritems(leaf);
2359         struct btrfs_key found_key;
2360         int scanned = 0;
2361
2362         slot++;
2363         while (slot < nritems) {
2364                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2365
2366                 /* we found a different objectid, there must not be acls */
2367                 if (found_key.objectid != objectid)
2368                         return 0;
2369
2370                 /* we found an xattr, assume we've got an acl */
2371                 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2372                         return 1;
2373
2374                 /*
2375                  * we found a key greater than an xattr key, there can't
2376                  * be any acls later on
2377                  */
2378                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2379                         return 0;
2380
2381                 slot++;
2382                 scanned++;
2383
2384                 /*
2385                  * it goes inode, inode backrefs, xattrs, extents,
2386                  * so if there are a ton of hard links to an inode there can
2387                  * be a lot of backrefs.  Don't waste time searching too hard,
2388                  * this is just an optimization
2389                  */
2390                 if (scanned >= 8)
2391                         break;
2392         }
2393         /* we hit the end of the leaf before we found an xattr or
2394          * something larger than an xattr.  We have to assume the inode
2395          * has acls
2396          */
2397         return 1;
2398 }
2399
2400 /*
2401  * read an inode from the btree into the in-memory inode
2402  */
2403 static void btrfs_read_locked_inode(struct inode *inode)
2404 {
2405         struct btrfs_path *path;
2406         struct extent_buffer *leaf;
2407         struct btrfs_inode_item *inode_item;
2408         struct btrfs_timespec *tspec;
2409         struct btrfs_root *root = BTRFS_I(inode)->root;
2410         struct btrfs_key location;
2411         int maybe_acls;
2412         u64 alloc_group_block;
2413         u32 rdev;
2414         int ret;
2415
2416         path = btrfs_alloc_path();
2417         BUG_ON(!path);
2418         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2419
2420         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2421         if (ret)
2422                 goto make_bad;
2423
2424         leaf = path->nodes[0];
2425         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2426                                     struct btrfs_inode_item);
2427
2428         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2429         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2430         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2431         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2432         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2433
2434         tspec = btrfs_inode_atime(inode_item);
2435         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2436         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2437
2438         tspec = btrfs_inode_mtime(inode_item);
2439         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2440         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2441
2442         tspec = btrfs_inode_ctime(inode_item);
2443         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2444         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2445
2446         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2447         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2448         BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2449         inode->i_generation = BTRFS_I(inode)->generation;
2450         inode->i_rdev = 0;
2451         rdev = btrfs_inode_rdev(leaf, inode_item);
2452
2453         BTRFS_I(inode)->index_cnt = (u64)-1;
2454         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2455
2456         alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
2457
2458         /*
2459          * try to precache a NULL acl entry for files that don't have
2460          * any xattrs or acls
2461          */
2462         maybe_acls = acls_after_inode_item(leaf, path->slots[0], inode->i_ino);
2463         if (!maybe_acls)
2464                 cache_no_acl(inode);
2465
2466         BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2467                                                 alloc_group_block, 0);
2468         btrfs_free_path(path);
2469         inode_item = NULL;
2470
2471         switch (inode->i_mode & S_IFMT) {
2472         case S_IFREG:
2473                 inode->i_mapping->a_ops = &btrfs_aops;
2474                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2475                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2476                 inode->i_fop = &btrfs_file_operations;
2477                 inode->i_op = &btrfs_file_inode_operations;
2478                 break;
2479         case S_IFDIR:
2480                 inode->i_fop = &btrfs_dir_file_operations;
2481                 if (root == root->fs_info->tree_root)
2482                         inode->i_op = &btrfs_dir_ro_inode_operations;
2483                 else
2484                         inode->i_op = &btrfs_dir_inode_operations;
2485                 break;
2486         case S_IFLNK:
2487                 inode->i_op = &btrfs_symlink_inode_operations;
2488                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2489                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2490                 break;
2491         default:
2492                 inode->i_op = &btrfs_special_inode_operations;
2493                 init_special_inode(inode, inode->i_mode, rdev);
2494                 break;
2495         }
2496
2497         btrfs_update_iflags(inode);
2498         return;
2499
2500 make_bad:
2501         btrfs_free_path(path);
2502         make_bad_inode(inode);
2503 }
2504
2505 /*
2506  * given a leaf and an inode, copy the inode fields into the leaf
2507  */
2508 static void fill_inode_item(struct btrfs_trans_handle *trans,
2509                             struct extent_buffer *leaf,
2510                             struct btrfs_inode_item *item,
2511                             struct inode *inode)
2512 {
2513         btrfs_set_inode_uid(leaf, item, inode->i_uid);
2514         btrfs_set_inode_gid(leaf, item, inode->i_gid);
2515         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2516         btrfs_set_inode_mode(leaf, item, inode->i_mode);
2517         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2518
2519         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2520                                inode->i_atime.tv_sec);
2521         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2522                                 inode->i_atime.tv_nsec);
2523
2524         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2525                                inode->i_mtime.tv_sec);
2526         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2527                                 inode->i_mtime.tv_nsec);
2528
2529         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2530                                inode->i_ctime.tv_sec);
2531         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2532                                 inode->i_ctime.tv_nsec);
2533
2534         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2535         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2536         btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2537         btrfs_set_inode_transid(leaf, item, trans->transid);
2538         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2539         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2540         btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
2541 }
2542
2543 /*
2544  * copy everything in the in-memory inode into the btree.
2545  */
2546 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2547                                 struct btrfs_root *root, struct inode *inode)
2548 {
2549         struct btrfs_inode_item *inode_item;
2550         struct btrfs_path *path;
2551         struct extent_buffer *leaf;
2552         int ret;
2553
2554         path = btrfs_alloc_path();
2555         BUG_ON(!path);
2556         path->leave_spinning = 1;
2557         ret = btrfs_lookup_inode(trans, root, path,
2558                                  &BTRFS_I(inode)->location, 1);
2559         if (ret) {
2560                 if (ret > 0)
2561                         ret = -ENOENT;
2562                 goto failed;
2563         }
2564
2565         btrfs_unlock_up_safe(path, 1);
2566         leaf = path->nodes[0];
2567         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2568                                   struct btrfs_inode_item);
2569
2570         fill_inode_item(trans, leaf, inode_item, inode);
2571         btrfs_mark_buffer_dirty(leaf);
2572         btrfs_set_inode_last_trans(trans, inode);
2573         ret = 0;
2574 failed:
2575         btrfs_free_path(path);
2576         return ret;
2577 }
2578
2579
2580 /*
2581  * unlink helper that gets used here in inode.c and in the tree logging
2582  * recovery code.  It remove a link in a directory with a given name, and
2583  * also drops the back refs in the inode to the directory
2584  */
2585 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2586                        struct btrfs_root *root,
2587                        struct inode *dir, struct inode *inode,
2588                        const char *name, int name_len)
2589 {
2590         struct btrfs_path *path;
2591         int ret = 0;
2592         struct extent_buffer *leaf;
2593         struct btrfs_dir_item *di;
2594         struct btrfs_key key;
2595         u64 index;
2596
2597         path = btrfs_alloc_path();
2598         if (!path) {
2599                 ret = -ENOMEM;
2600                 goto err;
2601         }
2602
2603         path->leave_spinning = 1;
2604         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2605                                     name, name_len, -1);
2606         if (IS_ERR(di)) {
2607                 ret = PTR_ERR(di);
2608                 goto err;
2609         }
2610         if (!di) {
2611                 ret = -ENOENT;
2612                 goto err;
2613         }
2614         leaf = path->nodes[0];
2615         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2616         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2617         if (ret)
2618                 goto err;
2619         btrfs_release_path(root, path);
2620
2621         ret = btrfs_del_inode_ref(trans, root, name, name_len,
2622                                   inode->i_ino,
2623                                   dir->i_ino, &index);
2624         if (ret) {
2625                 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2626                        "inode %lu parent %lu\n", name_len, name,
2627                        inode->i_ino, dir->i_ino);
2628                 goto err;
2629         }
2630
2631         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2632                                          index, name, name_len, -1);
2633         if (IS_ERR(di)) {
2634                 ret = PTR_ERR(di);
2635                 goto err;
2636         }
2637         if (!di) {
2638                 ret = -ENOENT;
2639                 goto err;
2640         }
2641         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2642         btrfs_release_path(root, path);
2643
2644         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2645                                          inode, dir->i_ino);
2646         BUG_ON(ret != 0 && ret != -ENOENT);
2647
2648         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2649                                            dir, index);
2650         BUG_ON(ret);
2651 err:
2652         btrfs_free_path(path);
2653         if (ret)
2654                 goto out;
2655
2656         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2657         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2658         btrfs_update_inode(trans, root, dir);
2659         btrfs_drop_nlink(inode);
2660         ret = btrfs_update_inode(trans, root, inode);
2661 out:
2662         return ret;
2663 }
2664
2665 /* helper to check if there is any shared block in the path */
2666 static int check_path_shared(struct btrfs_root *root,
2667                              struct btrfs_path *path)
2668 {
2669         struct extent_buffer *eb;
2670         int level;
2671         int ret;
2672         u64 refs;
2673
2674         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2675                 if (!path->nodes[level])
2676                         break;
2677                 eb = path->nodes[level];
2678                 if (!btrfs_block_can_be_shared(root, eb))
2679                         continue;
2680                 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2681                                                &refs, NULL);
2682                 if (refs > 1)
2683                         return 1;
2684         }
2685         return 0;
2686 }
2687
2688 /*
2689  * helper to start transaction for unlink and rmdir.
2690  *
2691  * unlink and rmdir are special in btrfs, they do not always free space.
2692  * so in enospc case, we should make sure they will free space before
2693  * allowing them to use the global metadata reservation.
2694  */
2695 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2696                                                        struct dentry *dentry)
2697 {
2698         struct btrfs_trans_handle *trans;
2699         struct btrfs_root *root = BTRFS_I(dir)->root;
2700         struct btrfs_path *path;
2701         struct btrfs_inode_ref *ref;
2702         struct btrfs_dir_item *di;
2703         struct inode *inode = dentry->d_inode;
2704         u64 index;
2705         int check_link = 1;
2706         int err = -ENOSPC;
2707         int ret;
2708
2709         trans = btrfs_start_transaction(root, 10);
2710         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2711                 return trans;
2712
2713         if (inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2714                 return ERR_PTR(-ENOSPC);
2715
2716         /* check if there is someone else holds reference */
2717         if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2718                 return ERR_PTR(-ENOSPC);
2719
2720         if (atomic_read(&inode->i_count) > 2)
2721                 return ERR_PTR(-ENOSPC);
2722
2723         if (xchg(&root->fs_info->enospc_unlink, 1))
2724                 return ERR_PTR(-ENOSPC);
2725
2726         path = btrfs_alloc_path();
2727         if (!path) {
2728                 root->fs_info->enospc_unlink = 0;
2729                 return ERR_PTR(-ENOMEM);
2730         }
2731
2732         trans = btrfs_start_transaction(root, 0);
2733         if (IS_ERR(trans)) {
2734                 btrfs_free_path(path);
2735                 root->fs_info->enospc_unlink = 0;
2736                 return trans;
2737         }
2738
2739         path->skip_locking = 1;
2740         path->search_commit_root = 1;
2741
2742         ret = btrfs_lookup_inode(trans, root, path,
2743                                 &BTRFS_I(dir)->location, 0);
2744         if (ret < 0) {
2745                 err = ret;
2746                 goto out;
2747         }
2748         if (ret == 0) {
2749                 if (check_path_shared(root, path))
2750                         goto out;
2751         } else {
2752                 check_link = 0;
2753         }
2754         btrfs_release_path(root, path);
2755
2756         ret = btrfs_lookup_inode(trans, root, path,
2757                                 &BTRFS_I(inode)->location, 0);
2758         if (ret < 0) {
2759                 err = ret;
2760                 goto out;
2761         }
2762         if (ret == 0) {
2763                 if (check_path_shared(root, path))
2764                         goto out;
2765         } else {
2766                 check_link = 0;
2767         }
2768         btrfs_release_path(root, path);
2769
2770         if (ret == 0 && S_ISREG(inode->i_mode)) {
2771                 ret = btrfs_lookup_file_extent(trans, root, path,
2772                                                inode->i_ino, (u64)-1, 0);
2773                 if (ret < 0) {
2774                         err = ret;
2775                         goto out;
2776                 }
2777                 BUG_ON(ret == 0);
2778                 if (check_path_shared(root, path))
2779                         goto out;
2780                 btrfs_release_path(root, path);
2781         }
2782
2783         if (!check_link) {
2784                 err = 0;
2785                 goto out;
2786         }
2787
2788         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2789                                 dentry->d_name.name, dentry->d_name.len, 0);
2790         if (IS_ERR(di)) {
2791                 err = PTR_ERR(di);
2792                 goto out;
2793         }
2794         if (di) {
2795                 if (check_path_shared(root, path))
2796                         goto out;
2797         } else {
2798                 err = 0;
2799                 goto out;
2800         }
2801         btrfs_release_path(root, path);
2802
2803         ref = btrfs_lookup_inode_ref(trans, root, path,
2804                                 dentry->d_name.name, dentry->d_name.len,
2805                                 inode->i_ino, dir->i_ino, 0);
2806         if (IS_ERR(ref)) {
2807                 err = PTR_ERR(ref);
2808                 goto out;
2809         }
2810         BUG_ON(!ref);
2811         if (check_path_shared(root, path))
2812                 goto out;
2813         index = btrfs_inode_ref_index(path->nodes[0], ref);
2814         btrfs_release_path(root, path);
2815
2816         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino, index,
2817                                 dentry->d_name.name, dentry->d_name.len, 0);
2818         if (IS_ERR(di)) {
2819                 err = PTR_ERR(di);
2820                 goto out;
2821         }
2822         BUG_ON(ret == -ENOENT);
2823         if (check_path_shared(root, path))
2824                 goto out;
2825
2826         err = 0;
2827 out:
2828         btrfs_free_path(path);
2829         if (err) {
2830                 btrfs_end_transaction(trans, root);
2831                 root->fs_info->enospc_unlink = 0;
2832                 return ERR_PTR(err);
2833         }
2834
2835         trans->block_rsv = &root->fs_info->global_block_rsv;
2836         return trans;
2837 }
2838
2839 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2840                                struct btrfs_root *root)
2841 {
2842         if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2843                 BUG_ON(!root->fs_info->enospc_unlink);
2844                 root->fs_info->enospc_unlink = 0;
2845         }
2846         btrfs_end_transaction_throttle(trans, root);
2847 }
2848
2849 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2850 {
2851         struct btrfs_root *root = BTRFS_I(dir)->root;
2852         struct btrfs_trans_handle *trans;
2853         struct inode *inode = dentry->d_inode;
2854         int ret;
2855         unsigned long nr = 0;
2856
2857         trans = __unlink_start_trans(dir, dentry);
2858         if (IS_ERR(trans))
2859                 return PTR_ERR(trans);
2860
2861         btrfs_set_trans_block_group(trans, dir);
2862
2863         btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2864
2865         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2866                                  dentry->d_name.name, dentry->d_name.len);
2867         BUG_ON(ret);
2868
2869         if (inode->i_nlink == 0) {
2870                 ret = btrfs_orphan_add(trans, inode);
2871                 BUG_ON(ret);
2872         }
2873
2874         nr = trans->blocks_used;
2875         __unlink_end_trans(trans, root);
2876         btrfs_btree_balance_dirty(root, nr);
2877         return ret;
2878 }
2879
2880 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2881                         struct btrfs_root *root,
2882                         struct inode *dir, u64 objectid,
2883                         const char *name, int name_len)
2884 {
2885         struct btrfs_path *path;
2886         struct extent_buffer *leaf;
2887         struct btrfs_dir_item *di;
2888         struct btrfs_key key;
2889         u64 index;
2890         int ret;
2891
2892         path = btrfs_alloc_path();
2893         if (!path)
2894                 return -ENOMEM;
2895
2896         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2897                                    name, name_len, -1);
2898         BUG_ON(!di || IS_ERR(di));
2899
2900         leaf = path->nodes[0];
2901         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2902         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2903         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2904         BUG_ON(ret);
2905         btrfs_release_path(root, path);
2906
2907         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2908                                  objectid, root->root_key.objectid,
2909                                  dir->i_ino, &index, name, name_len);
2910         if (ret < 0) {
2911                 BUG_ON(ret != -ENOENT);
2912                 di = btrfs_search_dir_index_item(root, path, dir->i_ino,
2913                                                  name, name_len);
2914                 BUG_ON(!di || IS_ERR(di));
2915
2916                 leaf = path->nodes[0];
2917                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2918                 btrfs_release_path(root, path);
2919                 index = key.offset;
2920         }
2921
2922         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2923                                          index, name, name_len, -1);
2924         BUG_ON(!di || IS_ERR(di));
2925
2926         leaf = path->nodes[0];
2927         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2928         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2929         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2930         BUG_ON(ret);
2931         btrfs_release_path(root, path);
2932
2933         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2934         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2935         ret = btrfs_update_inode(trans, root, dir);
2936         BUG_ON(ret);
2937         dir->i_sb->s_dirt = 1;
2938
2939         btrfs_free_path(path);
2940         return 0;
2941 }
2942
2943 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2944 {
2945         struct inode *inode = dentry->d_inode;
2946         int err = 0;
2947         struct btrfs_root *root = BTRFS_I(dir)->root;
2948         struct btrfs_trans_handle *trans;
2949         unsigned long nr = 0;
2950
2951         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
2952             inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
2953                 return -ENOTEMPTY;
2954
2955         trans = __unlink_start_trans(dir, dentry);
2956         if (IS_ERR(trans))
2957                 return PTR_ERR(trans);
2958
2959         btrfs_set_trans_block_group(trans, dir);
2960
2961         if (unlikely(inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
2962                 err = btrfs_unlink_subvol(trans, root, dir,
2963                                           BTRFS_I(inode)->location.objectid,
2964                                           dentry->d_name.name,
2965                                           dentry->d_name.len);
2966                 goto out;
2967         }
2968
2969         err = btrfs_orphan_add(trans, inode);
2970         if (err)
2971                 goto out;
2972
2973         /* now the directory is empty */
2974         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2975                                  dentry->d_name.name, dentry->d_name.len);
2976         if (!err)
2977                 btrfs_i_size_write(inode, 0);
2978 out:
2979         nr = trans->blocks_used;
2980         __unlink_end_trans(trans, root);
2981         btrfs_btree_balance_dirty(root, nr);
2982
2983         return err;
2984 }
2985
2986 #if 0
2987 /*
2988  * when truncating bytes in a file, it is possible to avoid reading
2989  * the leaves that contain only checksum items.  This can be the
2990  * majority of the IO required to delete a large file, but it must
2991  * be done carefully.
2992  *
2993  * The keys in the level just above the leaves are checked to make sure
2994  * the lowest key in a given leaf is a csum key, and starts at an offset
2995  * after the new  size.
2996  *
2997  * Then the key for the next leaf is checked to make sure it also has
2998  * a checksum item for the same file.  If it does, we know our target leaf
2999  * contains only checksum items, and it can be safely freed without reading
3000  * it.
3001  *
3002  * This is just an optimization targeted at large files.  It may do
3003  * nothing.  It will return 0 unless things went badly.
3004  */
3005 static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
3006                                      struct btrfs_root *root,
3007                                      struct btrfs_path *path,
3008                                      struct inode *inode, u64 new_size)
3009 {
3010         struct btrfs_key key;
3011         int ret;
3012         int nritems;
3013         struct btrfs_key found_key;
3014         struct btrfs_key other_key;
3015         struct btrfs_leaf_ref *ref;
3016         u64 leaf_gen;
3017         u64 leaf_start;
3018
3019         path->lowest_level = 1;
3020         key.objectid = inode->i_ino;
3021         key.type = BTRFS_CSUM_ITEM_KEY;
3022         key.offset = new_size;
3023 again:
3024         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3025         if (ret < 0)
3026                 goto out;
3027
3028         if (path->nodes[1] == NULL) {
3029                 ret = 0;
3030                 goto out;
3031         }
3032         ret = 0;
3033         btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
3034         nritems = btrfs_header_nritems(path->nodes[1]);
3035
3036         if (!nritems)
3037                 goto out;
3038
3039         if (path->slots[1] >= nritems)
3040                 goto next_node;
3041
3042         /* did we find a key greater than anything we want to delete? */
3043         if (found_key.objectid > inode->i_ino ||
3044            (found_key.objectid == inode->i_ino && found_key.type > key.type))
3045                 goto out;
3046
3047         /* we check the next key in the node to make sure the leave contains
3048          * only checksum items.  This comparison doesn't work if our
3049          * leaf is the last one in the node
3050          */
3051         if (path->slots[1] + 1 >= nritems) {
3052 next_node:
3053                 /* search forward from the last key in the node, this
3054                  * will bring us into the next node in the tree
3055                  */
3056                 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
3057
3058                 /* unlikely, but we inc below, so check to be safe */
3059                 if (found_key.offset == (u64)-1)
3060                         goto out;
3061
3062                 /* search_forward needs a path with locks held, do the
3063                  * search again for the original key.  It is possible
3064                  * this will race with a balance and return a path that
3065                  * we could modify, but this drop is just an optimization
3066                  * and is allowed to miss some leaves.
3067                  */
3068                 btrfs_release_path(root, path);
3069                 found_key.offset++;
3070
3071                 /* setup a max key for search_forward */
3072                 other_key.offset = (u64)-1;
3073                 other_key.type = key.type;
3074                 other_key.objectid = key.objectid;
3075
3076                 path->keep_locks = 1;
3077                 ret = btrfs_search_forward(root, &found_key, &other_key,
3078                                            path, 0, 0);
3079                 path->keep_locks = 0;
3080                 if (ret || found_key.objectid != key.objectid ||
3081                     found_key.type != key.type) {
3082                         ret = 0;
3083                         goto out;
3084                 }
3085
3086                 key.offset = found_key.offset;
3087                 btrfs_release_path(root, path);
3088                 cond_resched();
3089                 goto again;
3090         }
3091
3092         /* we know there's one more slot after us in the tree,
3093          * read that key so we can verify it is also a checksum item
3094          */
3095         btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
3096
3097         if (found_key.objectid < inode->i_ino)
3098                 goto next_key;
3099
3100         if (found_key.type != key.type || found_key.offset < new_size)
3101                 goto next_key;
3102
3103         /*
3104          * if the key for the next leaf isn't a csum key from this objectid,
3105          * we can't be sure there aren't good items inside this leaf.
3106          * Bail out
3107          */
3108         if (other_key.objectid != inode->i_ino || other_key.type != key.type)
3109                 goto out;
3110
3111         leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
3112         leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
3113         /*
3114          * it is safe to delete this leaf, it contains only
3115          * csum items from this inode at an offset >= new_size
3116          */
3117         ret = btrfs_del_leaf(trans, root, path, leaf_start);
3118         BUG_ON(ret);
3119
3120         if (root->ref_cows && leaf_gen < trans->transid) {
3121                 ref = btrfs_alloc_leaf_ref(root, 0);
3122                 if (ref) {
3123                         ref->root_gen = root->root_key.offset;
3124                         ref->bytenr = leaf_start;
3125                         ref->owner = 0;
3126                         ref->generation = leaf_gen;
3127                         ref->nritems = 0;
3128
3129                         btrfs_sort_leaf_ref(ref);
3130
3131                         ret = btrfs_add_leaf_ref(root, ref, 0);
3132                         WARN_ON(ret);
3133                         btrfs_free_leaf_ref(root, ref);
3134                 } else {
3135                         WARN_ON(1);
3136                 }
3137         }
3138 next_key:
3139         btrfs_release_path(root, path);
3140
3141         if (other_key.objectid == inode->i_ino &&
3142             other_key.type == key.type && other_key.offset > key.offset) {
3143                 key.offset = other_key.offset;
3144                 cond_resched();
3145                 goto again;
3146         }
3147         ret = 0;
3148 out:
3149         /* fixup any changes we've made to the path */
3150         path->lowest_level = 0;
3151         path->keep_locks = 0;
3152         btrfs_release_path(root, path);
3153         return ret;
3154 }
3155
3156 #endif
3157
3158 /*
3159  * this can truncate away extent items, csum items and directory items.
3160  * It starts at a high offset and removes keys until it can't find
3161  * any higher than new_size
3162  *
3163  * csum items that cross the new i_size are truncated to the new size
3164  * as well.
3165  *
3166  * min_type is the minimum key type to truncate down to.  If set to 0, this
3167  * will kill all the items on this inode, including the INODE_ITEM_KEY.
3168  */
3169 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3170                                struct btrfs_root *root,
3171                                struct inode *inode,
3172                                u64 new_size, u32 min_type)
3173 {
3174         struct btrfs_path *path;
3175         struct extent_buffer *leaf;
3176         struct btrfs_file_extent_item *fi;
3177         struct btrfs_key key;
3178         struct btrfs_key found_key;
3179         u64 extent_start = 0;
3180         u64 extent_num_bytes = 0;
3181         u64 extent_offset = 0;
3182         u64 item_end = 0;
3183         u64 mask = root->sectorsize - 1;
3184         u32 found_type = (u8)-1;
3185         int found_extent;
3186         int del_item;
3187         int pending_del_nr = 0;
3188         int pending_del_slot = 0;
3189         int extent_type = -1;
3190         int encoding;
3191         int ret;
3192         int err = 0;
3193
3194         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3195
3196         if (root->ref_cows)
3197                 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3198
3199         path = btrfs_alloc_path();
3200         BUG_ON(!path);
3201         path->reada = -1;
3202
3203         key.objectid = inode->i_ino;
3204         key.offset = (u64)-1;
3205         key.type = (u8)-1;
3206
3207 search_again:
3208         path->leave_spinning = 1;
3209         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3210         if (ret < 0) {
3211                 err = ret;
3212                 goto out;
3213         }
3214
3215         if (ret > 0) {
3216                 /* there are no items in the tree for us to truncate, we're
3217                  * done
3218                  */
3219                 if (path->slots[0] == 0)
3220                         goto out;
3221                 path->slots[0]--;
3222         }
3223
3224         while (1) {
3225                 fi = NULL;
3226                 leaf = path->nodes[0];
3227                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3228                 found_type = btrfs_key_type(&found_key);
3229                 encoding = 0;
3230
3231                 if (found_key.objectid != inode->i_ino)
3232                         break;
3233
3234                 if (found_type < min_type)
3235                         break;
3236
3237                 item_end = found_key.offset;
3238                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3239                         fi = btrfs_item_ptr(leaf, path->slots[0],
3240                                             struct btrfs_file_extent_item);
3241                         extent_type = btrfs_file_extent_type(leaf, fi);
3242                         encoding = btrfs_file_extent_compression(leaf, fi);
3243                         encoding |= btrfs_file_extent_encryption(leaf, fi);
3244                         encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3245
3246                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3247                                 item_end +=
3248                                     btrfs_file_extent_num_bytes(leaf, fi);
3249                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3250                                 item_end += btrfs_file_extent_inline_len(leaf,
3251                                                                          fi);
3252                         }
3253                         item_end--;
3254                 }
3255                 if (found_type > min_type) {
3256                         del_item = 1;
3257                 } else {
3258                         if (item_end < new_size)
3259                                 break;
3260                         if (found_key.offset >= new_size)
3261                                 del_item = 1;
3262                         else
3263                                 del_item = 0;
3264                 }
3265                 found_extent = 0;
3266                 /* FIXME, shrink the extent if the ref count is only 1 */
3267                 if (found_type != BTRFS_EXTENT_DATA_KEY)
3268                         goto delete;
3269
3270                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3271                         u64 num_dec;
3272                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3273                         if (!del_item && !encoding) {
3274                                 u64 orig_num_bytes =
3275                                         btrfs_file_extent_num_bytes(leaf, fi);
3276                                 extent_num_bytes = new_size -
3277                                         found_key.offset + root->sectorsize - 1;
3278                                 extent_num_bytes = extent_num_bytes &
3279                                         ~((u64)root->sectorsize - 1);
3280                                 btrfs_set_file_extent_num_bytes(leaf, fi,
3281                                                          extent_num_bytes);
3282                                 num_dec = (orig_num_bytes -
3283                                            extent_num_bytes);
3284                                 if (root->ref_cows && extent_start != 0)
3285                                         inode_sub_bytes(inode, num_dec);
3286                                 btrfs_mark_buffer_dirty(leaf);
3287                         } else {
3288                                 extent_num_bytes =
3289                                         btrfs_file_extent_disk_num_bytes(leaf,
3290                                                                          fi);
3291                                 extent_offset = found_key.offset -
3292                                         btrfs_file_extent_offset(leaf, fi);
3293
3294                                 /* FIXME blocksize != 4096 */
3295                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3296                                 if (extent_start != 0) {
3297                                         found_extent = 1;
3298                                         if (root->ref_cows)
3299                                                 inode_sub_bytes(inode, num_dec);
3300                                 }
3301                         }
3302                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3303                         /*
3304                          * we can't truncate inline items that have had
3305                          * special encodings
3306                          */
3307                         if (!del_item &&
3308                             btrfs_file_extent_compression(leaf, fi) == 0 &&
3309                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
3310                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3311                                 u32 size = new_size - found_key.offset;
3312
3313                                 if (root->ref_cows) {
3314                                         inode_sub_bytes(inode, item_end + 1 -
3315                                                         new_size);
3316                                 }
3317                                 size =
3318                                     btrfs_file_extent_calc_inline_size(size);
3319                                 ret = btrfs_truncate_item(trans, root, path,
3320                                                           size, 1);
3321                                 BUG_ON(ret);
3322                         } else if (root->ref_cows) {
3323                                 inode_sub_bytes(inode, item_end + 1 -
3324                                                 found_key.offset);
3325                         }
3326                 }
3327 delete:
3328                 if (del_item) {
3329                         if (!pending_del_nr) {
3330                                 /* no pending yet, add ourselves */
3331                                 pending_del_slot = path->slots[0];
3332                                 pending_del_nr = 1;
3333                         } else if (pending_del_nr &&
3334                                    path->slots[0] + 1 == pending_del_slot) {
3335                                 /* hop on the pending chunk */
3336                                 pending_del_nr++;
3337                                 pending_del_slot = path->slots[0];
3338                         } else {
3339                                 BUG();
3340                         }
3341                 } else {
3342                         break;
3343                 }
3344                 if (found_extent && root->ref_cows) {
3345                         btrfs_set_path_blocking(path);
3346                         ret = btrfs_free_extent(trans, root, extent_start,
3347                                                 extent_num_bytes, 0,
3348                                                 btrfs_header_owner(leaf),
3349                                                 inode->i_ino, extent_offset);
3350                         BUG_ON(ret);
3351                 }
3352
3353                 if (found_type == BTRFS_INODE_ITEM_KEY)
3354                         break;
3355
3356                 if (path->slots[0] == 0 ||
3357                     path->slots[0] != pending_del_slot) {
3358                         if (root->ref_cows) {
3359                                 err = -EAGAIN;
3360                                 goto out;
3361                         }
3362                         if (pending_del_nr) {
3363                                 ret = btrfs_del_items(trans, root, path,
3364                                                 pending_del_slot,
3365                                                 pending_del_nr);
3366                                 BUG_ON(ret);
3367                                 pending_del_nr = 0;
3368                         }
3369                         btrfs_release_path(root, path);
3370                         goto search_again;
3371                 } else {
3372                         path->slots[0]--;
3373                 }
3374         }
3375 out:
3376         if (pending_del_nr) {
3377                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3378                                       pending_del_nr);
3379                 BUG_ON(ret);
3380         }
3381         btrfs_free_path(path);
3382         return err;
3383 }
3384
3385 /*
3386  * taken from block_truncate_page, but does cow as it zeros out
3387  * any bytes left in the last page in the file.
3388  */
3389 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3390 {
3391         struct inode *inode = mapping->host;
3392         struct btrfs_root *root = BTRFS_I(inode)->root;
3393         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3394         struct btrfs_ordered_extent *ordered;
3395         struct extent_state *cached_state = NULL;
3396         char *kaddr;
3397         u32 blocksize = root->sectorsize;
3398         pgoff_t index = from >> PAGE_CACHE_SHIFT;
3399         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3400         struct page *page;
3401         int ret = 0;
3402         u64 page_start;
3403         u64 page_end;
3404
3405         if ((offset & (blocksize - 1)) == 0)
3406                 goto out;
3407         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3408         if (ret)
3409                 goto out;
3410
3411         ret = -ENOMEM;
3412 again:
3413         page = grab_cache_page(mapping, index);
3414         if (!page) {
3415                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3416                 goto out;
3417         }
3418
3419         page_start = page_offset(page);
3420         page_end = page_start + PAGE_CACHE_SIZE - 1;
3421
3422         if (!PageUptodate(page)) {
3423                 ret = btrfs_readpage(NULL, page);
3424                 lock_page(page);
3425                 if (page->mapping != mapping) {
3426                         unlock_page(page);
3427                         page_cache_release(page);
3428                         goto again;
3429                 }
3430                 if (!PageUptodate(page)) {
3431                         ret = -EIO;
3432                         goto out_unlock;
3433                 }
3434         }
3435         wait_on_page_writeback(page);
3436
3437         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3438                          GFP_NOFS);
3439         set_page_extent_mapped(page);
3440
3441         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3442         if (ordered) {
3443                 unlock_extent_cached(io_tree, page_start, page_end,
3444                                      &cached_state, GFP_NOFS);
3445                 unlock_page(page);
3446                 page_cache_release(page);
3447                 btrfs_start_ordered_extent(inode, ordered, 1);
3448                 btrfs_put_ordered_extent(ordered);
3449                 goto again;
3450         }
3451
3452         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3453                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3454                           0, 0, &cached_state, GFP_NOFS);
3455
3456         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3457                                         &cached_state);
3458         if (ret) {
3459                 unlock_extent_cached(io_tree, page_start, page_end,
3460                                      &cached_state, GFP_NOFS);
3461                 goto out_unlock;
3462         }
3463
3464         ret = 0;
3465         if (offset != PAGE_CACHE_SIZE) {
3466                 kaddr = kmap(page);
3467                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3468                 flush_dcache_page(page);
3469                 kunmap(page);
3470         }
3471         ClearPageChecked(page);
3472         set_page_dirty(page);
3473         unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3474                              GFP_NOFS);
3475
3476 out_unlock:
3477         if (ret)
3478                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3479         unlock_page(page);
3480         page_cache_release(page);
3481 out:
3482         return ret;
3483 }
3484
3485 int btrfs_cont_expand(struct inode *inode, loff_t size)
3486 {
3487         struct btrfs_trans_handle *trans;
3488         struct btrfs_root *root = BTRFS_I(inode)->root;
3489         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3490         struct extent_map *em = NULL;
3491         struct extent_state *cached_state = NULL;
3492         u64 mask = root->sectorsize - 1;
3493         u64 hole_start = (inode->i_size + mask) & ~mask;
3494         u64 block_end = (size + mask) & ~mask;
3495         u64 last_byte;
3496         u64 cur_offset;
3497         u64 hole_size;
3498         int err = 0;
3499
3500         if (size <= hole_start)
3501                 return 0;
3502
3503         while (1) {
3504                 struct btrfs_ordered_extent *ordered;
3505                 btrfs_wait_ordered_range(inode, hole_start,
3506                                          block_end - hole_start);
3507                 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3508                                  &cached_state, GFP_NOFS);
3509                 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3510                 if (!ordered)
3511                         break;
3512                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3513                                      &cached_state, GFP_NOFS);
3514                 btrfs_put_ordered_extent(ordered);
3515         }
3516
3517         cur_offset = hole_start;
3518         while (1) {
3519                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3520                                 block_end - cur_offset, 0);
3521                 BUG_ON(IS_ERR(em) || !em);
3522                 last_byte = min(extent_map_end(em), block_end);
3523                 last_byte = (last_byte + mask) & ~mask;
3524                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3525                         u64 hint_byte = 0;
3526                         hole_size = last_byte - cur_offset;
3527
3528                         trans = btrfs_start_transaction(root, 2);
3529                         if (IS_ERR(trans)) {
3530                                 err = PTR_ERR(trans);
3531                                 break;
3532                         }
3533                         btrfs_set_trans_block_group(trans, inode);
3534
3535                         err = btrfs_drop_extents(trans, inode, cur_offset,
3536                                                  cur_offset + hole_size,
3537                                                  &hint_byte, 1);
3538                         BUG_ON(err);
3539
3540                         err = btrfs_insert_file_extent(trans, root,
3541                                         inode->i_ino, cur_offset, 0,
3542                                         0, hole_size, 0, hole_size,
3543                                         0, 0, 0);
3544                         BUG_ON(err);
3545
3546                         btrfs_drop_extent_cache(inode, hole_start,
3547                                         last_byte - 1, 0);
3548
3549                         btrfs_end_transaction(trans, root);
3550                 }
3551                 free_extent_map(em);
3552                 em = NULL;
3553                 cur_offset = last_byte;
3554                 if (cur_offset >= block_end)
3555                         break;
3556         }
3557
3558         free_extent_map(em);
3559         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3560                              GFP_NOFS);
3561         return err;
3562 }
3563
3564 static int btrfs_setattr_size(struct inode *inode, struct iattr *attr)
3565 {
3566         struct btrfs_root *root = BTRFS_I(inode)->root;
3567         struct btrfs_trans_handle *trans;
3568         unsigned long nr;
3569         int ret;
3570
3571         if (attr->ia_size == inode->i_size)
3572                 return 0;
3573
3574         if (attr->ia_size > inode->i_size) {
3575                 unsigned long limit;
3576                 limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
3577                 if (attr->ia_size > inode->i_sb->s_maxbytes)
3578                         return -EFBIG;
3579                 if (limit != RLIM_INFINITY && attr->ia_size > limit) {
3580                         send_sig(SIGXFSZ, current, 0);
3581                         return -EFBIG;
3582                 }
3583         }
3584
3585         trans = btrfs_start_transaction(root, 5);
3586         if (IS_ERR(trans))
3587                 return PTR_ERR(trans);
3588
3589         btrfs_set_trans_block_group(trans, inode);
3590
3591         ret = btrfs_orphan_add(trans, inode);
3592         BUG_ON(ret);
3593
3594         nr = trans->blocks_used;
3595         btrfs_end_transaction(trans, root);
3596         btrfs_btree_balance_dirty(root, nr);
3597
3598         if (attr->ia_size > inode->i_size) {
3599                 ret = btrfs_cont_expand(inode, attr->ia_size);
3600                 if (ret) {
3601                         btrfs_truncate(inode);
3602                         return ret;
3603                 }
3604
3605                 i_size_write(inode, attr->ia_size);
3606                 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
3607
3608                 trans = btrfs_start_transaction(root, 0);
3609                 BUG_ON(IS_ERR(trans));
3610                 btrfs_set_trans_block_group(trans, inode);
3611                 trans->block_rsv = root->orphan_block_rsv;
3612                 BUG_ON(!trans->block_rsv);
3613
3614                 ret = btrfs_update_inode(trans, root, inode);
3615                 BUG_ON(ret);
3616                 if (inode->i_nlink > 0) {
3617                         ret = btrfs_orphan_del(trans, inode);
3618                         BUG_ON(ret);
3619                 }
3620                 nr = trans->blocks_used;
3621                 btrfs_end_transaction(trans, root);
3622                 btrfs_btree_balance_dirty(root, nr);
3623                 return 0;
3624         }
3625
3626         /*
3627          * We're truncating a file that used to have good data down to
3628          * zero. Make sure it gets into the ordered flush list so that
3629          * any new writes get down to disk quickly.
3630          */
3631         if (attr->ia_size == 0)
3632                 BTRFS_I(inode)->ordered_data_close = 1;
3633
3634         /* we don't support swapfiles, so vmtruncate shouldn't fail */
3635         ret = vmtruncate(inode, attr->ia_size);
3636         BUG_ON(ret);
3637
3638         return 0;
3639 }
3640
3641 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3642 {
3643         struct inode *inode = dentry->d_inode;
3644         int err;
3645
3646         err = inode_change_ok(inode, attr);
3647         if (err)
3648                 return err;
3649
3650         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3651                 err = btrfs_setattr_size(inode, attr);
3652                 if (err)
3653                         return err;
3654         }
3655         attr->ia_valid &= ~ATTR_SIZE;
3656
3657         if (attr->ia_valid)
3658                 err = inode_setattr(inode, attr);
3659
3660         if (!err && ((attr->ia_valid & ATTR_MODE)))
3661                 err = btrfs_acl_chmod(inode);
3662         return err;
3663 }
3664
3665 void btrfs_delete_inode(struct inode *inode)
3666 {
3667         struct btrfs_trans_handle *trans;
3668         struct btrfs_root *root = BTRFS_I(inode)->root;
3669         unsigned long nr;
3670         int ret;
3671
3672         truncate_inode_pages(&inode->i_data, 0);
3673         if (is_bad_inode(inode)) {
3674                 btrfs_orphan_del(NULL, inode);
3675                 goto no_delete;
3676         }
3677         btrfs_wait_ordered_range(inode, 0, (u64)-1);
3678
3679         if (root->fs_info->log_root_recovering) {
3680                 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3681                 goto no_delete;
3682         }
3683
3684         if (inode->i_nlink > 0) {
3685                 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3686                 goto no_delete;
3687         }
3688
3689         btrfs_i_size_write(inode, 0);
3690
3691         while (1) {
3692                 trans = btrfs_start_transaction(root, 0);
3693                 BUG_ON(IS_ERR(trans));
3694                 btrfs_set_trans_block_group(trans, inode);
3695                 trans->block_rsv = root->orphan_block_rsv;
3696
3697                 ret = btrfs_block_rsv_check(trans, root,
3698                                             root->orphan_block_rsv, 0, 5);
3699                 if (ret) {
3700                         BUG_ON(ret != -EAGAIN);
3701                         ret = btrfs_commit_transaction(trans, root);
3702                         BUG_ON(ret);
3703                         continue;
3704                 }
3705
3706                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3707                 if (ret != -EAGAIN)
3708                         break;
3709
3710                 nr = trans->blocks_used;
3711                 btrfs_end_transaction(trans, root);
3712                 trans = NULL;
3713                 btrfs_btree_balance_dirty(root, nr);
3714
3715         }
3716
3717         if (ret == 0) {
3718                 ret = btrfs_orphan_del(trans, inode);
3719                 BUG_ON(ret);
3720         }
3721
3722         nr = trans->blocks_used;
3723         btrfs_end_transaction(trans, root);
3724         btrfs_btree_balance_dirty(root, nr);
3725 no_delete:
3726         clear_inode(inode);
3727         return;
3728 }
3729
3730 /*
3731  * this returns the key found in the dir entry in the location pointer.
3732  * If no dir entries were found, location->objectid is 0.
3733  */
3734 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3735                                struct btrfs_key *location)
3736 {
3737         const char *name = dentry->d_name.name;
3738         int namelen = dentry->d_name.len;
3739         struct btrfs_dir_item *di;
3740         struct btrfs_path *path;
3741         struct btrfs_root *root = BTRFS_I(dir)->root;
3742         int ret = 0;
3743
3744         path = btrfs_alloc_path();
3745         BUG_ON(!path);
3746
3747         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
3748                                     namelen, 0);
3749         if (IS_ERR(di))
3750                 ret = PTR_ERR(di);
3751
3752         if (!di || IS_ERR(di))
3753                 goto out_err;
3754
3755         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3756 out:
3757         btrfs_free_path(path);
3758         return ret;
3759 out_err:
3760         location->objectid = 0;
3761         goto out;
3762 }
3763
3764 /*
3765  * when we hit a tree root in a directory, the btrfs part of the inode
3766  * needs to be changed to reflect the root directory of the tree root.  This
3767  * is kind of like crossing a mount point.
3768  */
3769 static int fixup_tree_root_location(struct btrfs_root *root,
3770                                     struct inode *dir,
3771                                     struct dentry *dentry,
3772                                     struct btrfs_key *location,
3773                                     struct btrfs_root **sub_root)
3774 {
3775         struct btrfs_path *path;
3776         struct btrfs_root *new_root;
3777         struct btrfs_root_ref *ref;
3778         struct extent_buffer *leaf;
3779         int ret;
3780         int err = 0;
3781
3782         path = btrfs_alloc_path();
3783         if (!path) {
3784                 err = -ENOMEM;
3785                 goto out;
3786         }
3787
3788         err = -ENOENT;
3789         ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3790                                   BTRFS_I(dir)->root->root_key.objectid,
3791                                   location->objectid);
3792         if (ret) {
3793                 if (ret < 0)
3794                         err = ret;
3795                 goto out;
3796         }
3797
3798         leaf = path->nodes[0];
3799         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3800         if (btrfs_root_ref_dirid(leaf, ref) != dir->i_ino ||
3801             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3802                 goto out;
3803
3804         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3805                                    (unsigned long)(ref + 1),
3806                                    dentry->d_name.len);
3807         if (ret)
3808                 goto out;
3809
3810         btrfs_release_path(root->fs_info->tree_root, path);
3811
3812         new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3813         if (IS_ERR(new_root)) {
3814                 err = PTR_ERR(new_root);
3815                 goto out;
3816         }
3817
3818         if (btrfs_root_refs(&new_root->root_item) == 0) {
3819                 err = -ENOENT;
3820                 goto out;
3821         }
3822
3823         *sub_root = new_root;
3824         location->objectid = btrfs_root_dirid(&new_root->root_item);
3825         location->type = BTRFS_INODE_ITEM_KEY;
3826         location->offset = 0;
3827         err = 0;
3828 out:
3829         btrfs_free_path(path);
3830         return err;
3831 }
3832
3833 static void inode_tree_add(struct inode *inode)
3834 {
3835         struct btrfs_root *root = BTRFS_I(inode)->root;
3836         struct btrfs_inode *entry;
3837         struct rb_node **p;
3838         struct rb_node *parent;
3839 again:
3840         p = &root->inode_tree.rb_node;
3841         parent = NULL;
3842
3843         if (hlist_unhashed(&inode->i_hash))
3844                 return;
3845
3846         spin_lock(&root->inode_lock);
3847         while (*p) {
3848                 parent = *p;
3849                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3850
3851                 if (inode->i_ino < entry->vfs_inode.i_ino)
3852                         p = &parent->rb_left;
3853                 else if (inode->i_ino > entry->vfs_inode.i_ino)
3854                         p = &parent->rb_right;
3855                 else {
3856                         WARN_ON(!(entry->vfs_inode.i_state &
3857                                   (I_WILL_FREE | I_FREEING | I_CLEAR)));
3858                         rb_erase(parent, &root->inode_tree);
3859                         RB_CLEAR_NODE(parent);
3860                         spin_unlock(&root->inode_lock);
3861                         goto again;
3862                 }
3863         }
3864         rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3865         rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3866         spin_unlock(&root->inode_lock);
3867 }
3868
3869 static void inode_tree_del(struct inode *inode)
3870 {
3871         struct btrfs_root *root = BTRFS_I(inode)->root;
3872         int empty = 0;
3873
3874         spin_lock(&root->inode_lock);
3875         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3876                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3877                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3878                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3879         }
3880         spin_unlock(&root->inode_lock);
3881
3882         if (empty && btrfs_root_refs(&root->root_item) == 0) {
3883                 synchronize_srcu(&root->fs_info->subvol_srcu);
3884                 spin_lock(&root->inode_lock);
3885                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3886                 spin_unlock(&root->inode_lock);
3887                 if (empty)
3888                         btrfs_add_dead_root(root);
3889         }
3890 }
3891
3892 int btrfs_invalidate_inodes(struct btrfs_root *root)
3893 {
3894         struct rb_node *node;
3895         struct rb_node *prev;
3896         struct btrfs_inode *entry;
3897         struct inode *inode;
3898         u64 objectid = 0;
3899
3900         WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3901
3902         spin_lock(&root->inode_lock);
3903 again:
3904         node = root->inode_tree.rb_node;
3905         prev = NULL;
3906         while (node) {
3907                 prev = node;
3908                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3909
3910                 if (objectid < entry->vfs_inode.i_ino)
3911                         node = node->rb_left;
3912                 else if (objectid > entry->vfs_inode.i_ino)
3913                         node = node->rb_right;
3914                 else
3915                         break;
3916         }
3917         if (!node) {
3918                 while (prev) {
3919                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
3920                         if (objectid <= entry->vfs_inode.i_ino) {
3921                                 node = prev;
3922                                 break;
3923                         }
3924                         prev = rb_next(prev);
3925                 }
3926         }
3927         while (node) {
3928                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3929                 objectid = entry->vfs_inode.i_ino + 1;
3930                 inode = igrab(&entry->vfs_inode);
3931                 if (inode) {
3932                         spin_unlock(&root->inode_lock);
3933                         if (atomic_read(&inode->i_count) > 1)
3934                                 d_prune_aliases(inode);
3935                         /*
3936                          * btrfs_drop_inode will remove it from
3937                          * the inode cache when its usage count
3938                          * hits zero.
3939                          */
3940                         iput(inode);
3941                         cond_resched();
3942                         spin_lock(&root->inode_lock);
3943                         goto again;
3944                 }
3945
3946                 if (cond_resched_lock(&root->inode_lock))
3947                         goto again;
3948
3949                 node = rb_next(node);
3950         }
3951         spin_unlock(&root->inode_lock);
3952         return 0;
3953 }
3954
3955 static int btrfs_init_locked_inode(struct inode *inode, void *p)
3956 {
3957         struct btrfs_iget_args *args = p;
3958         inode->i_ino = args->ino;
3959         BTRFS_I(inode)->root = args->root;
3960         btrfs_set_inode_space_info(args->root, inode);
3961         return 0;
3962 }
3963
3964 static int btrfs_find_actor(struct inode *inode, void *opaque)
3965 {
3966         struct btrfs_iget_args *args = opaque;
3967         return args->ino == inode->i_ino &&
3968                 args->root == BTRFS_I(inode)->root;
3969 }
3970
3971 static struct inode *btrfs_iget_locked(struct super_block *s,
3972                                        u64 objectid,
3973                                        struct btrfs_root *root)
3974 {
3975         struct inode *inode;
3976         struct btrfs_iget_args args;
3977         args.ino = objectid;
3978         args.root = root;
3979
3980         inode = iget5_locked(s, objectid, btrfs_find_actor,
3981                              btrfs_init_locked_inode,
3982                              (void *)&args);
3983         return inode;
3984 }
3985
3986 /* Get an inode object given its location and corresponding root.
3987  * Returns in *is_new if the inode was read from disk
3988  */
3989 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
3990                          struct btrfs_root *root, int *new)
3991 {
3992         struct inode *inode;
3993
3994         inode = btrfs_iget_locked(s, location->objectid, root);
3995         if (!inode)
3996                 return ERR_PTR(-ENOMEM);
3997
3998         if (inode->i_state & I_NEW) {
3999                 BTRFS_I(inode)->root = root;
4000                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4001                 btrfs_read_locked_inode(inode);
4002
4003                 inode_tree_add(inode);
4004                 unlock_new_inode(inode);
4005                 if (new)
4006                         *new = 1;
4007         }
4008
4009         return inode;
4010 }
4011
4012 static struct inode *new_simple_dir(struct super_block *s,
4013                                     struct btrfs_key *key,
4014                                     struct btrfs_root *root)
4015 {
4016         struct inode *inode = new_inode(s);
4017
4018         if (!inode)
4019                 return ERR_PTR(-ENOMEM);
4020
4021         BTRFS_I(inode)->root = root;
4022         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4023         BTRFS_I(inode)->dummy_inode = 1;
4024
4025         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4026         inode->i_op = &simple_dir_inode_operations;
4027         inode->i_fop = &simple_dir_operations;
4028         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4029         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4030
4031         return inode;
4032 }
4033
4034 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4035 {
4036         struct inode *inode;
4037         struct btrfs_root *root = BTRFS_I(dir)->root;
4038         struct btrfs_root *sub_root = root;
4039         struct btrfs_key location;
4040         int index;
4041         int ret;
4042
4043         dentry->d_op = &btrfs_dentry_operations;
4044
4045         if (dentry->d_name.len > BTRFS_NAME_LEN)
4046                 return ERR_PTR(-ENAMETOOLONG);
4047
4048         ret = btrfs_inode_by_name(dir, dentry, &location);
4049
4050         if (ret < 0)
4051                 return ERR_PTR(ret);
4052
4053         if (location.objectid == 0)
4054                 return NULL;
4055
4056         if (location.type == BTRFS_INODE_ITEM_KEY) {
4057                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4058                 return inode;
4059         }
4060
4061         BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4062
4063         index = srcu_read_lock(&root->fs_info->subvol_srcu);
4064         ret = fixup_tree_root_location(root, dir, dentry,
4065                                        &location, &sub_root);
4066         if (ret < 0) {
4067                 if (ret != -ENOENT)
4068                         inode = ERR_PTR(ret);
4069                 else
4070                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
4071         } else {
4072                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4073         }
4074         srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4075
4076         if (root != sub_root) {
4077                 down_read(&root->fs_info->cleanup_work_sem);
4078                 if (!(inode->i_sb->s_flags & MS_RDONLY))
4079                         btrfs_orphan_cleanup(sub_root);
4080                 up_read(&root->fs_info->cleanup_work_sem);
4081         }
4082
4083         return inode;
4084 }
4085
4086 static int btrfs_dentry_delete(struct dentry *dentry)
4087 {
4088         struct btrfs_root *root;
4089
4090         if (!dentry->d_inode && !IS_ROOT(dentry))
4091                 dentry = dentry->d_parent;
4092
4093         if (dentry->d_inode) {
4094                 root = BTRFS_I(dentry->d_inode)->root;
4095                 if (btrfs_root_refs(&root->root_item) == 0)
4096                         return 1;
4097         }
4098         return 0;
4099 }
4100
4101 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4102                                    struct nameidata *nd)
4103 {
4104         struct inode *inode;
4105
4106         inode = btrfs_lookup_dentry(dir, dentry);
4107         if (IS_ERR(inode))
4108                 return ERR_CAST(inode);
4109
4110         return d_splice_alias(inode, dentry);
4111 }
4112
4113 static unsigned char btrfs_filetype_table[] = {
4114         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4115 };
4116
4117 static int btrfs_real_readdir(struct file *filp, void *dirent,
4118                               filldir_t filldir)
4119 {
4120         struct inode *inode = filp->f_dentry->d_inode;
4121         struct btrfs_root *root = BTRFS_I(inode)->root;
4122         struct btrfs_item *item;
4123         struct btrfs_dir_item *di;
4124         struct btrfs_key key;
4125         struct btrfs_key found_key;
4126         struct btrfs_path *path;
4127         int ret;
4128         u32 nritems;
4129         struct extent_buffer *leaf;
4130         int slot;
4131         int advance;
4132         unsigned char d_type;
4133         int over = 0;
4134         u32 di_cur;
4135         u32 di_total;
4136         u32 di_len;
4137         int key_type = BTRFS_DIR_INDEX_KEY;
4138         char tmp_name[32];
4139         char *name_ptr;
4140         int name_len;
4141
4142         /* FIXME, use a real flag for deciding about the key type */
4143         if (root->fs_info->tree_root == root)
4144                 key_type = BTRFS_DIR_ITEM_KEY;
4145
4146         /* special case for "." */
4147         if (filp->f_pos == 0) {
4148                 over = filldir(dirent, ".", 1,
4149                                1, inode->i_ino,
4150                                DT_DIR);
4151                 if (over)
4152                         return 0;
4153                 filp->f_pos = 1;
4154         }
4155         /* special case for .., just use the back ref */
4156         if (filp->f_pos == 1) {
4157                 u64 pino = parent_ino(filp->f_path.dentry);
4158                 over = filldir(dirent, "..", 2,
4159                                2, pino, DT_DIR);
4160                 if (over)
4161                         return 0;
4162                 filp->f_pos = 2;
4163         }
4164         path = btrfs_alloc_path();
4165         path->reada = 2;
4166
4167         btrfs_set_key_type(&key, key_type);
4168         key.offset = filp->f_pos;
4169         key.objectid = inode->i_ino;
4170
4171         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4172         if (ret < 0)
4173                 goto err;
4174         advance = 0;
4175
4176         while (1) {
4177                 leaf = path->nodes[0];
4178                 nritems = btrfs_header_nritems(leaf);
4179                 slot = path->slots[0];
4180                 if (advance || slot >= nritems) {
4181                         if (slot >= nritems - 1) {
4182                                 ret = btrfs_next_leaf(root, path);
4183                                 if (ret)
4184                                         break;
4185                                 leaf = path->nodes[0];
4186                                 nritems = btrfs_header_nritems(leaf);
4187                                 slot = path->slots[0];
4188                         } else {
4189                                 slot++;
4190                                 path->slots[0]++;
4191                         }
4192                 }
4193
4194                 advance = 1;
4195                 item = btrfs_item_nr(leaf, slot);
4196                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4197
4198                 if (found_key.objectid != key.objectid)
4199                         break;
4200                 if (btrfs_key_type(&found_key) != key_type)
4201                         break;
4202                 if (found_key.offset < filp->f_pos)
4203                         continue;
4204
4205                 filp->f_pos = found_key.offset;
4206
4207                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4208                 di_cur = 0;
4209                 di_total = btrfs_item_size(leaf, item);
4210
4211                 while (di_cur < di_total) {
4212                         struct btrfs_key location;
4213
4214                         name_len = btrfs_dir_name_len(leaf, di);
4215                         if (name_len <= sizeof(tmp_name)) {
4216                                 name_ptr = tmp_name;
4217                         } else {
4218                                 name_ptr = kmalloc(name_len, GFP_NOFS);
4219                                 if (!name_ptr) {
4220                                         ret = -ENOMEM;
4221                                         goto err;
4222                                 }
4223                         }
4224                         read_extent_buffer(leaf, name_ptr,
4225                                            (unsigned long)(di + 1), name_len);
4226
4227                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4228                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
4229
4230                         /* is this a reference to our own snapshot? If so
4231                          * skip it
4232                          */
4233                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
4234                             location.objectid == root->root_key.objectid) {
4235                                 over = 0;
4236                                 goto skip;
4237                         }
4238                         over = filldir(dirent, name_ptr, name_len,
4239                                        found_key.offset, location.objectid,
4240                                        d_type);
4241
4242 skip:
4243                         if (name_ptr != tmp_name)
4244                                 kfree(name_ptr);
4245
4246                         if (over)
4247                                 goto nopos;
4248                         di_len = btrfs_dir_name_len(leaf, di) +
4249                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
4250                         di_cur += di_len;
4251                         di = (struct btrfs_dir_item *)((char *)di + di_len);
4252                 }
4253         }
4254
4255         /* Reached end of directory/root. Bump pos past the last item. */
4256         if (key_type == BTRFS_DIR_INDEX_KEY)
4257                 /*
4258                  * 32-bit glibc will use getdents64, but then strtol -
4259                  * so the last number we can serve is this.
4260                  */
4261                 filp->f_pos = 0x7fffffff;
4262         else
4263                 filp->f_pos++;
4264 nopos:
4265         ret = 0;
4266 err:
4267         btrfs_free_path(path);
4268         return ret;
4269 }
4270
4271 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4272 {
4273         struct btrfs_root *root = BTRFS_I(inode)->root;
4274         struct btrfs_trans_handle *trans;
4275         int ret = 0;
4276
4277         if (BTRFS_I(inode)->dummy_inode)
4278                 return 0;
4279
4280         if (wbc->sync_mode == WB_SYNC_ALL) {
4281                 trans = btrfs_join_transaction(root, 1);
4282                 btrfs_set_trans_block_group(trans, inode);
4283                 ret = btrfs_commit_transaction(trans, root);
4284         }
4285         return ret;
4286 }
4287
4288 /*
4289  * This is somewhat expensive, updating the tree every time the
4290  * inode changes.  But, it is most likely to find the inode in cache.
4291  * FIXME, needs more benchmarking...there are no reasons other than performance
4292  * to keep or drop this code.
4293  */
4294 void btrfs_dirty_inode(struct inode *inode)
4295 {
4296         struct btrfs_root *root = BTRFS_I(inode)->root;
4297         struct btrfs_trans_handle *trans;
4298         int ret;
4299
4300         if (BTRFS_I(inode)->dummy_inode)
4301                 return;
4302
4303         trans = btrfs_join_transaction(root, 1);
4304         btrfs_set_trans_block_group(trans, inode);
4305
4306         ret = btrfs_update_inode(trans, root, inode);
4307         if (ret)
4308                 printk(KERN_ERR"btrfs: fail to dirty inode %lu error %d\n",
4309                         inode->i_ino, ret);
4310
4311         btrfs_end_transaction(trans, root);
4312 }
4313
4314 /*
4315  * find the highest existing sequence number in a directory
4316  * and then set the in-memory index_cnt variable to reflect
4317  * free sequence numbers
4318  */
4319 static int btrfs_set_inode_index_count(struct inode *inode)
4320 {
4321         struct btrfs_root *root = BTRFS_I(inode)->root;
4322         struct btrfs_key key, found_key;
4323         struct btrfs_path *path;
4324         struct extent_buffer *leaf;
4325         int ret;
4326
4327         key.objectid = inode->i_ino;
4328         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4329         key.offset = (u64)-1;
4330
4331         path = btrfs_alloc_path();
4332         if (!path)
4333                 return -ENOMEM;
4334
4335         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4336         if (ret < 0)
4337                 goto out;
4338         /* FIXME: we should be able to handle this */
4339         if (ret == 0)
4340                 goto out;
4341         ret = 0;
4342
4343         /*
4344          * MAGIC NUMBER EXPLANATION:
4345          * since we search a directory based on f_pos we have to start at 2
4346          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4347          * else has to start at 2
4348          */
4349         if (path->slots[0] == 0) {
4350                 BTRFS_I(inode)->index_cnt = 2;
4351                 goto out;
4352         }
4353
4354         path->slots[0]--;
4355
4356         leaf = path->nodes[0];
4357         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4358
4359         if (found_key.objectid != inode->i_ino ||
4360             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4361                 BTRFS_I(inode)->index_cnt = 2;
4362                 goto out;
4363         }
4364
4365         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4366 out:
4367         btrfs_free_path(path);
4368         return ret;
4369 }
4370
4371 /*
4372  * helper to find a free sequence number in a given directory.  This current
4373  * code is very simple, later versions will do smarter things in the btree
4374  */
4375 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4376 {
4377         int ret = 0;
4378
4379         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4380                 ret = btrfs_set_inode_index_count(dir);
4381                 if (ret)
4382                         return ret;
4383         }
4384
4385         *index = BTRFS_I(dir)->index_cnt;
4386         BTRFS_I(dir)->index_cnt++;
4387
4388         return ret;
4389 }
4390
4391 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4392                                      struct btrfs_root *root,
4393                                      struct inode *dir,
4394                                      const char *name, int name_len,
4395                                      u64 ref_objectid, u64 objectid,
4396                                      u64 alloc_hint, int mode, u64 *index)
4397 {
4398         struct inode *inode;
4399         struct btrfs_inode_item *inode_item;
4400         struct btrfs_key *location;
4401         struct btrfs_path *path;
4402         struct btrfs_inode_ref *ref;
4403         struct btrfs_key key[2];
4404         u32 sizes[2];
4405         unsigned long ptr;
4406         int ret;
4407         int owner;
4408
4409         path = btrfs_alloc_path();
4410         BUG_ON(!path);
4411
4412         inode = new_inode(root->fs_info->sb);
4413         if (!inode)
4414                 return ERR_PTR(-ENOMEM);
4415
4416         if (dir) {
4417                 ret = btrfs_set_inode_index(dir, index);
4418                 if (ret) {
4419                         iput(inode);
4420                         return ERR_PTR(ret);
4421                 }
4422         }
4423         /*
4424          * index_cnt is ignored for everything but a dir,
4425          * btrfs_get_inode_index_count has an explanation for the magic
4426          * number
4427          */
4428         BTRFS_I(inode)->index_cnt = 2;
4429         BTRFS_I(inode)->root = root;
4430         BTRFS_I(inode)->generation = trans->transid;
4431         btrfs_set_inode_space_info(root, inode);
4432
4433         if (mode & S_IFDIR)
4434                 owner = 0;
4435         else
4436                 owner = 1;
4437         BTRFS_I(inode)->block_group =
4438                         btrfs_find_block_group(root, 0, alloc_hint, owner);
4439
4440         key[0].objectid = objectid;
4441         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4442         key[0].offset = 0;
4443
4444         key[1].objectid = objectid;
4445         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4446         key[1].offset = ref_objectid;
4447
4448         sizes[0] = sizeof(struct btrfs_inode_item);
4449         sizes[1] = name_len + sizeof(*ref);
4450
4451         path->leave_spinning = 1;
4452         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4453         if (ret != 0)
4454                 goto fail;
4455
4456         inode->i_uid = current_fsuid();
4457
4458         if (dir && (dir->i_mode & S_ISGID)) {
4459                 inode->i_gid = dir->i_gid;
4460                 if (S_ISDIR(mode))
4461                         mode |= S_ISGID;
4462         } else
4463                 inode->i_gid = current_fsgid();
4464
4465         inode->i_mode = mode;
4466         inode->i_ino = objectid;
4467         inode_set_bytes(inode, 0);
4468         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4469         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4470                                   struct btrfs_inode_item);
4471         fill_inode_item(trans, path->nodes[0], inode_item, inode);
4472
4473         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4474                              struct btrfs_inode_ref);
4475         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4476         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4477         ptr = (unsigned long)(ref + 1);
4478         write_extent_buffer(path->nodes[0], name, ptr, name_len);
4479
4480         btrfs_mark_buffer_dirty(path->nodes[0]);
4481         btrfs_free_path(path);
4482
4483         location = &BTRFS_I(inode)->location;
4484         location->objectid = objectid;
4485         location->offset = 0;
4486         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4487
4488         btrfs_inherit_iflags(inode, dir);
4489
4490         if ((mode & S_IFREG)) {
4491                 if (btrfs_test_opt(root, NODATASUM))
4492                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4493                 if (btrfs_test_opt(root, NODATACOW))
4494                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4495         }
4496
4497         insert_inode_hash(inode);
4498         inode_tree_add(inode);
4499         return inode;
4500 fail:
4501         if (dir)
4502                 BTRFS_I(dir)->index_cnt--;
4503         btrfs_free_path(path);
4504         iput(inode);
4505         return ERR_PTR(ret);
4506 }
4507
4508 static inline u8 btrfs_inode_type(struct inode *inode)
4509 {
4510         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4511 }
4512
4513 /*
4514  * utility function to add 'inode' into 'parent_inode' with
4515  * a give name and a given sequence number.
4516  * if 'add_backref' is true, also insert a backref from the
4517  * inode to the parent directory.
4518  */
4519 int btrfs_add_link(struct btrfs_trans_handle *trans,
4520                    struct inode *parent_inode, struct inode *inode,
4521                    const char *name, int name_len, int add_backref, u64 index)
4522 {
4523         int ret = 0;
4524         struct btrfs_key key;
4525         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4526
4527         if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4528                 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4529         } else {
4530                 key.objectid = inode->i_ino;
4531                 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4532                 key.offset = 0;
4533         }
4534
4535         if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4536                 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4537                                          key.objectid, root->root_key.objectid,
4538                                          parent_inode->i_ino,
4539                                          index, name, name_len);
4540         } else if (add_backref) {
4541                 ret = btrfs_insert_inode_ref(trans, root,
4542                                              name, name_len, inode->i_ino,
4543                                              parent_inode->i_ino, index);
4544         }
4545
4546         if (ret == 0) {
4547                 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4548                                             parent_inode->i_ino, &key,
4549                                             btrfs_inode_type(inode), index);
4550                 BUG_ON(ret);
4551
4552                 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4553                                    name_len * 2);
4554                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4555                 ret = btrfs_update_inode(trans, root, parent_inode);
4556         }
4557         return ret;
4558 }
4559
4560 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4561                             struct dentry *dentry, struct inode *inode,
4562                             int backref, u64 index)
4563 {
4564         int err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4565                                  inode, dentry->d_name.name,
4566                                  dentry->d_name.len, backref, index);
4567         if (!err) {
4568                 d_instantiate(dentry, inode);
4569                 return 0;
4570         }
4571         if (err > 0)
4572                 err = -EEXIST;
4573         return err;
4574 }
4575
4576 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4577                         int mode, dev_t rdev)
4578 {
4579         struct btrfs_trans_handle *trans;
4580         struct btrfs_root *root = BTRFS_I(dir)->root;
4581         struct inode *inode = NULL;
4582         int err;
4583         int drop_inode = 0;
4584         u64 objectid;
4585         unsigned long nr = 0;
4586         u64 index = 0;
4587
4588         if (!new_valid_dev(rdev))
4589                 return -EINVAL;
4590
4591         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4592         if (err)
4593                 return err;
4594
4595         /*
4596          * 2 for inode item and ref
4597          * 2 for dir items
4598          * 1 for xattr if selinux is on
4599          */
4600         trans = btrfs_start_transaction(root, 5);
4601         if (IS_ERR(trans))
4602                 return PTR_ERR(trans);
4603
4604         btrfs_set_trans_block_group(trans, dir);
4605
4606         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4607                                 dentry->d_name.len,
4608                                 dentry->d_parent->d_inode->i_ino, objectid,
4609                                 BTRFS_I(dir)->block_group, mode, &index);
4610         err = PTR_ERR(inode);
4611         if (IS_ERR(inode))
4612                 goto out_unlock;
4613
4614         err = btrfs_init_inode_security(trans, inode, dir);
4615         if (err) {
4616                 drop_inode = 1;
4617                 goto out_unlock;
4618         }
4619
4620         btrfs_set_trans_block_group(trans, inode);
4621         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4622         if (err)
4623                 drop_inode = 1;
4624         else {
4625                 inode->i_op = &btrfs_special_inode_operations;
4626                 init_special_inode(inode, inode->i_mode, rdev);
4627                 btrfs_update_inode(trans, root, inode);
4628         }
4629         btrfs_update_inode_block_group(trans, inode);
4630         btrfs_update_inode_block_group(trans, dir);
4631 out_unlock:
4632         nr = trans->blocks_used;
4633         btrfs_end_transaction_throttle(trans, root);
4634         btrfs_btree_balance_dirty(root, nr);
4635         if (drop_inode) {
4636                 inode_dec_link_count(inode);
4637                 iput(inode);
4638         }
4639         return err;
4640 }
4641
4642 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4643                         int mode, struct nameidata *nd)
4644 {
4645         struct btrfs_trans_handle *trans;
4646         struct btrfs_root *root = BTRFS_I(dir)->root;
4647         struct inode *inode = NULL;
4648         int drop_inode = 0;
4649         int err;
4650         unsigned long nr = 0;
4651         u64 objectid;
4652         u64 index = 0;
4653
4654         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4655         if (err)
4656                 return err;
4657         /*
4658          * 2 for inode item and ref
4659          * 2 for dir items
4660          * 1 for xattr if selinux is on
4661          */
4662         trans = btrfs_start_transaction(root, 5);
4663         if (IS_ERR(trans))
4664                 return PTR_ERR(trans);
4665
4666         btrfs_set_trans_block_group(trans, dir);
4667
4668         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4669                                 dentry->d_name.len,
4670                                 dentry->d_parent->d_inode->i_ino,
4671                                 objectid, BTRFS_I(dir)->block_group, mode,
4672                                 &index);
4673         err = PTR_ERR(inode);
4674         if (IS_ERR(inode))
4675                 goto out_unlock;
4676
4677         err = btrfs_init_inode_security(trans, inode, dir);
4678         if (err) {
4679                 drop_inode = 1;
4680                 goto out_unlock;
4681         }
4682
4683         btrfs_set_trans_block_group(trans, inode);
4684         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4685         if (err)
4686                 drop_inode = 1;
4687         else {
4688                 inode->i_mapping->a_ops = &btrfs_aops;
4689                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4690                 inode->i_fop = &btrfs_file_operations;
4691                 inode->i_op = &btrfs_file_inode_operations;
4692                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4693         }
4694         btrfs_update_inode_block_group(trans, inode);
4695         btrfs_update_inode_block_group(trans, dir);
4696 out_unlock:
4697         nr = trans->blocks_used;
4698         btrfs_end_transaction_throttle(trans, root);
4699         if (drop_inode) {
4700                 inode_dec_link_count(inode);
4701                 iput(inode);
4702         }
4703         btrfs_btree_balance_dirty(root, nr);
4704         return err;
4705 }
4706
4707 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4708                       struct dentry *dentry)
4709 {
4710         struct btrfs_trans_handle *trans;
4711         struct btrfs_root *root = BTRFS_I(dir)->root;
4712         struct inode *inode = old_dentry->d_inode;
4713         u64 index;
4714         unsigned long nr = 0;
4715         int err;
4716         int drop_inode = 0;
4717
4718         if (inode->i_nlink == 0)
4719                 return -ENOENT;
4720
4721         /* do not allow sys_link's with other subvols of the same device */
4722         if (root->objectid != BTRFS_I(inode)->root->objectid)
4723                 return -EPERM;
4724
4725         btrfs_inc_nlink(inode);
4726
4727         err = btrfs_set_inode_index(dir, &index);
4728         if (err)
4729                 goto fail;
4730
4731         /*
4732          * 1 item for inode ref
4733          * 2 items for dir items
4734          */
4735         trans = btrfs_start_transaction(root, 3);
4736         if (IS_ERR(trans)) {
4737                 err = PTR_ERR(trans);
4738                 goto fail;
4739         }
4740
4741         btrfs_set_trans_block_group(trans, dir);
4742         atomic_inc(&inode->i_count);
4743
4744         err = btrfs_add_nondir(trans, dentry, inode, 1, index);
4745
4746         if (err) {
4747                 drop_inode = 1;
4748         } else {
4749                 btrfs_update_inode_block_group(trans, dir);
4750                 err = btrfs_update_inode(trans, root, inode);
4751                 BUG_ON(err);
4752                 btrfs_log_new_name(trans, inode, NULL, dentry->d_parent);
4753         }
4754
4755         nr = trans->blocks_used;
4756         btrfs_end_transaction_throttle(trans, root);
4757 fail:
4758         if (drop_inode) {
4759                 inode_dec_link_count(inode);
4760                 iput(inode);
4761         }
4762         btrfs_btree_balance_dirty(root, nr);
4763         return err;
4764 }
4765
4766 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4767 {
4768         struct inode *inode = NULL;
4769         struct btrfs_trans_handle *trans;
4770         struct btrfs_root *root = BTRFS_I(dir)->root;
4771         int err = 0;
4772         int drop_on_err = 0;
4773         u64 objectid = 0;
4774         u64 index = 0;
4775         unsigned long nr = 1;
4776
4777         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4778         if (err)
4779                 return err;
4780
4781         /*
4782          * 2 items for inode and ref
4783          * 2 items for dir items
4784          * 1 for xattr if selinux is on
4785          */
4786         trans = btrfs_start_transaction(root, 5);
4787         if (IS_ERR(trans))
4788                 return PTR_ERR(trans);
4789         btrfs_set_trans_block_group(trans, dir);
4790
4791         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4792                                 dentry->d_name.len,
4793                                 dentry->d_parent->d_inode->i_ino, objectid,
4794                                 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4795                                 &index);
4796         if (IS_ERR(inode)) {
4797                 err = PTR_ERR(inode);
4798                 goto out_fail;
4799         }
4800
4801         drop_on_err = 1;
4802
4803         err = btrfs_init_inode_security(trans, inode, dir);
4804         if (err)
4805                 goto out_fail;
4806
4807         inode->i_op = &btrfs_dir_inode_operations;
4808         inode->i_fop = &btrfs_dir_file_operations;
4809         btrfs_set_trans_block_group(trans, inode);
4810
4811         btrfs_i_size_write(inode, 0);
4812         err = btrfs_update_inode(trans, root, inode);
4813         if (err)
4814                 goto out_fail;
4815
4816         err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4817                                  inode, dentry->d_name.name,
4818                                  dentry->d_name.len, 0, index);
4819         if (err)
4820                 goto out_fail;
4821
4822         d_instantiate(dentry, inode);
4823         drop_on_err = 0;
4824         btrfs_update_inode_block_group(trans, inode);
4825         btrfs_update_inode_block_group(trans, dir);
4826
4827 out_fail:
4828         nr = trans->blocks_used;
4829         btrfs_end_transaction_throttle(trans, root);
4830         if (drop_on_err)
4831                 iput(inode);
4832         btrfs_btree_balance_dirty(root, nr);
4833         return err;
4834 }
4835
4836 /* helper for btfs_get_extent.  Given an existing extent in the tree,
4837  * and an extent that you want to insert, deal with overlap and insert
4838  * the new extent into the tree.
4839  */
4840 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4841                                 struct extent_map *existing,
4842                                 struct extent_map *em,
4843                                 u64 map_start, u64 map_len)
4844 {
4845         u64 start_diff;
4846
4847         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4848         start_diff = map_start - em->start;
4849         em->start = map_start;
4850         em->len = map_len;
4851         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4852             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4853                 em->block_start += start_diff;
4854                 em->block_len -= start_diff;
4855         }
4856         return add_extent_mapping(em_tree, em);
4857 }
4858
4859 static noinline int uncompress_inline(struct btrfs_path *path,
4860                                       struct inode *inode, struct page *page,
4861                                       size_t pg_offset, u64 extent_offset,
4862                                       struct btrfs_file_extent_item *item)
4863 {
4864         int ret;
4865         struct extent_buffer *leaf = path->nodes[0];
4866         char *tmp;
4867         size_t max_size;
4868         unsigned long inline_size;
4869         unsigned long ptr;
4870
4871         WARN_ON(pg_offset != 0);
4872         max_size = btrfs_file_extent_ram_bytes(leaf, item);
4873         inline_size = btrfs_file_extent_inline_item_len(leaf,
4874                                         btrfs_item_nr(leaf, path->slots[0]));
4875         tmp = kmalloc(inline_size, GFP_NOFS);
4876         ptr = btrfs_file_extent_inline_start(item);
4877
4878         read_extent_buffer(leaf, tmp, ptr, inline_size);
4879
4880         max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4881         ret = btrfs_zlib_decompress(tmp, page, extent_offset,
4882                                     inline_size, max_size);
4883         if (ret) {
4884                 char *kaddr = kmap_atomic(page, KM_USER0);
4885                 unsigned long copy_size = min_t(u64,
4886                                   PAGE_CACHE_SIZE - pg_offset,
4887                                   max_size - extent_offset);
4888                 memset(kaddr + pg_offset, 0, copy_size);
4889                 kunmap_atomic(kaddr, KM_USER0);
4890         }
4891         kfree(tmp);
4892         return 0;
4893 }
4894
4895 /*
4896  * a bit scary, this does extent mapping from logical file offset to the disk.
4897  * the ugly parts come from merging extents from the disk with the in-ram
4898  * representation.  This gets more complex because of the data=ordered code,
4899  * where the in-ram extents might be locked pending data=ordered completion.
4900  *
4901  * This also copies inline extents directly into the page.
4902  */
4903
4904 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4905                                     size_t pg_offset, u64 start, u64 len,
4906                                     int create)
4907 {
4908         int ret;
4909         int err = 0;
4910         u64 bytenr;
4911         u64 extent_start = 0;
4912         u64 extent_end = 0;
4913         u64 objectid = inode->i_ino;
4914         u32 found_type;
4915         struct btrfs_path *path = NULL;
4916         struct btrfs_root *root = BTRFS_I(inode)->root;
4917         struct btrfs_file_extent_item *item;
4918         struct extent_buffer *leaf;
4919         struct btrfs_key found_key;
4920         struct extent_map *em = NULL;
4921         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4922         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4923         struct btrfs_trans_handle *trans = NULL;
4924         int compressed;
4925
4926 again:
4927         read_lock(&em_tree->lock);
4928         em = lookup_extent_mapping(em_tree, start, len);
4929         if (em)
4930                 em->bdev = root->fs_info->fs_devices->latest_bdev;
4931         read_unlock(&em_tree->lock);
4932
4933         if (em) {
4934                 if (em->start > start || em->start + em->len <= start)
4935                         free_extent_map(em);
4936                 else if (em->block_start == EXTENT_MAP_INLINE && page)
4937                         free_extent_map(em);
4938                 else
4939                         goto out;
4940         }
4941         em = alloc_extent_map(GFP_NOFS);
4942         if (!em) {
4943                 err = -ENOMEM;
4944                 goto out;
4945         }
4946         em->bdev = root->fs_info->fs_devices->latest_bdev;
4947         em->start = EXTENT_MAP_HOLE;
4948         em->orig_start = EXTENT_MAP_HOLE;
4949         em->len = (u64)-1;
4950         em->block_len = (u64)-1;
4951
4952         if (!path) {
4953                 path = btrfs_alloc_path();
4954                 BUG_ON(!path);
4955         }
4956
4957         ret = btrfs_lookup_file_extent(trans, root, path,
4958                                        objectid, start, trans != NULL);
4959         if (ret < 0) {
4960                 err = ret;
4961                 goto out;
4962         }
4963
4964         if (ret != 0) {
4965                 if (path->slots[0] == 0)
4966                         goto not_found;
4967                 path->slots[0]--;
4968         }
4969
4970         leaf = path->nodes[0];
4971         item = btrfs_item_ptr(leaf, path->slots[0],
4972                               struct btrfs_file_extent_item);
4973         /* are we inside the extent that was found? */
4974         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4975         found_type = btrfs_key_type(&found_key);
4976         if (found_key.objectid != objectid ||
4977             found_type != BTRFS_EXTENT_DATA_KEY) {
4978                 goto not_found;
4979         }
4980
4981         found_type = btrfs_file_extent_type(leaf, item);
4982         extent_start = found_key.offset;
4983         compressed = btrfs_file_extent_compression(leaf, item);
4984         if (found_type == BTRFS_FILE_EXTENT_REG ||
4985             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
4986                 extent_end = extent_start +
4987                        btrfs_file_extent_num_bytes(leaf, item);
4988         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4989                 size_t size;
4990                 size = btrfs_file_extent_inline_len(leaf, item);
4991                 extent_end = (extent_start + size + root->sectorsize - 1) &
4992                         ~((u64)root->sectorsize - 1);
4993         }
4994
4995         if (start >= extent_end) {
4996                 path->slots[0]++;
4997                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4998                         ret = btrfs_next_leaf(root, path);
4999                         if (ret < 0) {
5000                                 err = ret;
5001                                 goto out;
5002                         }
5003                         if (ret > 0)
5004                                 goto not_found;
5005                         leaf = path->nodes[0];
5006                 }
5007                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5008                 if (found_key.objectid != objectid ||
5009                     found_key.type != BTRFS_EXTENT_DATA_KEY)
5010                         goto not_found;
5011                 if (start + len <= found_key.offset)
5012                         goto not_found;
5013                 em->start = start;
5014                 em->len = found_key.offset - start;
5015                 goto not_found_em;
5016         }
5017
5018         if (found_type == BTRFS_FILE_EXTENT_REG ||
5019             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5020                 em->start = extent_start;
5021                 em->len = extent_end - extent_start;
5022                 em->orig_start = extent_start -
5023                                  btrfs_file_extent_offset(leaf, item);
5024                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5025                 if (bytenr == 0) {
5026                         em->block_start = EXTENT_MAP_HOLE;
5027                         goto insert;
5028                 }
5029                 if (compressed) {
5030                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5031                         em->block_start = bytenr;
5032                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5033                                                                          item);
5034                 } else {
5035                         bytenr += btrfs_file_extent_offset(leaf, item);
5036                         em->block_start = bytenr;
5037                         em->block_len = em->len;
5038                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5039                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5040                 }
5041                 goto insert;
5042         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5043                 unsigned long ptr;
5044                 char *map;
5045                 size_t size;
5046                 size_t extent_offset;
5047                 size_t copy_size;
5048
5049                 em->block_start = EXTENT_MAP_INLINE;
5050                 if (!page || create) {
5051                         em->start = extent_start;
5052                         em->len = extent_end - extent_start;
5053                         goto out;
5054                 }
5055
5056                 size = btrfs_file_extent_inline_len(leaf, item);
5057                 extent_offset = page_offset(page) + pg_offset - extent_start;
5058                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5059                                 size - extent_offset);
5060                 em->start = extent_start + extent_offset;
5061                 em->len = (copy_size + root->sectorsize - 1) &
5062                         ~((u64)root->sectorsize - 1);
5063                 em->orig_start = EXTENT_MAP_INLINE;
5064                 if (compressed)
5065                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5066                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5067                 if (create == 0 && !PageUptodate(page)) {
5068                         if (btrfs_file_extent_compression(leaf, item) ==
5069                             BTRFS_COMPRESS_ZLIB) {
5070                                 ret = uncompress_inline(path, inode, page,
5071                                                         pg_offset,
5072                                                         extent_offset, item);
5073                                 BUG_ON(ret);
5074                         } else {
5075                                 map = kmap(page);
5076                                 read_extent_buffer(leaf, map + pg_offset, ptr,
5077                                                    copy_size);
5078                                 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5079                                         memset(map + pg_offset + copy_size, 0,
5080                                                PAGE_CACHE_SIZE - pg_offset -
5081                                                copy_size);
5082                                 }
5083                                 kunmap(page);
5084                         }
5085                         flush_dcache_page(page);
5086                 } else if (create && PageUptodate(page)) {
5087                         WARN_ON(1);
5088                         if (!trans) {
5089                                 kunmap(page);
5090                                 free_extent_map(em);
5091                                 em = NULL;
5092                                 btrfs_release_path(root, path);
5093                                 trans = btrfs_join_transaction(root, 1);
5094                                 goto again;
5095                         }
5096                         map = kmap(page);
5097                         write_extent_buffer(leaf, map + pg_offset, ptr,
5098                                             copy_size);
5099                         kunmap(page);
5100                         btrfs_mark_buffer_dirty(leaf);
5101                 }
5102                 set_extent_uptodate(io_tree, em->start,
5103                                     extent_map_end(em) - 1, GFP_NOFS);
5104                 goto insert;
5105         } else {
5106                 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5107                 WARN_ON(1);
5108         }
5109 not_found:
5110         em->start = start;
5111         em->len = len;
5112 not_found_em:
5113         em->block_start = EXTENT_MAP_HOLE;
5114         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5115 insert:
5116         btrfs_release_path(root, path);
5117         if (em->start > start || extent_map_end(em) <= start) {
5118                 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5119                        "[%llu %llu]\n", (unsigned long long)em->start,
5120                        (unsigned long long)em->len,
5121                        (unsigned long long)start,
5122                        (unsigned long long)len);
5123                 err = -EIO;
5124                 goto out;
5125         }
5126
5127         err = 0;
5128         write_lock(&em_tree->lock);
5129         ret = add_extent_mapping(em_tree, em);
5130         /* it is possible that someone inserted the extent into the tree
5131          * while we had the lock dropped.  It is also possible that
5132          * an overlapping map exists in the tree
5133          */
5134         if (ret == -EEXIST) {
5135                 struct extent_map *existing;
5136
5137                 ret = 0;
5138
5139                 existing = lookup_extent_mapping(em_tree, start, len);
5140                 if (existing && (existing->start > start ||
5141                     existing->start + existing->len <= start)) {
5142                         free_extent_map(existing);
5143                         existing = NULL;
5144                 }
5145                 if (!existing) {
5146                         existing = lookup_extent_mapping(em_tree, em->start,
5147                                                          em->len);
5148                         if (existing) {
5149                                 err = merge_extent_mapping(em_tree, existing,
5150                                                            em, start,
5151                                                            root->sectorsize);
5152                                 free_extent_map(existing);
5153                                 if (err) {
5154                                         free_extent_map(em);
5155                                         em = NULL;
5156                                 }
5157                         } else {
5158                                 err = -EIO;
5159                                 free_extent_map(em);
5160                                 em = NULL;
5161                         }
5162                 } else {
5163                         free_extent_map(em);
5164                         em = existing;
5165                         err = 0;
5166                 }
5167         }
5168         write_unlock(&em_tree->lock);
5169 out:
5170         if (path)
5171                 btrfs_free_path(path);
5172         if (trans) {
5173                 ret = btrfs_end_transaction(trans, root);
5174                 if (!err)
5175                         err = ret;
5176         }
5177         if (err) {
5178                 free_extent_map(em);
5179                 return ERR_PTR(err);
5180         }
5181         return em;
5182 }
5183
5184 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5185                                                   u64 start, u64 len)
5186 {
5187         struct btrfs_root *root = BTRFS_I(inode)->root;
5188         struct btrfs_trans_handle *trans;
5189         struct extent_map *em;
5190         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5191         struct btrfs_key ins;
5192         u64 alloc_hint;
5193         int ret;
5194
5195         btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5196
5197         trans = btrfs_join_transaction(root, 0);
5198         if (!trans)
5199                 return ERR_PTR(-ENOMEM);
5200
5201         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5202
5203         alloc_hint = get_extent_allocation_hint(inode, start, len);
5204         ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5205                                    alloc_hint, (u64)-1, &ins, 1);
5206         if (ret) {
5207                 em = ERR_PTR(ret);
5208                 goto out;
5209         }
5210
5211         em = alloc_extent_map(GFP_NOFS);
5212         if (!em) {
5213                 em = ERR_PTR(-ENOMEM);
5214                 goto out;
5215         }
5216
5217         em->start = start;
5218         em->orig_start = em->start;
5219         em->len = ins.offset;
5220
5221         em->block_start = ins.objectid;
5222         em->block_len = ins.offset;
5223         em->bdev = root->fs_info->fs_devices->latest_bdev;
5224         set_bit(EXTENT_FLAG_PINNED, &em->flags);
5225
5226         while (1) {
5227                 write_lock(&em_tree->lock);
5228                 ret = add_extent_mapping(em_tree, em);
5229                 write_unlock(&em_tree->lock);
5230                 if (ret != -EEXIST)
5231                         break;
5232                 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5233         }
5234
5235         ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5236                                            ins.offset, ins.offset, 0);
5237         if (ret) {
5238                 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5239                 em = ERR_PTR(ret);
5240         }
5241 out:
5242         btrfs_end_transaction(trans, root);
5243         return em;
5244 }
5245
5246 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5247                                    struct buffer_head *bh_result, int create)
5248 {
5249         struct extent_map *em;
5250         struct btrfs_root *root = BTRFS_I(inode)->root;
5251         u64 start = iblock << inode->i_blkbits;
5252         u64 len = bh_result->b_size;
5253
5254         em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5255         if (IS_ERR(em))
5256                 return PTR_ERR(em);
5257
5258         /*
5259          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5260          * io.  INLINE is special, and we could probably kludge it in here, but
5261          * it's still buffered so for safety lets just fall back to the generic
5262          * buffered path.
5263          *
5264          * For COMPRESSED we _have_ to read the entire extent in so we can
5265          * decompress it, so there will be buffering required no matter what we
5266          * do, so go ahead and fallback to buffered.
5267          *
5268          * We return -ENOTBLK because thats what makes DIO go ahead and go back
5269          * to buffered IO.  Don't blame me, this is the price we pay for using
5270          * the generic code.
5271          */
5272         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5273             em->block_start == EXTENT_MAP_INLINE) {
5274                 free_extent_map(em);
5275                 return -ENOTBLK;
5276         }
5277
5278         /* Just a good old fashioned hole, return */
5279         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5280                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5281                 free_extent_map(em);
5282                 /* DIO will do one hole at a time, so just unlock a sector */
5283                 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5284                               start + root->sectorsize - 1, GFP_NOFS);
5285                 return 0;
5286         }
5287
5288         /*
5289          * We don't allocate a new extent in the following cases
5290          *
5291          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
5292          * existing extent.
5293          * 2) The extent is marked as PREALLOC.  We're good to go here and can
5294          * just use the extent.
5295          *
5296          */
5297         if (!create)
5298                 goto map;
5299
5300         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5301             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5302              em->block_start != EXTENT_MAP_HOLE)) {
5303                 u64 block_start;
5304                 int type;
5305                 int ret;
5306
5307                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5308                         type = BTRFS_ORDERED_PREALLOC;
5309                 else
5310                         type = BTRFS_ORDERED_NOCOW;
5311                 len = min(len, em->block_len - (start - em->start));
5312                 block_start = em->block_start + (start - em->start);
5313                 ret = btrfs_add_ordered_extent_dio(inode, start,
5314                                                    start, len, len, type);
5315                 if (ret) {
5316                         free_extent_map(em);
5317                         return ret;
5318                 }
5319         } else {
5320                 free_extent_map(em);
5321                 em = btrfs_new_extent_direct(inode, start, len);
5322                 if (IS_ERR(em))
5323                         return PTR_ERR(em);
5324                 len = min(len, em->block_len);
5325         }
5326         unlock_extent(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5327                       GFP_NOFS);
5328 map:
5329         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5330                 inode->i_blkbits;
5331         bh_result->b_size = em->len - (start - em->start);
5332         bh_result->b_bdev = em->bdev;
5333         set_buffer_mapped(bh_result);
5334         if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5335                 set_buffer_new(bh_result);
5336
5337         free_extent_map(em);
5338
5339         return 0;
5340 }
5341
5342 struct btrfs_dio_private {
5343         struct inode *inode;
5344         u64 logical_offset;
5345         u64 disk_bytenr;
5346         u64 bytes;
5347         u32 *csums;
5348         void *private;
5349 };
5350
5351 static void btrfs_endio_direct_read(struct bio *bio, int err)
5352 {
5353         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5354         struct bio_vec *bvec = bio->bi_io_vec;
5355         struct btrfs_dio_private *dip = bio->bi_private;
5356         struct inode *inode = dip->inode;
5357         struct btrfs_root *root = BTRFS_I(inode)->root;
5358         u64 start;
5359         u32 *private = dip->csums;
5360
5361         start = dip->logical_offset;
5362         do {
5363                 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5364                         struct page *page = bvec->bv_page;
5365                         char *kaddr;
5366                         u32 csum = ~(u32)0;
5367                         unsigned long flags;
5368
5369                         local_irq_save(flags);
5370                         kaddr = kmap_atomic(page, KM_IRQ0);
5371                         csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5372                                                csum, bvec->bv_len);
5373                         btrfs_csum_final(csum, (char *)&csum);
5374                         kunmap_atomic(kaddr, KM_IRQ0);
5375                         local_irq_restore(flags);
5376
5377                         flush_dcache_page(bvec->bv_page);
5378                         if (csum != *private) {
5379                                 printk(KERN_ERR "btrfs csum failed ino %lu off"
5380                                       " %llu csum %u private %u\n",
5381                                       inode->i_ino, (unsigned long long)start,
5382                                       csum, *private);
5383                                 err = -EIO;
5384                         }
5385                 }
5386
5387                 start += bvec->bv_len;
5388                 private++;
5389                 bvec++;
5390         } while (bvec <= bvec_end);
5391
5392         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5393                       dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5394         bio->bi_private = dip->private;
5395
5396         kfree(dip->csums);
5397         kfree(dip);
5398         dio_end_io(bio, err);
5399 }
5400
5401 static void btrfs_endio_direct_write(struct bio *bio, int err)
5402 {
5403         struct btrfs_dio_private *dip = bio->bi_private;
5404         struct inode *inode = dip->inode;
5405         struct btrfs_root *root = BTRFS_I(inode)->root;
5406         struct btrfs_trans_handle *trans;
5407         struct btrfs_ordered_extent *ordered = NULL;
5408         struct extent_state *cached_state = NULL;
5409         int ret;
5410
5411         if (err)
5412                 goto out_done;
5413
5414         ret = btrfs_dec_test_ordered_pending(inode, &ordered,
5415                                              dip->logical_offset, dip->bytes);
5416         if (!ret)
5417                 goto out_done;
5418
5419         BUG_ON(!ordered);
5420
5421         trans = btrfs_join_transaction(root, 1);
5422         if (!trans) {
5423                 err = -ENOMEM;
5424                 goto out;
5425         }
5426         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5427
5428         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5429                 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5430                 if (!ret)
5431                         ret = btrfs_update_inode(trans, root, inode);
5432                 err = ret;
5433                 goto out;
5434         }
5435
5436         lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5437                          ordered->file_offset + ordered->len - 1, 0,
5438                          &cached_state, GFP_NOFS);
5439
5440         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5441                 ret = btrfs_mark_extent_written(trans, inode,
5442                                                 ordered->file_offset,
5443                                                 ordered->file_offset +
5444                                                 ordered->len);
5445                 if (ret) {
5446                         err = ret;
5447                         goto out_unlock;
5448                 }
5449         } else {
5450                 ret = insert_reserved_file_extent(trans, inode,
5451                                                   ordered->file_offset,
5452                                                   ordered->start,
5453                                                   ordered->disk_len,
5454                                                   ordered->len,
5455                                                   ordered->len,
5456                                                   0, 0, 0,
5457                                                   BTRFS_FILE_EXTENT_REG);
5458                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5459                                    ordered->file_offset, ordered->len);
5460                 if (ret) {
5461                         err = ret;
5462                         WARN_ON(1);
5463                         goto out_unlock;
5464                 }
5465         }
5466
5467         add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5468         btrfs_ordered_update_i_size(inode, 0, ordered);
5469         btrfs_update_inode(trans, root, inode);
5470 out_unlock:
5471         unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5472                              ordered->file_offset + ordered->len - 1,
5473                              &cached_state, GFP_NOFS);
5474 out:
5475         btrfs_delalloc_release_metadata(inode, ordered->len);
5476         btrfs_end_transaction(trans, root);
5477         btrfs_put_ordered_extent(ordered);
5478         btrfs_put_ordered_extent(ordered);
5479 out_done:
5480         bio->bi_private = dip->private;
5481
5482         kfree(dip->csums);
5483         kfree(dip);
5484         dio_end_io(bio, err);
5485 }
5486
5487 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
5488                                 loff_t file_offset)
5489 {
5490         struct btrfs_root *root = BTRFS_I(inode)->root;
5491         struct btrfs_dio_private *dip;
5492         struct bio_vec *bvec = bio->bi_io_vec;
5493         u64 start;
5494         int skip_sum;
5495         int write = rw & (1 << BIO_RW);
5496         int ret = 0;
5497
5498         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
5499
5500         dip = kmalloc(sizeof(*dip), GFP_NOFS);
5501         if (!dip) {
5502                 ret = -ENOMEM;
5503                 goto free_ordered;
5504         }
5505         dip->csums = NULL;
5506
5507         if (!skip_sum) {
5508                 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
5509                 if (!dip->csums) {
5510                         ret = -ENOMEM;
5511                         goto free_ordered;
5512                 }
5513         }
5514
5515         dip->private = bio->bi_private;
5516         dip->inode = inode;
5517         dip->logical_offset = file_offset;
5518
5519         start = dip->logical_offset;
5520         dip->bytes = 0;
5521         do {
5522                 dip->bytes += bvec->bv_len;
5523                 bvec++;
5524         } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
5525
5526         dip->disk_bytenr = bio->bi_sector << 9;
5527         bio->bi_private = dip;
5528
5529         if (write)
5530                 bio->bi_end_io = btrfs_endio_direct_write;
5531         else
5532                 bio->bi_end_io = btrfs_endio_direct_read;
5533
5534         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5535         if (ret)
5536                 goto out_err;
5537
5538         if (write && !skip_sum)
5539                 btrfs_csum_one_bio(root, inode, bio, dip->logical_offset, 1);
5540         else if (!skip_sum)
5541                 btrfs_lookup_bio_sums_dio(root, inode, bio,
5542                                           dip->logical_offset, dip->csums);
5543
5544         ret = btrfs_map_bio(root, rw, bio, 0, 0);
5545         if (ret)
5546                 goto out_err;
5547         return;
5548 out_err:
5549         kfree(dip->csums);
5550         kfree(dip);
5551 free_ordered:
5552         /*
5553          * If this is a write, we need to clean up the reserved space and kill
5554          * the ordered extent.
5555          */
5556         if (write) {
5557                 struct btrfs_ordered_extent *ordered;
5558                 ordered = btrfs_lookup_ordered_extent(inode,
5559                                                       dip->logical_offset);
5560                 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
5561                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
5562                         btrfs_free_reserved_extent(root, ordered->start,
5563                                                    ordered->disk_len);
5564                 btrfs_put_ordered_extent(ordered);
5565                 btrfs_put_ordered_extent(ordered);
5566         }
5567         bio_endio(bio, ret);
5568 }
5569
5570 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
5571                         const struct iovec *iov, loff_t offset,
5572                         unsigned long nr_segs)
5573 {
5574         struct file *file = iocb->ki_filp;
5575         struct inode *inode = file->f_mapping->host;
5576         struct btrfs_ordered_extent *ordered;
5577         u64 lockstart, lockend;
5578         ssize_t ret;
5579
5580         lockstart = offset;
5581         lockend = offset + iov_length(iov, nr_segs) - 1;
5582         while (1) {
5583                 lock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5584                             GFP_NOFS);
5585                 /*
5586                  * We're concerned with the entire range that we're going to be
5587                  * doing DIO to, so we need to make sure theres no ordered
5588                  * extents in this range.
5589                  */
5590                 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5591                                                      lockend - lockstart + 1);
5592                 if (!ordered)
5593                         break;
5594                 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5595                               GFP_NOFS);
5596                 btrfs_start_ordered_extent(inode, ordered, 1);
5597                 btrfs_put_ordered_extent(ordered);
5598                 cond_resched();
5599         }
5600
5601         ret = __blockdev_direct_IO(rw, iocb, inode, NULL, iov, offset, nr_segs,
5602                                    btrfs_get_blocks_direct, NULL,
5603                                    btrfs_submit_direct, 0);
5604
5605         if (ret < 0 && ret != -EIOCBQUEUED) {
5606                 unlock_extent(&BTRFS_I(inode)->io_tree, offset,
5607                               offset + iov_length(iov, nr_segs) - 1, GFP_NOFS);
5608         } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
5609                 /*
5610                  * We're falling back to buffered, unlock the section we didn't
5611                  * do IO on.
5612                  */
5613                 unlock_extent(&BTRFS_I(inode)->io_tree, offset + ret,
5614                               offset + iov_length(iov, nr_segs) - 1, GFP_NOFS);
5615         }
5616
5617         return ret;
5618 }
5619
5620 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5621                 __u64 start, __u64 len)
5622 {
5623         return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent);
5624 }
5625
5626 int btrfs_readpage(struct file *file, struct page *page)
5627 {
5628         struct extent_io_tree *tree;
5629         tree = &BTRFS_I(page->mapping->host)->io_tree;
5630         return extent_read_full_page(tree, page, btrfs_get_extent);
5631 }
5632
5633 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
5634 {
5635         struct extent_io_tree *tree;
5636
5637
5638         if (current->flags & PF_MEMALLOC) {
5639                 redirty_page_for_writepage(wbc, page);
5640                 unlock_page(page);
5641                 return 0;
5642         }
5643         tree = &BTRFS_I(page->mapping->host)->io_tree;
5644         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
5645 }
5646
5647 int btrfs_writepages(struct address_space *mapping,
5648                      struct writeback_control *wbc)
5649 {
5650         struct extent_io_tree *tree;
5651
5652         tree = &BTRFS_I(mapping->host)->io_tree;
5653         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
5654 }
5655
5656 static int
5657 btrfs_readpages(struct file *file, struct address_space *mapping,
5658                 struct list_head *pages, unsigned nr_pages)
5659 {
5660         struct extent_io_tree *tree;
5661         tree = &BTRFS_I(mapping->host)->io_tree;
5662         return extent_readpages(tree, mapping, pages, nr_pages,
5663                                 btrfs_get_extent);
5664 }
5665 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
5666 {
5667         struct extent_io_tree *tree;
5668         struct extent_map_tree *map;
5669         int ret;
5670
5671         tree = &BTRFS_I(page->mapping->host)->io_tree;
5672         map = &BTRFS_I(page->mapping->host)->extent_tree;
5673         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
5674         if (ret == 1) {
5675                 ClearPagePrivate(page);
5676                 set_page_private(page, 0);
5677                 page_cache_release(page);
5678         }
5679         return ret;
5680 }
5681
5682 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
5683 {
5684         if (PageWriteback(page) || PageDirty(page))
5685                 return 0;
5686         return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
5687 }
5688
5689 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
5690 {
5691         struct extent_io_tree *tree;
5692         struct btrfs_ordered_extent *ordered;
5693         struct extent_state *cached_state = NULL;
5694         u64 page_start = page_offset(page);
5695         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
5696
5697
5698         /*
5699          * we have the page locked, so new writeback can't start,
5700          * and the dirty bit won't be cleared while we are here.
5701          *
5702          * Wait for IO on this page so that we can safely clear
5703          * the PagePrivate2 bit and do ordered accounting
5704          */
5705         wait_on_page_writeback(page);
5706
5707         tree = &BTRFS_I(page->mapping->host)->io_tree;
5708         if (offset) {
5709                 btrfs_releasepage(page, GFP_NOFS);
5710                 return;
5711         }
5712         lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
5713                          GFP_NOFS);
5714         ordered = btrfs_lookup_ordered_extent(page->mapping->host,
5715                                            page_offset(page));
5716         if (ordered) {
5717                 /*
5718                  * IO on this page will never be started, so we need
5719                  * to account for any ordered extents now
5720                  */
5721                 clear_extent_bit(tree, page_start, page_end,
5722                                  EXTENT_DIRTY | EXTENT_DELALLOC |
5723                                  EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
5724                                  &cached_state, GFP_NOFS);
5725                 /*
5726                  * whoever cleared the private bit is responsible
5727                  * for the finish_ordered_io
5728                  */
5729                 if (TestClearPagePrivate2(page)) {
5730                         btrfs_finish_ordered_io(page->mapping->host,
5731                                                 page_start, page_end);
5732                 }
5733                 btrfs_put_ordered_extent(ordered);
5734                 cached_state = NULL;
5735                 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
5736                                  GFP_NOFS);
5737         }
5738         clear_extent_bit(tree, page_start, page_end,
5739                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
5740                  EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
5741         __btrfs_releasepage(page, GFP_NOFS);
5742
5743         ClearPageChecked(page);
5744         if (PagePrivate(page)) {
5745                 ClearPagePrivate(page);
5746                 set_page_private(page, 0);
5747                 page_cache_release(page);
5748         }
5749 }
5750
5751 /*
5752  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
5753  * called from a page fault handler when a page is first dirtied. Hence we must
5754  * be careful to check for EOF conditions here. We set the page up correctly
5755  * for a written page which means we get ENOSPC checking when writing into
5756  * holes and correct delalloc and unwritten extent mapping on filesystems that
5757  * support these features.
5758  *
5759  * We are not allowed to take the i_mutex here so we have to play games to
5760  * protect against truncate races as the page could now be beyond EOF.  Because
5761  * vmtruncate() writes the inode size before removing pages, once we have the
5762  * page lock we can determine safely if the page is beyond EOF. If it is not
5763  * beyond EOF, then the page is guaranteed safe against truncation until we
5764  * unlock the page.
5765  */
5766 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5767 {
5768         struct page *page = vmf->page;
5769         struct inode *inode = fdentry(vma->vm_file)->d_inode;
5770         struct btrfs_root *root = BTRFS_I(inode)->root;
5771         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5772         struct btrfs_ordered_extent *ordered;
5773         struct extent_state *cached_state = NULL;
5774         char *kaddr;
5775         unsigned long zero_start;
5776         loff_t size;
5777         int ret;
5778         u64 page_start;
5779         u64 page_end;
5780
5781         ret  = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
5782         if (ret) {
5783                 if (ret == -ENOMEM)
5784                         ret = VM_FAULT_OOM;
5785                 else /* -ENOSPC, -EIO, etc */
5786                         ret = VM_FAULT_SIGBUS;
5787                 goto out;
5788         }
5789
5790         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
5791 again:
5792         lock_page(page);
5793         size = i_size_read(inode);
5794         page_start = page_offset(page);
5795         page_end = page_start + PAGE_CACHE_SIZE - 1;
5796
5797         if ((page->mapping != inode->i_mapping) ||
5798             (page_start >= size)) {
5799                 /* page got truncated out from underneath us */
5800                 goto out_unlock;
5801         }
5802         wait_on_page_writeback(page);
5803
5804         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
5805                          GFP_NOFS);
5806         set_page_extent_mapped(page);
5807
5808         /*
5809          * we can't set the delalloc bits if there are pending ordered
5810          * extents.  Drop our locks and wait for them to finish
5811          */
5812         ordered = btrfs_lookup_ordered_extent(inode, page_start);
5813         if (ordered) {
5814                 unlock_extent_cached(io_tree, page_start, page_end,
5815                                      &cached_state, GFP_NOFS);
5816                 unlock_page(page);
5817                 btrfs_start_ordered_extent(inode, ordered, 1);
5818                 btrfs_put_ordered_extent(ordered);
5819                 goto again;
5820         }
5821
5822         /*
5823          * XXX - page_mkwrite gets called every time the page is dirtied, even
5824          * if it was already dirty, so for space accounting reasons we need to
5825          * clear any delalloc bits for the range we are fixing to save.  There
5826          * is probably a better way to do this, but for now keep consistent with
5827          * prepare_pages in the normal write path.
5828          */
5829         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
5830                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
5831                           0, 0, &cached_state, GFP_NOFS);
5832
5833         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
5834                                         &cached_state);
5835         if (ret) {
5836                 unlock_extent_cached(io_tree, page_start, page_end,
5837                                      &cached_state, GFP_NOFS);
5838                 ret = VM_FAULT_SIGBUS;
5839                 goto out_unlock;
5840         }
5841         ret = 0;
5842
5843         /* page is wholly or partially inside EOF */
5844         if (page_start + PAGE_CACHE_SIZE > size)
5845                 zero_start = size & ~PAGE_CACHE_MASK;
5846         else
5847                 zero_start = PAGE_CACHE_SIZE;
5848
5849         if (zero_start != PAGE_CACHE_SIZE) {
5850                 kaddr = kmap(page);
5851                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
5852                 flush_dcache_page(page);
5853                 kunmap(page);
5854         }
5855         ClearPageChecked(page);
5856         set_page_dirty(page);
5857         SetPageUptodate(page);
5858
5859         BTRFS_I(inode)->last_trans = root->fs_info->generation;
5860         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
5861
5862         unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
5863
5864 out_unlock:
5865         if (!ret)
5866                 return VM_FAULT_LOCKED;
5867         unlock_page(page);
5868         btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
5869 out:
5870         return ret;
5871 }
5872
5873 static void btrfs_truncate(struct inode *inode)
5874 {
5875         struct btrfs_root *root = BTRFS_I(inode)->root;
5876         int ret;
5877         struct btrfs_trans_handle *trans;
5878         unsigned long nr;
5879         u64 mask = root->sectorsize - 1;
5880
5881         if (!S_ISREG(inode->i_mode)) {
5882                 WARN_ON(1);
5883                 return;
5884         }
5885
5886         ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
5887         if (ret)
5888                 return;
5889
5890         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
5891         btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
5892
5893         trans = btrfs_start_transaction(root, 0);
5894         BUG_ON(IS_ERR(trans));
5895         btrfs_set_trans_block_group(trans, inode);
5896         trans->block_rsv = root->orphan_block_rsv;
5897
5898         /*
5899          * setattr is responsible for setting the ordered_data_close flag,
5900          * but that is only tested during the last file release.  That
5901          * could happen well after the next commit, leaving a great big
5902          * window where new writes may get lost if someone chooses to write
5903          * to this file after truncating to zero
5904          *
5905          * The inode doesn't have any dirty data here, and so if we commit
5906          * this is a noop.  If someone immediately starts writing to the inode
5907          * it is very likely we'll catch some of their writes in this
5908          * transaction, and the commit will find this file on the ordered
5909          * data list with good things to send down.
5910          *
5911          * This is a best effort solution, there is still a window where
5912          * using truncate to replace the contents of the file will
5913          * end up with a zero length file after a crash.
5914          */
5915         if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
5916                 btrfs_add_ordered_operation(trans, root, inode);
5917
5918         while (1) {
5919                 if (!trans) {
5920                         trans = btrfs_start_transaction(root, 0);
5921                         BUG_ON(IS_ERR(trans));
5922                         btrfs_set_trans_block_group(trans, inode);
5923                         trans->block_rsv = root->orphan_block_rsv;
5924                 }
5925
5926                 ret = btrfs_block_rsv_check(trans, root,
5927                                             root->orphan_block_rsv, 0, 5);
5928                 if (ret) {
5929                         BUG_ON(ret != -EAGAIN);
5930                         ret = btrfs_commit_transaction(trans, root);
5931                         BUG_ON(ret);
5932                         trans = NULL;
5933                         continue;
5934                 }
5935
5936                 ret = btrfs_truncate_inode_items(trans, root, inode,
5937                                                  inode->i_size,
5938                                                  BTRFS_EXTENT_DATA_KEY);
5939                 if (ret != -EAGAIN)
5940                         break;
5941
5942                 ret = btrfs_update_inode(trans, root, inode);
5943                 BUG_ON(ret);
5944
5945                 nr = trans->blocks_used;
5946                 btrfs_end_transaction(trans, root);
5947                 trans = NULL;
5948                 btrfs_btree_balance_dirty(root, nr);
5949         }
5950
5951         if (ret == 0 && inode->i_nlink > 0) {
5952                 ret = btrfs_orphan_del(trans, inode);
5953                 BUG_ON(ret);
5954         }
5955
5956         ret = btrfs_update_inode(trans, root, inode);
5957         BUG_ON(ret);
5958
5959         nr = trans->blocks_used;
5960         ret = btrfs_end_transaction_throttle(trans, root);
5961         BUG_ON(ret);
5962         btrfs_btree_balance_dirty(root, nr);
5963 }
5964
5965 /*
5966  * create a new subvolume directory/inode (helper for the ioctl).
5967  */
5968 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
5969                              struct btrfs_root *new_root,
5970                              u64 new_dirid, u64 alloc_hint)
5971 {
5972         struct inode *inode;
5973         int err;
5974         u64 index = 0;
5975
5976         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
5977                                 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
5978         if (IS_ERR(inode))
5979                 return PTR_ERR(inode);
5980         inode->i_op = &btrfs_dir_inode_operations;
5981         inode->i_fop = &btrfs_dir_file_operations;
5982
5983         inode->i_nlink = 1;
5984         btrfs_i_size_write(inode, 0);
5985
5986         err = btrfs_update_inode(trans, new_root, inode);
5987         BUG_ON(err);
5988
5989         iput(inode);
5990         return 0;
5991 }
5992
5993 /* helper function for file defrag and space balancing.  This
5994  * forces readahead on a given range of bytes in an inode
5995  */
5996 unsigned long btrfs_force_ra(struct address_space *mapping,
5997                               struct file_ra_state *ra, struct file *file,
5998                               pgoff_t offset, pgoff_t last_index)
5999 {
6000         pgoff_t req_size = last_index - offset + 1;
6001
6002         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
6003         return offset + req_size;
6004 }
6005
6006 struct inode *btrfs_alloc_inode(struct super_block *sb)
6007 {
6008         struct btrfs_inode *ei;
6009         struct inode *inode;
6010
6011         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6012         if (!ei)
6013                 return NULL;
6014
6015         ei->root = NULL;
6016         ei->space_info = NULL;
6017         ei->generation = 0;
6018         ei->sequence = 0;
6019         ei->last_trans = 0;
6020         ei->last_sub_trans = 0;
6021         ei->logged_trans = 0;
6022         ei->delalloc_bytes = 0;
6023         ei->reserved_bytes = 0;
6024         ei->disk_i_size = 0;
6025         ei->flags = 0;
6026         ei->index_cnt = (u64)-1;
6027         ei->last_unlink_trans = 0;
6028
6029         spin_lock_init(&ei->accounting_lock);
6030         atomic_set(&ei->outstanding_extents, 0);
6031         ei->reserved_extents = 0;
6032
6033         ei->ordered_data_close = 0;
6034         ei->orphan_meta_reserved = 0;
6035         ei->dummy_inode = 0;
6036         ei->force_compress = 0;
6037
6038         inode = &ei->vfs_inode;
6039         extent_map_tree_init(&ei->extent_tree, GFP_NOFS);
6040         extent_io_tree_init(&ei->io_tree, &inode->i_data, GFP_NOFS);
6041         extent_io_tree_init(&ei->io_failure_tree, &inode->i_data, GFP_NOFS);
6042         mutex_init(&ei->log_mutex);
6043         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6044         INIT_LIST_HEAD(&ei->i_orphan);
6045         INIT_LIST_HEAD(&ei->delalloc_inodes);
6046         INIT_LIST_HEAD(&ei->ordered_operations);
6047         RB_CLEAR_NODE(&ei->rb_node);
6048
6049         return inode;
6050 }
6051
6052 void btrfs_destroy_inode(struct inode *inode)
6053 {
6054         struct btrfs_ordered_extent *ordered;
6055         struct btrfs_root *root = BTRFS_I(inode)->root;
6056
6057         WARN_ON(!list_empty(&inode->i_dentry));
6058         WARN_ON(inode->i_data.nrpages);
6059         WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents));
6060         WARN_ON(BTRFS_I(inode)->reserved_extents);
6061
6062         /*
6063          * This can happen where we create an inode, but somebody else also
6064          * created the same inode and we need to destroy the one we already
6065          * created.
6066          */
6067         if (!root)
6068                 goto free;
6069
6070         /*
6071          * Make sure we're properly removed from the ordered operation
6072          * lists.
6073          */
6074         smp_mb();
6075         if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6076                 spin_lock(&root->fs_info->ordered_extent_lock);
6077                 list_del_init(&BTRFS_I(inode)->ordered_operations);
6078                 spin_unlock(&root->fs_info->ordered_extent_lock);
6079         }
6080
6081         spin_lock(&root->orphan_lock);
6082         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6083                 printk(KERN_INFO "BTRFS: inode %lu still on the orphan list\n",
6084                        inode->i_ino);
6085                 list_del_init(&BTRFS_I(inode)->i_orphan);
6086         }
6087         spin_unlock(&root->orphan_lock);
6088
6089         while (1) {
6090                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6091                 if (!ordered)
6092                         break;
6093                 else {
6094                         printk(KERN_ERR "btrfs found ordered "
6095                                "extent %llu %llu on inode cleanup\n",
6096                                (unsigned long long)ordered->file_offset,
6097                                (unsigned long long)ordered->len);
6098                         btrfs_remove_ordered_extent(inode, ordered);
6099                         btrfs_put_ordered_extent(ordered);
6100                         btrfs_put_ordered_extent(ordered);
6101                 }
6102         }
6103         inode_tree_del(inode);
6104         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6105 free:
6106         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6107 }
6108
6109 void btrfs_drop_inode(struct inode *inode)
6110 {
6111         struct btrfs_root *root = BTRFS_I(inode)->root;
6112         if (inode->i_nlink > 0 && btrfs_root_refs(&root->root_item) == 0)
6113                 generic_delete_inode(inode);
6114         else
6115                 generic_drop_inode(inode);
6116 }
6117
6118 static void init_once(void *foo)
6119 {
6120         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6121
6122         inode_init_once(&ei->vfs_inode);
6123 }
6124
6125 void btrfs_destroy_cachep(void)
6126 {
6127         if (btrfs_inode_cachep)
6128                 kmem_cache_destroy(btrfs_inode_cachep);
6129         if (btrfs_trans_handle_cachep)
6130                 kmem_cache_destroy(btrfs_trans_handle_cachep);
6131         if (btrfs_transaction_cachep)
6132                 kmem_cache_destroy(btrfs_transaction_cachep);
6133         if (btrfs_path_cachep)
6134                 kmem_cache_destroy(btrfs_path_cachep);
6135 }
6136
6137 int btrfs_init_cachep(void)
6138 {
6139         btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6140                         sizeof(struct btrfs_inode), 0,
6141                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6142         if (!btrfs_inode_cachep)
6143                 goto fail;
6144
6145         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6146                         sizeof(struct btrfs_trans_handle), 0,
6147                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6148         if (!btrfs_trans_handle_cachep)
6149                 goto fail;
6150
6151         btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6152                         sizeof(struct btrfs_transaction), 0,
6153                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6154         if (!btrfs_transaction_cachep)
6155                 goto fail;
6156
6157         btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6158                         sizeof(struct btrfs_path), 0,
6159                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6160         if (!btrfs_path_cachep)
6161                 goto fail;
6162
6163         return 0;
6164 fail:
6165         btrfs_destroy_cachep();
6166         return -ENOMEM;
6167 }
6168
6169 static int btrfs_getattr(struct vfsmount *mnt,
6170                          struct dentry *dentry, struct kstat *stat)
6171 {
6172         struct inode *inode = dentry->d_inode;
6173         generic_fillattr(inode, stat);
6174         stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
6175         stat->blksize = PAGE_CACHE_SIZE;
6176         stat->blocks = (inode_get_bytes(inode) +
6177                         BTRFS_I(inode)->delalloc_bytes) >> 9;
6178         return 0;
6179 }
6180
6181 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6182                            struct inode *new_dir, struct dentry *new_dentry)
6183 {
6184         struct btrfs_trans_handle *trans;
6185         struct btrfs_root *root = BTRFS_I(old_dir)->root;
6186         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6187         struct inode *new_inode = new_dentry->d_inode;
6188         struct inode *old_inode = old_dentry->d_inode;
6189         struct timespec ctime = CURRENT_TIME;
6190         u64 index = 0;
6191         u64 root_objectid;
6192         int ret;
6193
6194         if (new_dir->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6195                 return -EPERM;
6196
6197         /* we only allow rename subvolume link between subvolumes */
6198         if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6199                 return -EXDEV;
6200
6201         if (old_inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6202             (new_inode && new_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID))
6203                 return -ENOTEMPTY;
6204
6205         if (S_ISDIR(old_inode->i_mode) && new_inode &&
6206             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6207                 return -ENOTEMPTY;
6208         /*
6209          * we're using rename to replace one file with another.
6210          * and the replacement file is large.  Start IO on it now so
6211          * we don't add too much work to the end of the transaction
6212          */
6213         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6214             old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6215                 filemap_flush(old_inode->i_mapping);
6216
6217         /* close the racy window with snapshot create/destroy ioctl */
6218         if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6219                 down_read(&root->fs_info->subvol_sem);
6220         /*
6221          * We want to reserve the absolute worst case amount of items.  So if
6222          * both inodes are subvols and we need to unlink them then that would
6223          * require 4 item modifications, but if they are both normal inodes it
6224          * would require 5 item modifications, so we'll assume their normal
6225          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6226          * should cover the worst case number of items we'll modify.
6227          */
6228         trans = btrfs_start_transaction(root, 20);
6229         if (IS_ERR(trans))
6230                 return PTR_ERR(trans);
6231
6232         btrfs_set_trans_block_group(trans, new_dir);
6233
6234         if (dest != root)
6235                 btrfs_record_root_in_trans(trans, dest);
6236
6237         ret = btrfs_set_inode_index(new_dir, &index);
6238         if (ret)
6239                 goto out_fail;
6240
6241         if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6242                 /* force full log commit if subvolume involved. */
6243                 root->fs_info->last_trans_log_full_commit = trans->transid;
6244         } else {
6245                 ret = btrfs_insert_inode_ref(trans, dest,
6246                                              new_dentry->d_name.name,
6247                                              new_dentry->d_name.len,
6248                                              old_inode->i_ino,
6249                                              new_dir->i_ino, index);
6250                 if (ret)
6251                         goto out_fail;
6252                 /*
6253                  * this is an ugly little race, but the rename is required
6254                  * to make sure that if we crash, the inode is either at the
6255                  * old name or the new one.  pinning the log transaction lets
6256                  * us make sure we don't allow a log commit to come in after
6257                  * we unlink the name but before we add the new name back in.
6258                  */
6259                 btrfs_pin_log_trans(root);
6260         }
6261         /*
6262          * make sure the inode gets flushed if it is replacing
6263          * something.
6264          */
6265         if (new_inode && new_inode->i_size &&
6266             old_inode && S_ISREG(old_inode->i_mode)) {
6267                 btrfs_add_ordered_operation(trans, root, old_inode);
6268         }
6269
6270         old_dir->i_ctime = old_dir->i_mtime = ctime;
6271         new_dir->i_ctime = new_dir->i_mtime = ctime;
6272         old_inode->i_ctime = ctime;
6273
6274         if (old_dentry->d_parent != new_dentry->d_parent)
6275                 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6276
6277         if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6278                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6279                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6280                                         old_dentry->d_name.name,
6281                                         old_dentry->d_name.len);
6282         } else {
6283                 btrfs_inc_nlink(old_dentry->d_inode);
6284                 ret = btrfs_unlink_inode(trans, root, old_dir,
6285                                          old_dentry->d_inode,
6286                                          old_dentry->d_name.name,
6287                                          old_dentry->d_name.len);
6288         }
6289         BUG_ON(ret);
6290
6291         if (new_inode) {
6292                 new_inode->i_ctime = CURRENT_TIME;
6293                 if (unlikely(new_inode->i_ino ==
6294                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6295                         root_objectid = BTRFS_I(new_inode)->location.objectid;
6296                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
6297                                                 root_objectid,
6298                                                 new_dentry->d_name.name,
6299                                                 new_dentry->d_name.len);
6300                         BUG_ON(new_inode->i_nlink == 0);
6301                 } else {
6302                         ret = btrfs_unlink_inode(trans, dest, new_dir,
6303                                                  new_dentry->d_inode,
6304                                                  new_dentry->d_name.name,
6305                                                  new_dentry->d_name.len);
6306                 }
6307                 BUG_ON(ret);
6308                 if (new_inode->i_nlink == 0) {
6309                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
6310                         BUG_ON(ret);
6311                 }
6312         }
6313
6314         ret = btrfs_add_link(trans, new_dir, old_inode,
6315                              new_dentry->d_name.name,
6316                              new_dentry->d_name.len, 0, index);
6317         BUG_ON(ret);
6318
6319         if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
6320                 btrfs_log_new_name(trans, old_inode, old_dir,
6321                                    new_dentry->d_parent);
6322                 btrfs_end_log_trans(root);
6323         }
6324 out_fail:
6325         btrfs_end_transaction_throttle(trans, root);
6326
6327         if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6328                 up_read(&root->fs_info->subvol_sem);
6329
6330         return ret;
6331 }
6332
6333 /*
6334  * some fairly slow code that needs optimization. This walks the list
6335  * of all the inodes with pending delalloc and forces them to disk.
6336  */
6337 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
6338 {
6339         struct list_head *head = &root->fs_info->delalloc_inodes;
6340         struct btrfs_inode *binode;
6341         struct inode *inode;
6342
6343         if (root->fs_info->sb->s_flags & MS_RDONLY)
6344                 return -EROFS;
6345
6346         spin_lock(&root->fs_info->delalloc_lock);
6347         while (!list_empty(head)) {
6348                 binode = list_entry(head->next, struct btrfs_inode,
6349                                     delalloc_inodes);
6350                 inode = igrab(&binode->vfs_inode);
6351                 if (!inode)
6352                         list_del_init(&binode->delalloc_inodes);
6353                 spin_unlock(&root->fs_info->delalloc_lock);
6354                 if (inode) {
6355                         filemap_flush(inode->i_mapping);
6356                         if (delay_iput)
6357                                 btrfs_add_delayed_iput(inode);
6358                         else
6359                                 iput(inode);
6360                 }
6361                 cond_resched();
6362                 spin_lock(&root->fs_info->delalloc_lock);
6363         }
6364         spin_unlock(&root->fs_info->delalloc_lock);
6365
6366         /* the filemap_flush will queue IO into the worker threads, but
6367          * we have to make sure the IO is actually started and that
6368          * ordered extents get created before we return
6369          */
6370         atomic_inc(&root->fs_info->async_submit_draining);
6371         while (atomic_read(&root->fs_info->nr_async_submits) ||
6372               atomic_read(&root->fs_info->async_delalloc_pages)) {
6373                 wait_event(root->fs_info->async_submit_wait,
6374                    (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
6375                     atomic_read(&root->fs_info->async_delalloc_pages) == 0));
6376         }
6377         atomic_dec(&root->fs_info->async_submit_draining);
6378         return 0;
6379 }
6380
6381 int btrfs_start_one_delalloc_inode(struct btrfs_root *root, int delay_iput)
6382 {
6383         struct btrfs_inode *binode;
6384         struct inode *inode = NULL;
6385
6386         spin_lock(&root->fs_info->delalloc_lock);
6387         while (!list_empty(&root->fs_info->delalloc_inodes)) {
6388                 binode = list_entry(root->fs_info->delalloc_inodes.next,
6389                                     struct btrfs_inode, delalloc_inodes);
6390                 inode = igrab(&binode->vfs_inode);
6391                 if (inode) {
6392                         list_move_tail(&binode->delalloc_inodes,
6393                                        &root->fs_info->delalloc_inodes);
6394                         break;
6395                 }
6396
6397                 list_del_init(&binode->delalloc_inodes);
6398                 cond_resched_lock(&root->fs_info->delalloc_lock);
6399         }
6400         spin_unlock(&root->fs_info->delalloc_lock);
6401
6402         if (inode) {
6403                 write_inode_now(inode, 0);
6404                 if (delay_iput)
6405                         btrfs_add_delayed_iput(inode);
6406                 else
6407                         iput(inode);
6408                 return 1;
6409         }
6410         return 0;
6411 }
6412
6413 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
6414                          const char *symname)
6415 {
6416         struct btrfs_trans_handle *trans;
6417         struct btrfs_root *root = BTRFS_I(dir)->root;
6418         struct btrfs_path *path;
6419         struct btrfs_key key;
6420         struct inode *inode = NULL;
6421         int err;
6422         int drop_inode = 0;
6423         u64 objectid;
6424         u64 index = 0 ;
6425         int name_len;
6426         int datasize;
6427         unsigned long ptr;
6428         struct btrfs_file_extent_item *ei;
6429         struct extent_buffer *leaf;
6430         unsigned long nr = 0;
6431
6432         name_len = strlen(symname) + 1;
6433         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
6434                 return -ENAMETOOLONG;
6435
6436         err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
6437         if (err)
6438                 return err;
6439         /*
6440          * 2 items for inode item and ref
6441          * 2 items for dir items
6442          * 1 item for xattr if selinux is on
6443          */
6444         trans = btrfs_start_transaction(root, 5);
6445         if (IS_ERR(trans))
6446                 return PTR_ERR(trans);
6447
6448         btrfs_set_trans_block_group(trans, dir);
6449
6450         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6451                                 dentry->d_name.len,
6452                                 dentry->d_parent->d_inode->i_ino, objectid,
6453                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
6454                                 &index);
6455         err = PTR_ERR(inode);
6456         if (IS_ERR(inode))
6457                 goto out_unlock;
6458
6459         err = btrfs_init_inode_security(trans, inode, dir);
6460         if (err) {
6461                 drop_inode = 1;
6462                 goto out_unlock;
6463         }
6464
6465         btrfs_set_trans_block_group(trans, inode);
6466         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
6467         if (err)
6468                 drop_inode = 1;
6469         else {
6470                 inode->i_mapping->a_ops = &btrfs_aops;
6471                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6472                 inode->i_fop = &btrfs_file_operations;
6473                 inode->i_op = &btrfs_file_inode_operations;
6474                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6475         }
6476         btrfs_update_inode_block_group(trans, inode);
6477         btrfs_update_inode_block_group(trans, dir);
6478         if (drop_inode)
6479                 goto out_unlock;
6480
6481         path = btrfs_alloc_path();
6482         BUG_ON(!path);
6483         key.objectid = inode->i_ino;
6484         key.offset = 0;
6485         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
6486         datasize = btrfs_file_extent_calc_inline_size(name_len);
6487         err = btrfs_insert_empty_item(trans, root, path, &key,
6488                                       datasize);
6489         if (err) {
6490                 drop_inode = 1;
6491                 goto out_unlock;
6492         }
6493         leaf = path->nodes[0];
6494         ei = btrfs_item_ptr(leaf, path->slots[0],
6495                             struct btrfs_file_extent_item);
6496         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
6497         btrfs_set_file_extent_type(leaf, ei,
6498                                    BTRFS_FILE_EXTENT_INLINE);
6499         btrfs_set_file_extent_encryption(leaf, ei, 0);
6500         btrfs_set_file_extent_compression(leaf, ei, 0);
6501         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
6502         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
6503
6504         ptr = btrfs_file_extent_inline_start(ei);
6505         write_extent_buffer(leaf, symname, ptr, name_len);
6506         btrfs_mark_buffer_dirty(leaf);
6507         btrfs_free_path(path);
6508
6509         inode->i_op = &btrfs_symlink_inode_operations;
6510         inode->i_mapping->a_ops = &btrfs_symlink_aops;
6511         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6512         inode_set_bytes(inode, name_len);
6513         btrfs_i_size_write(inode, name_len - 1);
6514         err = btrfs_update_inode(trans, root, inode);
6515         if (err)
6516                 drop_inode = 1;
6517
6518 out_unlock:
6519         nr = trans->blocks_used;
6520         btrfs_end_transaction_throttle(trans, root);
6521         if (drop_inode) {
6522                 inode_dec_link_count(inode);
6523                 iput(inode);
6524         }
6525         btrfs_btree_balance_dirty(root, nr);
6526         return err;
6527 }
6528
6529 int btrfs_prealloc_file_range(struct inode *inode, int mode,
6530                               u64 start, u64 num_bytes, u64 min_size,
6531                               loff_t actual_len, u64 *alloc_hint)
6532 {
6533         struct btrfs_trans_handle *trans;
6534         struct btrfs_root *root = BTRFS_I(inode)->root;
6535         struct btrfs_key ins;
6536         u64 cur_offset = start;
6537         int ret = 0;
6538
6539         while (num_bytes > 0) {
6540                 trans = btrfs_start_transaction(root, 3);
6541                 if (IS_ERR(trans)) {
6542                         ret = PTR_ERR(trans);
6543                         break;
6544                 }
6545
6546                 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
6547                                            0, *alloc_hint, (u64)-1, &ins, 1);
6548                 if (ret) {
6549                         btrfs_end_transaction(trans, root);
6550                         break;
6551                 }
6552
6553                 ret = insert_reserved_file_extent(trans, inode,
6554                                                   cur_offset, ins.objectid,
6555                                                   ins.offset, ins.offset,
6556                                                   ins.offset, 0, 0, 0,
6557                                                   BTRFS_FILE_EXTENT_PREALLOC);
6558                 BUG_ON(ret);
6559                 btrfs_drop_extent_cache(inode, cur_offset,
6560                                         cur_offset + ins.offset -1, 0);
6561
6562                 num_bytes -= ins.offset;
6563                 cur_offset += ins.offset;
6564                 *alloc_hint = ins.objectid + ins.offset;
6565
6566                 inode->i_ctime = CURRENT_TIME;
6567                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
6568                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
6569                     (actual_len > inode->i_size) &&
6570                     (cur_offset > inode->i_size)) {
6571                         if (cur_offset > actual_len)
6572                                 i_size_write(inode, actual_len);
6573                         else
6574                                 i_size_write(inode, cur_offset);
6575                         i_size_write(inode, cur_offset);
6576                         btrfs_ordered_update_i_size(inode, cur_offset, NULL);
6577                 }
6578
6579                 ret = btrfs_update_inode(trans, root, inode);
6580                 BUG_ON(ret);
6581
6582                 btrfs_end_transaction(trans, root);
6583         }
6584         return ret;
6585 }
6586
6587 static long btrfs_fallocate(struct inode *inode, int mode,
6588                             loff_t offset, loff_t len)
6589 {
6590         struct extent_state *cached_state = NULL;
6591         u64 cur_offset;
6592         u64 last_byte;
6593         u64 alloc_start;
6594         u64 alloc_end;
6595         u64 alloc_hint = 0;
6596         u64 locked_end;
6597         u64 mask = BTRFS_I(inode)->root->sectorsize - 1;
6598         struct extent_map *em;
6599         int ret;
6600
6601         alloc_start = offset & ~mask;
6602         alloc_end =  (offset + len + mask) & ~mask;
6603
6604         /*
6605          * wait for ordered IO before we have any locks.  We'll loop again
6606          * below with the locks held.
6607          */
6608         btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
6609
6610         mutex_lock(&inode->i_mutex);
6611         if (alloc_start > inode->i_size) {
6612                 ret = btrfs_cont_expand(inode, alloc_start);
6613                 if (ret)
6614                         goto out;
6615         }
6616
6617         ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
6618         if (ret)
6619                 goto out;
6620
6621         locked_end = alloc_end - 1;
6622         while (1) {
6623                 struct btrfs_ordered_extent *ordered;
6624
6625                 /* the extent lock is ordered inside the running
6626                  * transaction
6627                  */
6628                 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
6629                                  locked_end, 0, &cached_state, GFP_NOFS);
6630                 ordered = btrfs_lookup_first_ordered_extent(inode,
6631                                                             alloc_end - 1);
6632                 if (ordered &&
6633                     ordered->file_offset + ordered->len > alloc_start &&
6634                     ordered->file_offset < alloc_end) {
6635                         btrfs_put_ordered_extent(ordered);
6636                         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
6637                                              alloc_start, locked_end,
6638                                              &cached_state, GFP_NOFS);
6639                         /*
6640                          * we can't wait on the range with the transaction
6641                          * running or with the extent lock held
6642                          */
6643                         btrfs_wait_ordered_range(inode, alloc_start,
6644                                                  alloc_end - alloc_start);
6645                 } else {
6646                         if (ordered)
6647                                 btrfs_put_ordered_extent(ordered);
6648                         break;
6649                 }
6650         }
6651
6652         cur_offset = alloc_start;
6653         while (1) {
6654                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
6655                                       alloc_end - cur_offset, 0);
6656                 BUG_ON(IS_ERR(em) || !em);
6657                 last_byte = min(extent_map_end(em), alloc_end);
6658                 last_byte = (last_byte + mask) & ~mask;
6659                 if (em->block_start == EXTENT_MAP_HOLE ||
6660                     (cur_offset >= inode->i_size &&
6661                      !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6662                         ret = btrfs_prealloc_file_range(inode, 0, cur_offset,
6663                                                         last_byte - cur_offset,
6664                                                         1 << inode->i_blkbits,
6665                                                         offset + len,
6666                                                         &alloc_hint);
6667                         if (ret < 0) {
6668                                 free_extent_map(em);
6669                                 break;
6670                         }
6671                 }
6672                 free_extent_map(em);
6673
6674                 cur_offset = last_byte;
6675                 if (cur_offset >= alloc_end) {
6676                         ret = 0;
6677                         break;
6678                 }
6679         }
6680         unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
6681                              &cached_state, GFP_NOFS);
6682
6683         btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
6684 out:
6685         mutex_unlock(&inode->i_mutex);
6686         return ret;
6687 }
6688
6689 static int btrfs_set_page_dirty(struct page *page)
6690 {
6691         return __set_page_dirty_nobuffers(page);
6692 }
6693
6694 static int btrfs_permission(struct inode *inode, int mask)
6695 {
6696         if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
6697                 return -EACCES;
6698         return generic_permission(inode, mask, btrfs_check_acl);
6699 }
6700
6701 static const struct inode_operations btrfs_dir_inode_operations = {
6702         .getattr        = btrfs_getattr,
6703         .lookup         = btrfs_lookup,
6704         .create         = btrfs_create,
6705         .unlink         = btrfs_unlink,
6706         .link           = btrfs_link,
6707         .mkdir          = btrfs_mkdir,
6708         .rmdir          = btrfs_rmdir,
6709         .rename         = btrfs_rename,
6710         .symlink        = btrfs_symlink,
6711         .setattr        = btrfs_setattr,
6712         .mknod          = btrfs_mknod,
6713         .setxattr       = btrfs_setxattr,
6714         .getxattr       = btrfs_getxattr,
6715         .listxattr      = btrfs_listxattr,
6716         .removexattr    = btrfs_removexattr,
6717         .permission     = btrfs_permission,
6718 };
6719 static const struct inode_operations btrfs_dir_ro_inode_operations = {
6720         .lookup         = btrfs_lookup,
6721         .permission     = btrfs_permission,
6722 };
6723
6724 static const struct file_operations btrfs_dir_file_operations = {
6725         .llseek         = generic_file_llseek,
6726         .read           = generic_read_dir,
6727         .readdir        = btrfs_real_readdir,
6728         .unlocked_ioctl = btrfs_ioctl,
6729 #ifdef CONFIG_COMPAT
6730         .compat_ioctl   = btrfs_ioctl,
6731 #endif
6732         .release        = btrfs_release_file,
6733         .fsync          = btrfs_sync_file,
6734 };
6735
6736 static struct extent_io_ops btrfs_extent_io_ops = {
6737         .fill_delalloc = run_delalloc_range,
6738         .submit_bio_hook = btrfs_submit_bio_hook,
6739         .merge_bio_hook = btrfs_merge_bio_hook,
6740         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
6741         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
6742         .writepage_start_hook = btrfs_writepage_start_hook,
6743         .readpage_io_failed_hook = btrfs_io_failed_hook,
6744         .set_bit_hook = btrfs_set_bit_hook,
6745         .clear_bit_hook = btrfs_clear_bit_hook,
6746         .merge_extent_hook = btrfs_merge_extent_hook,
6747         .split_extent_hook = btrfs_split_extent_hook,
6748 };
6749
6750 /*
6751  * btrfs doesn't support the bmap operation because swapfiles
6752  * use bmap to make a mapping of extents in the file.  They assume
6753  * these extents won't change over the life of the file and they
6754  * use the bmap result to do IO directly to the drive.
6755  *
6756  * the btrfs bmap call would return logical addresses that aren't
6757  * suitable for IO and they also will change frequently as COW
6758  * operations happen.  So, swapfile + btrfs == corruption.
6759  *
6760  * For now we're avoiding this by dropping bmap.
6761  */
6762 static const struct address_space_operations btrfs_aops = {
6763         .readpage       = btrfs_readpage,
6764         .writepage      = btrfs_writepage,
6765         .writepages     = btrfs_writepages,
6766         .readpages      = btrfs_readpages,
6767         .sync_page      = block_sync_page,
6768         .direct_IO      = btrfs_direct_IO,
6769         .invalidatepage = btrfs_invalidatepage,
6770         .releasepage    = btrfs_releasepage,
6771         .set_page_dirty = btrfs_set_page_dirty,
6772         .error_remove_page = generic_error_remove_page,
6773 };
6774
6775 static const struct address_space_operations btrfs_symlink_aops = {
6776         .readpage       = btrfs_readpage,
6777         .writepage      = btrfs_writepage,
6778         .invalidatepage = btrfs_invalidatepage,
6779         .releasepage    = btrfs_releasepage,
6780 };
6781
6782 static const struct inode_operations btrfs_file_inode_operations = {
6783         .truncate       = btrfs_truncate,
6784         .getattr        = btrfs_getattr,
6785         .setattr        = btrfs_setattr,
6786         .setxattr       = btrfs_setxattr,
6787         .getxattr       = btrfs_getxattr,
6788         .listxattr      = btrfs_listxattr,
6789         .removexattr    = btrfs_removexattr,
6790         .permission     = btrfs_permission,
6791         .fallocate      = btrfs_fallocate,
6792         .fiemap         = btrfs_fiemap,
6793 };
6794 static const struct inode_operations btrfs_special_inode_operations = {
6795         .getattr        = btrfs_getattr,
6796         .setattr        = btrfs_setattr,
6797         .permission     = btrfs_permission,
6798         .setxattr       = btrfs_setxattr,
6799         .getxattr       = btrfs_getxattr,
6800         .listxattr      = btrfs_listxattr,
6801         .removexattr    = btrfs_removexattr,
6802 };
6803 static const struct inode_operations btrfs_symlink_inode_operations = {
6804         .readlink       = generic_readlink,
6805         .follow_link    = page_follow_link_light,
6806         .put_link       = page_put_link,
6807         .permission     = btrfs_permission,
6808         .setxattr       = btrfs_setxattr,
6809         .getxattr       = btrfs_getxattr,
6810         .listxattr      = btrfs_listxattr,
6811         .removexattr    = btrfs_removexattr,
6812 };
6813
6814 const struct dentry_operations btrfs_dentry_operations = {
6815         .d_delete       = btrfs_dentry_delete,
6816 };