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