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