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