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