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