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