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