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