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