007d487eeb6c57aaf29592c84d1b9968425b3019
[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         bool emitted;
4115
4116         /* FIXME, use a real flag for deciding about the key type */
4117         if (root->fs_info->tree_root == root)
4118                 key_type = BTRFS_DIR_ITEM_KEY;
4119
4120         /* special case for "." */
4121         if (filp->f_pos == 0) {
4122                 over = filldir(dirent, ".", 1,
4123                                filp->f_pos, btrfs_ino(inode), DT_DIR);
4124                 if (over)
4125                         return 0;
4126                 filp->f_pos = 1;
4127         }
4128         /* special case for .., just use the back ref */
4129         if (filp->f_pos == 1) {
4130                 u64 pino = parent_ino(filp->f_path.dentry);
4131                 over = filldir(dirent, "..", 2,
4132                                filp->f_pos, pino, DT_DIR);
4133                 if (over)
4134                         return 0;
4135                 filp->f_pos = 2;
4136         }
4137         path = btrfs_alloc_path();
4138         if (!path)
4139                 return -ENOMEM;
4140
4141         path->reada = 1;
4142
4143         if (key_type == BTRFS_DIR_INDEX_KEY) {
4144                 INIT_LIST_HEAD(&ins_list);
4145                 INIT_LIST_HEAD(&del_list);
4146                 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4147         }
4148
4149         btrfs_set_key_type(&key, key_type);
4150         key.offset = filp->f_pos;
4151         key.objectid = btrfs_ino(inode);
4152
4153         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4154         if (ret < 0)
4155                 goto err;
4156
4157         emitted = false;
4158         while (1) {
4159                 leaf = path->nodes[0];
4160                 slot = path->slots[0];
4161                 if (slot >= btrfs_header_nritems(leaf)) {
4162                         ret = btrfs_next_leaf(root, path);
4163                         if (ret < 0)
4164                                 goto err;
4165                         else if (ret > 0)
4166                                 break;
4167                         continue;
4168                 }
4169
4170                 item = btrfs_item_nr(leaf, slot);
4171                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4172
4173                 if (found_key.objectid != key.objectid)
4174                         break;
4175                 if (btrfs_key_type(&found_key) != key_type)
4176                         break;
4177                 if (found_key.offset < filp->f_pos)
4178                         goto next;
4179                 if (key_type == BTRFS_DIR_INDEX_KEY &&
4180                     btrfs_should_delete_dir_index(&del_list,
4181                                                   found_key.offset))
4182                         goto next;
4183
4184                 filp->f_pos = found_key.offset;
4185                 is_curr = 1;
4186
4187                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4188                 di_cur = 0;
4189                 di_total = btrfs_item_size(leaf, item);
4190
4191                 while (di_cur < di_total) {
4192                         struct btrfs_key location;
4193                         struct dentry *tmp;
4194
4195                         if (verify_dir_item(root, leaf, di))
4196                                 break;
4197
4198                         name_len = btrfs_dir_name_len(leaf, di);
4199                         if (name_len <= sizeof(tmp_name)) {
4200                                 name_ptr = tmp_name;
4201                         } else {
4202                                 name_ptr = kmalloc(name_len, GFP_NOFS);
4203                                 if (!name_ptr) {
4204                                         ret = -ENOMEM;
4205                                         goto err;
4206                                 }
4207                         }
4208                         read_extent_buffer(leaf, name_ptr,
4209                                            (unsigned long)(di + 1), name_len);
4210
4211                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4212                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
4213
4214                         q.name = name_ptr;
4215                         q.len = name_len;
4216                         q.hash = full_name_hash(q.name, q.len);
4217                         tmp = d_lookup(filp->f_dentry, &q);
4218                         if (!tmp) {
4219                                 struct btrfs_key *newkey;
4220
4221                                 newkey = kzalloc(sizeof(struct btrfs_key),
4222                                                  GFP_NOFS);
4223                                 if (!newkey)
4224                                         goto no_dentry;
4225                                 tmp = d_alloc(filp->f_dentry, &q);
4226                                 if (!tmp) {
4227                                         kfree(newkey);
4228                                         dput(tmp);
4229                                         goto no_dentry;
4230                                 }
4231                                 memcpy(newkey, &location,
4232                                        sizeof(struct btrfs_key));
4233                                 tmp->d_fsdata = newkey;
4234                                 tmp->d_flags |= DCACHE_NEED_LOOKUP;
4235                                 d_rehash(tmp);
4236                                 dput(tmp);
4237                         } else {
4238                                 dput(tmp);
4239                         }
4240 no_dentry:
4241                         /* is this a reference to our own snapshot? If so
4242                          * skip it
4243                          */
4244                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
4245                             location.objectid == root->root_key.objectid) {
4246                                 over = 0;
4247                                 goto skip;
4248                         }
4249                         over = filldir(dirent, name_ptr, name_len,
4250                                        found_key.offset, location.objectid,
4251                                        d_type);
4252
4253 skip:
4254                         if (name_ptr != tmp_name)
4255                                 kfree(name_ptr);
4256
4257                         if (over)
4258                                 goto nopos;
4259                         emitted = true;
4260                         di_len = btrfs_dir_name_len(leaf, di) +
4261                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
4262                         di_cur += di_len;
4263                         di = (struct btrfs_dir_item *)((char *)di + di_len);
4264                 }
4265 next:
4266                 path->slots[0]++;
4267         }
4268
4269         if (key_type == BTRFS_DIR_INDEX_KEY) {
4270                 if (is_curr)
4271                         filp->f_pos++;
4272                 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4273                                                       &ins_list, &emitted);
4274                 if (ret)
4275                         goto nopos;
4276         }
4277
4278         /*
4279          * If we haven't emitted any dir entry, we must not touch filp->f_pos as
4280          * it was was set to the termination value in previous call. We assume
4281          * that "." and ".." were emitted if we reach this point and set the
4282          * termination value as well for an empty directory.
4283          */
4284         if (filp->f_pos > 2 && !emitted)
4285                 goto nopos;
4286
4287         /* Reached end of directory/root. Bump pos past the last item. */
4288         if (key_type == BTRFS_DIR_INDEX_KEY)
4289                 /*
4290                  * 32-bit glibc will use getdents64, but then strtol -
4291                  * so the last number we can serve is this.
4292                  */
4293                 filp->f_pos = 0x7fffffff;
4294         else
4295                 filp->f_pos++;
4296 nopos:
4297         ret = 0;
4298 err:
4299         if (key_type == BTRFS_DIR_INDEX_KEY)
4300                 btrfs_put_delayed_items(&ins_list, &del_list);
4301         btrfs_free_path(path);
4302         return ret;
4303 }
4304
4305 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4306 {
4307         struct btrfs_root *root = BTRFS_I(inode)->root;
4308         struct btrfs_trans_handle *trans;
4309         int ret = 0;
4310         bool nolock = false;
4311
4312         if (BTRFS_I(inode)->dummy_inode)
4313                 return 0;
4314
4315         if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(root, inode))
4316                 nolock = true;
4317
4318         if (wbc->sync_mode == WB_SYNC_ALL) {
4319                 if (nolock)
4320                         trans = btrfs_join_transaction_nolock(root);
4321                 else
4322                         trans = btrfs_join_transaction(root);
4323                 if (IS_ERR(trans))
4324                         return PTR_ERR(trans);
4325                 if (nolock)
4326                         ret = btrfs_end_transaction_nolock(trans, root);
4327                 else
4328                         ret = btrfs_commit_transaction(trans, root);
4329         }
4330         return ret;
4331 }
4332
4333 /*
4334  * This is somewhat expensive, updating the tree every time the
4335  * inode changes.  But, it is most likely to find the inode in cache.
4336  * FIXME, needs more benchmarking...there are no reasons other than performance
4337  * to keep or drop this code.
4338  */
4339 int btrfs_dirty_inode(struct inode *inode)
4340 {
4341         struct btrfs_root *root = BTRFS_I(inode)->root;
4342         struct btrfs_trans_handle *trans;
4343         int ret;
4344
4345         if (BTRFS_I(inode)->dummy_inode)
4346                 return 0;
4347
4348         trans = btrfs_join_transaction(root);
4349         if (IS_ERR(trans))
4350                 return PTR_ERR(trans);
4351
4352         ret = btrfs_update_inode(trans, root, inode);
4353         if (ret && ret == -ENOSPC) {
4354                 /* whoops, lets try again with the full transaction */
4355                 btrfs_end_transaction(trans, root);
4356                 trans = btrfs_start_transaction(root, 1);
4357                 if (IS_ERR(trans))
4358                         return PTR_ERR(trans);
4359
4360                 ret = btrfs_update_inode(trans, root, inode);
4361         }
4362         btrfs_end_transaction(trans, root);
4363         if (BTRFS_I(inode)->delayed_node)
4364                 btrfs_balance_delayed_items(root);
4365
4366         return ret;
4367 }
4368
4369 /*
4370  * This is a copy of file_update_time.  We need this so we can return error on
4371  * ENOSPC for updating the inode in the case of file write and mmap writes.
4372  */
4373 int btrfs_update_time(struct file *file)
4374 {
4375         struct inode *inode = file->f_path.dentry->d_inode;
4376         struct timespec now;
4377         int ret;
4378         enum { S_MTIME = 1, S_CTIME = 2, S_VERSION = 4 } sync_it = 0;
4379
4380         /* First try to exhaust all avenues to not sync */
4381         if (IS_NOCMTIME(inode))
4382                 return 0;
4383
4384         now = current_fs_time(inode->i_sb);
4385         if (!timespec_equal(&inode->i_mtime, &now))
4386                 sync_it = S_MTIME;
4387
4388         if (!timespec_equal(&inode->i_ctime, &now))
4389                 sync_it |= S_CTIME;
4390
4391         if (IS_I_VERSION(inode))
4392                 sync_it |= S_VERSION;
4393
4394         if (!sync_it)
4395                 return 0;
4396
4397         /* Finally allowed to write? Takes lock. */
4398         if (mnt_want_write_file(file))
4399                 return 0;
4400
4401         /* Only change inode inside the lock region */
4402         if (sync_it & S_VERSION)
4403                 inode_inc_iversion(inode);
4404         if (sync_it & S_CTIME)
4405                 inode->i_ctime = now;
4406         if (sync_it & S_MTIME)
4407                 inode->i_mtime = now;
4408         ret = btrfs_dirty_inode(inode);
4409         if (!ret)
4410                 mark_inode_dirty_sync(inode);
4411         mnt_drop_write(file->f_path.mnt);
4412         return ret;
4413 }
4414
4415 /*
4416  * find the highest existing sequence number in a directory
4417  * and then set the in-memory index_cnt variable to reflect
4418  * free sequence numbers
4419  */
4420 static int btrfs_set_inode_index_count(struct inode *inode)
4421 {
4422         struct btrfs_root *root = BTRFS_I(inode)->root;
4423         struct btrfs_key key, found_key;
4424         struct btrfs_path *path;
4425         struct extent_buffer *leaf;
4426         int ret;
4427
4428         key.objectid = btrfs_ino(inode);
4429         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4430         key.offset = (u64)-1;
4431
4432         path = btrfs_alloc_path();
4433         if (!path)
4434                 return -ENOMEM;
4435
4436         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4437         if (ret < 0)
4438                 goto out;
4439         /* FIXME: we should be able to handle this */
4440         if (ret == 0)
4441                 goto out;
4442         ret = 0;
4443
4444         /*
4445          * MAGIC NUMBER EXPLANATION:
4446          * since we search a directory based on f_pos we have to start at 2
4447          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4448          * else has to start at 2
4449          */
4450         if (path->slots[0] == 0) {
4451                 BTRFS_I(inode)->index_cnt = 2;
4452                 goto out;
4453         }
4454
4455         path->slots[0]--;
4456
4457         leaf = path->nodes[0];
4458         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4459
4460         if (found_key.objectid != btrfs_ino(inode) ||
4461             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4462                 BTRFS_I(inode)->index_cnt = 2;
4463                 goto out;
4464         }
4465
4466         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4467 out:
4468         btrfs_free_path(path);
4469         return ret;
4470 }
4471
4472 /*
4473  * helper to find a free sequence number in a given directory.  This current
4474  * code is very simple, later versions will do smarter things in the btree
4475  */
4476 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4477 {
4478         int ret = 0;
4479
4480         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4481                 ret = btrfs_inode_delayed_dir_index_count(dir);
4482                 if (ret) {
4483                         ret = btrfs_set_inode_index_count(dir);
4484                         if (ret)
4485                                 return ret;
4486                 }
4487         }
4488
4489         *index = BTRFS_I(dir)->index_cnt;
4490         BTRFS_I(dir)->index_cnt++;
4491
4492         return ret;
4493 }
4494
4495 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4496                                      struct btrfs_root *root,
4497                                      struct inode *dir,
4498                                      const char *name, int name_len,
4499                                      u64 ref_objectid, u64 objectid, int mode,
4500                                      u64 *index)
4501 {
4502         struct inode *inode;
4503         struct btrfs_inode_item *inode_item;
4504         struct btrfs_key *location;
4505         struct btrfs_path *path;
4506         struct btrfs_inode_ref *ref;
4507         struct btrfs_key key[2];
4508         u32 sizes[2];
4509         unsigned long ptr;
4510         int ret;
4511         int owner;
4512
4513         path = btrfs_alloc_path();
4514         if (!path)
4515                 return ERR_PTR(-ENOMEM);
4516
4517         inode = new_inode(root->fs_info->sb);
4518         if (!inode) {
4519                 btrfs_free_path(path);
4520                 return ERR_PTR(-ENOMEM);
4521         }
4522
4523         /*
4524          * we have to initialize this early, so we can reclaim the inode
4525          * number if we fail afterwards in this function.
4526          */
4527         inode->i_ino = objectid;
4528
4529         if (dir) {
4530                 trace_btrfs_inode_request(dir);
4531
4532                 ret = btrfs_set_inode_index(dir, index);
4533                 if (ret) {
4534                         btrfs_free_path(path);
4535                         iput(inode);
4536                         return ERR_PTR(ret);
4537                 }
4538         }
4539         /*
4540          * index_cnt is ignored for everything but a dir,
4541          * btrfs_get_inode_index_count has an explanation for the magic
4542          * number
4543          */
4544         BTRFS_I(inode)->index_cnt = 2;
4545         BTRFS_I(inode)->root = root;
4546         BTRFS_I(inode)->generation = trans->transid;
4547         inode->i_generation = BTRFS_I(inode)->generation;
4548         btrfs_set_inode_space_info(root, inode);
4549
4550         if (S_ISDIR(mode))
4551                 owner = 0;
4552         else
4553                 owner = 1;
4554
4555         key[0].objectid = objectid;
4556         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4557         key[0].offset = 0;
4558
4559         key[1].objectid = objectid;
4560         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4561         key[1].offset = ref_objectid;
4562
4563         sizes[0] = sizeof(struct btrfs_inode_item);
4564         sizes[1] = name_len + sizeof(*ref);
4565
4566         path->leave_spinning = 1;
4567         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4568         if (ret != 0)
4569                 goto fail;
4570
4571         inode_init_owner(inode, dir, mode);
4572         inode_set_bytes(inode, 0);
4573         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4574         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4575                                   struct btrfs_inode_item);
4576         fill_inode_item(trans, path->nodes[0], inode_item, inode);
4577
4578         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4579                              struct btrfs_inode_ref);
4580         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4581         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4582         ptr = (unsigned long)(ref + 1);
4583         write_extent_buffer(path->nodes[0], name, ptr, name_len);
4584
4585         btrfs_mark_buffer_dirty(path->nodes[0]);
4586         btrfs_free_path(path);
4587
4588         location = &BTRFS_I(inode)->location;
4589         location->objectid = objectid;
4590         location->offset = 0;
4591         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4592
4593         btrfs_inherit_iflags(inode, dir);
4594
4595         if (S_ISREG(mode)) {
4596                 if (btrfs_test_opt(root, NODATASUM))
4597                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4598                 if (btrfs_test_opt(root, NODATACOW) ||
4599                     (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
4600                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4601         }
4602
4603         insert_inode_hash(inode);
4604         inode_tree_add(inode);
4605
4606         trace_btrfs_inode_new(inode);
4607         btrfs_set_inode_last_trans(trans, inode);
4608
4609         return inode;
4610 fail:
4611         if (dir)
4612                 BTRFS_I(dir)->index_cnt--;
4613         btrfs_free_path(path);
4614         iput(inode);
4615         return ERR_PTR(ret);
4616 }
4617
4618 static inline u8 btrfs_inode_type(struct inode *inode)
4619 {
4620         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4621 }
4622
4623 /*
4624  * utility function to add 'inode' into 'parent_inode' with
4625  * a give name and a given sequence number.
4626  * if 'add_backref' is true, also insert a backref from the
4627  * inode to the parent directory.
4628  */
4629 int btrfs_add_link(struct btrfs_trans_handle *trans,
4630                    struct inode *parent_inode, struct inode *inode,
4631                    const char *name, int name_len, int add_backref, u64 index)
4632 {
4633         int ret = 0;
4634         struct btrfs_key key;
4635         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4636         u64 ino = btrfs_ino(inode);
4637         u64 parent_ino = btrfs_ino(parent_inode);
4638
4639         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4640                 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4641         } else {
4642                 key.objectid = ino;
4643                 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4644                 key.offset = 0;
4645         }
4646
4647         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4648                 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4649                                          key.objectid, root->root_key.objectid,
4650                                          parent_ino, index, name, name_len);
4651         } else if (add_backref) {
4652                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4653                                              parent_ino, index);
4654         }
4655
4656         if (ret == 0) {
4657                 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4658                                             parent_inode, &key,
4659                                             btrfs_inode_type(inode), index);
4660                 BUG_ON(ret);
4661
4662                 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4663                                    name_len * 2);
4664                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4665                 ret = btrfs_update_inode(trans, root, parent_inode);
4666         }
4667         return ret;
4668 }
4669
4670 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4671                             struct inode *dir, struct dentry *dentry,
4672                             struct inode *inode, int backref, u64 index)
4673 {
4674         int err = btrfs_add_link(trans, dir, inode,
4675                                  dentry->d_name.name, dentry->d_name.len,
4676                                  backref, index);
4677         if (err > 0)
4678                 err = -EEXIST;
4679         return err;
4680 }
4681
4682 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4683                         int mode, dev_t rdev)
4684 {
4685         struct btrfs_trans_handle *trans;
4686         struct btrfs_root *root = BTRFS_I(dir)->root;
4687         struct inode *inode = NULL;
4688         int err;
4689         int drop_inode = 0;
4690         u64 objectid;
4691         unsigned long nr = 0;
4692         u64 index = 0;
4693
4694         if (!new_valid_dev(rdev))
4695                 return -EINVAL;
4696
4697         /*
4698          * 2 for inode item and ref
4699          * 2 for dir items
4700          * 1 for xattr if selinux is on
4701          */
4702         trans = btrfs_start_transaction(root, 5);
4703         if (IS_ERR(trans))
4704                 return PTR_ERR(trans);
4705
4706         err = btrfs_find_free_ino(root, &objectid);
4707         if (err)
4708                 goto out_unlock;
4709
4710         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4711                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4712                                 mode, &index);
4713         if (IS_ERR(inode)) {
4714                 err = PTR_ERR(inode);
4715                 goto out_unlock;
4716         }
4717
4718         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4719         if (err) {
4720                 drop_inode = 1;
4721                 goto out_unlock;
4722         }
4723
4724         /*
4725         * If the active LSM wants to access the inode during
4726         * d_instantiate it needs these. Smack checks to see
4727         * if the filesystem supports xattrs by looking at the
4728         * ops vector.
4729         */
4730
4731         inode->i_op = &btrfs_special_inode_operations;
4732         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4733         if (err)
4734                 drop_inode = 1;
4735         else {
4736                 init_special_inode(inode, inode->i_mode, rdev);
4737                 btrfs_update_inode(trans, root, inode);
4738                 d_instantiate(dentry, inode);
4739         }
4740 out_unlock:
4741         nr = trans->blocks_used;
4742         btrfs_end_transaction_throttle(trans, root);
4743         btrfs_btree_balance_dirty(root, nr);
4744         if (drop_inode) {
4745                 inode_dec_link_count(inode);
4746                 iput(inode);
4747         }
4748         return err;
4749 }
4750
4751 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4752                         int mode, struct nameidata *nd)
4753 {
4754         struct btrfs_trans_handle *trans;
4755         struct btrfs_root *root = BTRFS_I(dir)->root;
4756         struct inode *inode = NULL;
4757         int drop_inode = 0;
4758         int err;
4759         unsigned long nr = 0;
4760         u64 objectid;
4761         u64 index = 0;
4762
4763         /*
4764          * 2 for inode item and ref
4765          * 2 for dir items
4766          * 1 for xattr if selinux is on
4767          */
4768         trans = btrfs_start_transaction(root, 5);
4769         if (IS_ERR(trans))
4770                 return PTR_ERR(trans);
4771
4772         err = btrfs_find_free_ino(root, &objectid);
4773         if (err)
4774                 goto out_unlock;
4775
4776         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4777                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4778                                 mode, &index);
4779         if (IS_ERR(inode)) {
4780                 err = PTR_ERR(inode);
4781                 goto out_unlock;
4782         }
4783
4784         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4785         if (err) {
4786                 drop_inode = 1;
4787                 goto out_unlock;
4788         }
4789
4790         /*
4791         * If the active LSM wants to access the inode during
4792         * d_instantiate it needs these. Smack checks to see
4793         * if the filesystem supports xattrs by looking at the
4794         * ops vector.
4795         */
4796         inode->i_fop = &btrfs_file_operations;
4797         inode->i_op = &btrfs_file_inode_operations;
4798
4799         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4800         if (err)
4801                 drop_inode = 1;
4802         else {
4803                 inode->i_mapping->a_ops = &btrfs_aops;
4804                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4805                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4806                 d_instantiate(dentry, inode);
4807         }
4808 out_unlock:
4809         nr = trans->blocks_used;
4810         btrfs_end_transaction_throttle(trans, root);
4811         if (drop_inode) {
4812                 inode_dec_link_count(inode);
4813                 iput(inode);
4814         }
4815         btrfs_btree_balance_dirty(root, nr);
4816         return err;
4817 }
4818
4819 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4820                       struct dentry *dentry)
4821 {
4822         struct btrfs_trans_handle *trans;
4823         struct btrfs_root *root = BTRFS_I(dir)->root;
4824         struct inode *inode = old_dentry->d_inode;
4825         u64 index;
4826         unsigned long nr = 0;
4827         int err;
4828         int drop_inode = 0;
4829
4830         /* do not allow sys_link's with other subvols of the same device */
4831         if (root->objectid != BTRFS_I(inode)->root->objectid)
4832                 return -EXDEV;
4833
4834         if (inode->i_nlink == ~0U)
4835                 return -EMLINK;
4836
4837         err = btrfs_set_inode_index(dir, &index);
4838         if (err)
4839                 goto fail;
4840
4841         /*
4842          * 2 items for inode and inode ref
4843          * 2 items for dir items
4844          * 1 item for parent inode
4845          */
4846         trans = btrfs_start_transaction(root, 5);
4847         if (IS_ERR(trans)) {
4848                 err = PTR_ERR(trans);
4849                 goto fail;
4850         }
4851
4852         btrfs_inc_nlink(inode);
4853         inode->i_ctime = CURRENT_TIME;
4854         ihold(inode);
4855
4856         err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
4857
4858         if (err) {
4859                 drop_inode = 1;
4860         } else {
4861                 struct dentry *parent = dentry->d_parent;
4862                 err = btrfs_update_inode(trans, root, inode);
4863                 BUG_ON(err);
4864                 d_instantiate(dentry, inode);
4865                 btrfs_log_new_name(trans, inode, NULL, parent);
4866         }
4867
4868         nr = trans->blocks_used;
4869         btrfs_end_transaction_throttle(trans, root);
4870 fail:
4871         if (drop_inode) {
4872                 inode_dec_link_count(inode);
4873                 iput(inode);
4874         }
4875         btrfs_btree_balance_dirty(root, nr);
4876         return err;
4877 }
4878
4879 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4880 {
4881         struct inode *inode = NULL;
4882         struct btrfs_trans_handle *trans;
4883         struct btrfs_root *root = BTRFS_I(dir)->root;
4884         int err = 0;
4885         int drop_on_err = 0;
4886         u64 objectid = 0;
4887         u64 index = 0;
4888         unsigned long nr = 1;
4889
4890         /*
4891          * 2 items for inode and ref
4892          * 2 items for dir items
4893          * 1 for xattr if selinux is on
4894          */
4895         trans = btrfs_start_transaction(root, 5);
4896         if (IS_ERR(trans))
4897                 return PTR_ERR(trans);
4898
4899         err = btrfs_find_free_ino(root, &objectid);
4900         if (err)
4901                 goto out_fail;
4902
4903         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4904                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4905                                 S_IFDIR | mode, &index);
4906         if (IS_ERR(inode)) {
4907                 err = PTR_ERR(inode);
4908                 goto out_fail;
4909         }
4910
4911         drop_on_err = 1;
4912
4913         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4914         if (err)
4915                 goto out_fail;
4916
4917         inode->i_op = &btrfs_dir_inode_operations;
4918         inode->i_fop = &btrfs_dir_file_operations;
4919
4920         btrfs_i_size_write(inode, 0);
4921         err = btrfs_update_inode(trans, root, inode);
4922         if (err)
4923                 goto out_fail;
4924
4925         err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4926                              dentry->d_name.len, 0, index);
4927         if (err)
4928                 goto out_fail;
4929
4930         d_instantiate(dentry, inode);
4931         drop_on_err = 0;
4932
4933 out_fail:
4934         nr = trans->blocks_used;
4935         btrfs_end_transaction_throttle(trans, root);
4936         if (drop_on_err)
4937                 iput(inode);
4938         btrfs_btree_balance_dirty(root, nr);
4939         return err;
4940 }
4941
4942 /* helper for btfs_get_extent.  Given an existing extent in the tree,
4943  * and an extent that you want to insert, deal with overlap and insert
4944  * the new extent into the tree.
4945  */
4946 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4947                                 struct extent_map *existing,
4948                                 struct extent_map *em,
4949                                 u64 map_start, u64 map_len)
4950 {
4951         u64 start_diff;
4952
4953         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4954         start_diff = map_start - em->start;
4955         em->start = map_start;
4956         em->len = map_len;
4957         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4958             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4959                 em->block_start += start_diff;
4960                 em->block_len -= start_diff;
4961         }
4962         return add_extent_mapping(em_tree, em);
4963 }
4964
4965 static noinline int uncompress_inline(struct btrfs_path *path,
4966                                       struct inode *inode, struct page *page,
4967                                       size_t pg_offset, u64 extent_offset,
4968                                       struct btrfs_file_extent_item *item)
4969 {
4970         int ret;
4971         struct extent_buffer *leaf = path->nodes[0];
4972         char *tmp;
4973         size_t max_size;
4974         unsigned long inline_size;
4975         unsigned long ptr;
4976         int compress_type;
4977
4978         WARN_ON(pg_offset != 0);
4979         compress_type = btrfs_file_extent_compression(leaf, item);
4980         max_size = btrfs_file_extent_ram_bytes(leaf, item);
4981         inline_size = btrfs_file_extent_inline_item_len(leaf,
4982                                         btrfs_item_nr(leaf, path->slots[0]));
4983         tmp = kmalloc(inline_size, GFP_NOFS);
4984         if (!tmp)
4985                 return -ENOMEM;
4986         ptr = btrfs_file_extent_inline_start(item);
4987
4988         read_extent_buffer(leaf, tmp, ptr, inline_size);
4989
4990         max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4991         ret = btrfs_decompress(compress_type, tmp, page,
4992                                extent_offset, inline_size, max_size);
4993         if (ret) {
4994                 char *kaddr = kmap_atomic(page, KM_USER0);
4995                 unsigned long copy_size = min_t(u64,
4996                                   PAGE_CACHE_SIZE - pg_offset,
4997                                   max_size - extent_offset);
4998                 memset(kaddr + pg_offset, 0, copy_size);
4999                 kunmap_atomic(kaddr, KM_USER0);
5000         }
5001         kfree(tmp);
5002         return 0;
5003 }
5004
5005 /*
5006  * a bit scary, this does extent mapping from logical file offset to the disk.
5007  * the ugly parts come from merging extents from the disk with the in-ram
5008  * representation.  This gets more complex because of the data=ordered code,
5009  * where the in-ram extents might be locked pending data=ordered completion.
5010  *
5011  * This also copies inline extents directly into the page.
5012  */
5013
5014 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5015                                     size_t pg_offset, u64 start, u64 len,
5016                                     int create)
5017 {
5018         int ret;
5019         int err = 0;
5020         u64 bytenr;
5021         u64 extent_start = 0;
5022         u64 extent_end = 0;
5023         u64 objectid = btrfs_ino(inode);
5024         u32 found_type;
5025         struct btrfs_path *path = NULL;
5026         struct btrfs_root *root = BTRFS_I(inode)->root;
5027         struct btrfs_file_extent_item *item;
5028         struct extent_buffer *leaf;
5029         struct btrfs_key found_key;
5030         struct extent_map *em = NULL;
5031         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5032         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5033         struct btrfs_trans_handle *trans = NULL;
5034         int compress_type;
5035
5036 again:
5037         read_lock(&em_tree->lock);
5038         em = lookup_extent_mapping(em_tree, start, len);
5039         if (em)
5040                 em->bdev = root->fs_info->fs_devices->latest_bdev;
5041         read_unlock(&em_tree->lock);
5042
5043         if (em) {
5044                 if (em->start > start || em->start + em->len <= start)
5045                         free_extent_map(em);
5046                 else if (em->block_start == EXTENT_MAP_INLINE && page)
5047                         free_extent_map(em);
5048                 else
5049                         goto out;
5050         }
5051         em = alloc_extent_map();
5052         if (!em) {
5053                 err = -ENOMEM;
5054                 goto out;
5055         }
5056         em->bdev = root->fs_info->fs_devices->latest_bdev;
5057         em->start = EXTENT_MAP_HOLE;
5058         em->orig_start = EXTENT_MAP_HOLE;
5059         em->len = (u64)-1;
5060         em->block_len = (u64)-1;
5061
5062         if (!path) {
5063                 path = btrfs_alloc_path();
5064                 if (!path) {
5065                         err = -ENOMEM;
5066                         goto out;
5067                 }
5068                 /*
5069                  * Chances are we'll be called again, so go ahead and do
5070                  * readahead
5071                  */
5072                 path->reada = 1;
5073         }
5074
5075         ret = btrfs_lookup_file_extent(trans, root, path,
5076                                        objectid, start, trans != NULL);
5077         if (ret < 0) {
5078                 err = ret;
5079                 goto out;
5080         }
5081
5082         if (ret != 0) {
5083                 if (path->slots[0] == 0)
5084                         goto not_found;
5085                 path->slots[0]--;
5086         }
5087
5088         leaf = path->nodes[0];
5089         item = btrfs_item_ptr(leaf, path->slots[0],
5090                               struct btrfs_file_extent_item);
5091         /* are we inside the extent that was found? */
5092         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5093         found_type = btrfs_key_type(&found_key);
5094         if (found_key.objectid != objectid ||
5095             found_type != BTRFS_EXTENT_DATA_KEY) {
5096                 goto not_found;
5097         }
5098
5099         found_type = btrfs_file_extent_type(leaf, item);
5100         extent_start = found_key.offset;
5101         compress_type = btrfs_file_extent_compression(leaf, item);
5102         if (found_type == BTRFS_FILE_EXTENT_REG ||
5103             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5104                 extent_end = extent_start +
5105                        btrfs_file_extent_num_bytes(leaf, item);
5106         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5107                 size_t size;
5108                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
5109                 extent_end = (extent_start + size + root->sectorsize - 1) &
5110                         ~((u64)root->sectorsize - 1);
5111         }
5112
5113         if (start >= extent_end) {
5114                 path->slots[0]++;
5115                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5116                         ret = btrfs_next_leaf(root, path);
5117                         if (ret < 0) {
5118                                 err = ret;
5119                                 goto out;
5120                         }
5121                         if (ret > 0)
5122                                 goto not_found;
5123                         leaf = path->nodes[0];
5124                 }
5125                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5126                 if (found_key.objectid != objectid ||
5127                     found_key.type != BTRFS_EXTENT_DATA_KEY)
5128                         goto not_found;
5129                 if (start + len <= found_key.offset)
5130                         goto not_found;
5131                 em->start = start;
5132                 em->len = found_key.offset - start;
5133                 goto not_found_em;
5134         }
5135
5136         if (found_type == BTRFS_FILE_EXTENT_REG ||
5137             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5138                 em->start = extent_start;
5139                 em->len = extent_end - extent_start;
5140                 em->orig_start = extent_start -
5141                                  btrfs_file_extent_offset(leaf, item);
5142                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5143                 if (bytenr == 0) {
5144                         em->block_start = EXTENT_MAP_HOLE;
5145                         goto insert;
5146                 }
5147                 if (compress_type != BTRFS_COMPRESS_NONE) {
5148                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5149                         em->compress_type = compress_type;
5150                         em->block_start = bytenr;
5151                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5152                                                                          item);
5153                 } else {
5154                         bytenr += btrfs_file_extent_offset(leaf, item);
5155                         em->block_start = bytenr;
5156                         em->block_len = em->len;
5157                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5158                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5159                 }
5160                 goto insert;
5161         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5162                 unsigned long ptr;
5163                 char *map;
5164                 size_t size;
5165                 size_t extent_offset;
5166                 size_t copy_size;
5167
5168                 em->block_start = EXTENT_MAP_INLINE;
5169                 if (!page || create) {
5170                         em->start = extent_start;
5171                         em->len = extent_end - extent_start;
5172                         goto out;
5173                 }
5174
5175                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
5176                 extent_offset = page_offset(page) + pg_offset - extent_start;
5177                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5178                                 size - extent_offset);
5179                 em->start = extent_start + extent_offset;
5180                 em->len = (copy_size + root->sectorsize - 1) &
5181                         ~((u64)root->sectorsize - 1);
5182                 em->orig_start = EXTENT_MAP_INLINE;
5183                 if (compress_type) {
5184                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5185                         em->compress_type = compress_type;
5186                 }
5187                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5188                 if (create == 0 && !PageUptodate(page)) {
5189                         if (btrfs_file_extent_compression(leaf, item) !=
5190                             BTRFS_COMPRESS_NONE) {
5191                                 ret = uncompress_inline(path, inode, page,
5192                                                         pg_offset,
5193                                                         extent_offset, item);
5194                                 BUG_ON(ret);
5195                         } else {
5196                                 map = kmap(page);
5197                                 read_extent_buffer(leaf, map + pg_offset, ptr,
5198                                                    copy_size);
5199                                 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5200                                         memset(map + pg_offset + copy_size, 0,
5201                                                PAGE_CACHE_SIZE - pg_offset -
5202                                                copy_size);
5203                                 }
5204                                 kunmap(page);
5205                         }
5206                         flush_dcache_page(page);
5207                 } else if (create && PageUptodate(page)) {
5208                         WARN_ON(1);
5209                         if (!trans) {
5210                                 kunmap(page);
5211                                 free_extent_map(em);
5212                                 em = NULL;
5213
5214                                 btrfs_release_path(path);
5215                                 trans = btrfs_join_transaction(root);
5216
5217                                 if (IS_ERR(trans))
5218                                         return ERR_CAST(trans);
5219                                 goto again;
5220                         }
5221                         map = kmap(page);
5222                         write_extent_buffer(leaf, map + pg_offset, ptr,
5223                                             copy_size);
5224                         kunmap(page);
5225                         btrfs_mark_buffer_dirty(leaf);
5226                 }
5227                 set_extent_uptodate(io_tree, em->start,
5228                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
5229                 goto insert;
5230         } else {
5231                 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5232                 WARN_ON(1);
5233         }
5234 not_found:
5235         em->start = start;
5236         em->len = len;
5237 not_found_em:
5238         em->block_start = EXTENT_MAP_HOLE;
5239         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5240 insert:
5241         btrfs_release_path(path);
5242         if (em->start > start || extent_map_end(em) <= start) {
5243                 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5244                        "[%llu %llu]\n", (unsigned long long)em->start,
5245                        (unsigned long long)em->len,
5246                        (unsigned long long)start,
5247                        (unsigned long long)len);
5248                 err = -EIO;
5249                 goto out;
5250         }
5251
5252         err = 0;
5253         write_lock(&em_tree->lock);
5254         ret = add_extent_mapping(em_tree, em);
5255         /* it is possible that someone inserted the extent into the tree
5256          * while we had the lock dropped.  It is also possible that
5257          * an overlapping map exists in the tree
5258          */
5259         if (ret == -EEXIST) {
5260                 struct extent_map *existing;
5261
5262                 ret = 0;
5263
5264                 existing = lookup_extent_mapping(em_tree, start, len);
5265                 if (existing && (existing->start > start ||
5266                     existing->start + existing->len <= start)) {
5267                         free_extent_map(existing);
5268                         existing = NULL;
5269                 }
5270                 if (!existing) {
5271                         existing = lookup_extent_mapping(em_tree, em->start,
5272                                                          em->len);
5273                         if (existing) {
5274                                 err = merge_extent_mapping(em_tree, existing,
5275                                                            em, start,
5276                                                            root->sectorsize);
5277                                 free_extent_map(existing);
5278                                 if (err) {
5279                                         free_extent_map(em);
5280                                         em = NULL;
5281                                 }
5282                         } else {
5283                                 err = -EIO;
5284                                 free_extent_map(em);
5285                                 em = NULL;
5286                         }
5287                 } else {
5288                         free_extent_map(em);
5289                         em = existing;
5290                         err = 0;
5291                 }
5292         }
5293         write_unlock(&em_tree->lock);
5294 out:
5295
5296         trace_btrfs_get_extent(root, em);
5297
5298         if (path)
5299                 btrfs_free_path(path);
5300         if (trans) {
5301                 ret = btrfs_end_transaction(trans, root);
5302                 if (!err)
5303                         err = ret;
5304         }
5305         if (err) {
5306                 free_extent_map(em);
5307                 return ERR_PTR(err);
5308         }
5309         return em;
5310 }
5311
5312 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5313                                            size_t pg_offset, u64 start, u64 len,
5314                                            int create)
5315 {
5316         struct extent_map *em;
5317         struct extent_map *hole_em = NULL;
5318         u64 range_start = start;
5319         u64 end;
5320         u64 found;
5321         u64 found_end;
5322         int err = 0;
5323
5324         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5325         if (IS_ERR(em))
5326                 return em;
5327         if (em) {
5328                 /*
5329                  * if our em maps to a hole, there might
5330                  * actually be delalloc bytes behind it
5331                  */
5332                 if (em->block_start != EXTENT_MAP_HOLE)
5333                         return em;
5334                 else
5335                         hole_em = em;
5336         }
5337
5338         /* check to see if we've wrapped (len == -1 or similar) */
5339         end = start + len;
5340         if (end < start)
5341                 end = (u64)-1;
5342         else
5343                 end -= 1;
5344
5345         em = NULL;
5346
5347         /* ok, we didn't find anything, lets look for delalloc */
5348         found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5349                                  end, len, EXTENT_DELALLOC, 1);
5350         found_end = range_start + found;
5351         if (found_end < range_start)
5352                 found_end = (u64)-1;
5353
5354         /*
5355          * we didn't find anything useful, return
5356          * the original results from get_extent()
5357          */
5358         if (range_start > end || found_end <= start) {
5359                 em = hole_em;
5360                 hole_em = NULL;
5361                 goto out;
5362         }
5363
5364         /* adjust the range_start to make sure it doesn't
5365          * go backwards from the start they passed in
5366          */
5367         range_start = max(start,range_start);
5368         found = found_end - range_start;
5369
5370         if (found > 0) {
5371                 u64 hole_start = start;
5372                 u64 hole_len = len;
5373
5374                 em = alloc_extent_map();
5375                 if (!em) {
5376                         err = -ENOMEM;
5377                         goto out;
5378                 }
5379                 /*
5380                  * when btrfs_get_extent can't find anything it
5381                  * returns one huge hole
5382                  *
5383                  * make sure what it found really fits our range, and
5384                  * adjust to make sure it is based on the start from
5385                  * the caller
5386                  */
5387                 if (hole_em) {
5388                         u64 calc_end = extent_map_end(hole_em);
5389
5390                         if (calc_end <= start || (hole_em->start > end)) {
5391                                 free_extent_map(hole_em);
5392                                 hole_em = NULL;
5393                         } else {
5394                                 hole_start = max(hole_em->start, start);
5395                                 hole_len = calc_end - hole_start;
5396                         }
5397                 }
5398                 em->bdev = NULL;
5399                 if (hole_em && range_start > hole_start) {
5400                         /* our hole starts before our delalloc, so we
5401                          * have to return just the parts of the hole
5402                          * that go until  the delalloc starts
5403                          */
5404                         em->len = min(hole_len,
5405                                       range_start - hole_start);
5406                         em->start = hole_start;
5407                         em->orig_start = hole_start;
5408                         /*
5409                          * don't adjust block start at all,
5410                          * it is fixed at EXTENT_MAP_HOLE
5411                          */
5412                         em->block_start = hole_em->block_start;
5413                         em->block_len = hole_len;
5414                 } else {
5415                         em->start = range_start;
5416                         em->len = found;
5417                         em->orig_start = range_start;
5418                         em->block_start = EXTENT_MAP_DELALLOC;
5419                         em->block_len = found;
5420                 }
5421         } else if (hole_em) {
5422                 return hole_em;
5423         }
5424 out:
5425
5426         free_extent_map(hole_em);
5427         if (err) {
5428                 free_extent_map(em);
5429                 return ERR_PTR(err);
5430         }
5431         return em;
5432 }
5433
5434 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5435                                                   struct extent_map *em,
5436                                                   u64 start, u64 len)
5437 {
5438         struct btrfs_root *root = BTRFS_I(inode)->root;
5439         struct btrfs_trans_handle *trans;
5440         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5441         struct btrfs_key ins;
5442         u64 alloc_hint;
5443         int ret;
5444         bool insert = false;
5445
5446         /*
5447          * Ok if the extent map we looked up is a hole and is for the exact
5448          * range we want, there is no reason to allocate a new one, however if
5449          * it is not right then we need to free this one and drop the cache for
5450          * our range.
5451          */
5452         if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
5453             em->len != len) {
5454                 free_extent_map(em);
5455                 em = NULL;
5456                 insert = true;
5457                 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5458         }
5459
5460         trans = btrfs_join_transaction(root);
5461         if (IS_ERR(trans))
5462                 return ERR_CAST(trans);
5463
5464         if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
5465                 btrfs_add_inode_defrag(trans, inode);
5466
5467         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5468
5469         alloc_hint = get_extent_allocation_hint(inode, start, len);
5470         ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5471                                    alloc_hint, (u64)-1, &ins, 1);
5472         if (ret) {
5473                 em = ERR_PTR(ret);
5474                 goto out;
5475         }
5476
5477         if (!em) {
5478                 em = alloc_extent_map();
5479                 if (!em) {
5480                         em = ERR_PTR(-ENOMEM);
5481                         goto out;
5482                 }
5483         }
5484
5485         em->start = start;
5486         em->orig_start = em->start;
5487         em->len = ins.offset;
5488
5489         em->block_start = ins.objectid;
5490         em->block_len = ins.offset;
5491         em->bdev = root->fs_info->fs_devices->latest_bdev;
5492
5493         /*
5494          * We need to do this because if we're using the original em we searched
5495          * for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
5496          */
5497         em->flags = 0;
5498         set_bit(EXTENT_FLAG_PINNED, &em->flags);
5499
5500         while (insert) {
5501                 write_lock(&em_tree->lock);
5502                 ret = add_extent_mapping(em_tree, em);
5503                 write_unlock(&em_tree->lock);
5504                 if (ret != -EEXIST)
5505                         break;
5506                 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5507         }
5508
5509         ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5510                                            ins.offset, ins.offset, 0);
5511         if (ret) {
5512                 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5513                 em = ERR_PTR(ret);
5514         }
5515 out:
5516         btrfs_end_transaction(trans, root);
5517         return em;
5518 }
5519
5520 /*
5521  * returns 1 when the nocow is safe, < 1 on error, 0 if the
5522  * block must be cow'd
5523  */
5524 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5525                                       struct inode *inode, u64 offset, u64 len)
5526 {
5527         struct btrfs_path *path;
5528         int ret;
5529         struct extent_buffer *leaf;
5530         struct btrfs_root *root = BTRFS_I(inode)->root;
5531         struct btrfs_file_extent_item *fi;
5532         struct btrfs_key key;
5533         u64 disk_bytenr;
5534         u64 backref_offset;
5535         u64 extent_end;
5536         u64 num_bytes;
5537         int slot;
5538         int found_type;
5539
5540         path = btrfs_alloc_path();
5541         if (!path)
5542                 return -ENOMEM;
5543
5544         ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5545                                        offset, 0);
5546         if (ret < 0)
5547                 goto out;
5548
5549         slot = path->slots[0];
5550         if (ret == 1) {
5551                 if (slot == 0) {
5552                         /* can't find the item, must cow */
5553                         ret = 0;
5554                         goto out;
5555                 }
5556                 slot--;
5557         }
5558         ret = 0;
5559         leaf = path->nodes[0];
5560         btrfs_item_key_to_cpu(leaf, &key, slot);
5561         if (key.objectid != btrfs_ino(inode) ||
5562             key.type != BTRFS_EXTENT_DATA_KEY) {
5563                 /* not our file or wrong item type, must cow */
5564                 goto out;
5565         }
5566
5567         if (key.offset > offset) {
5568                 /* Wrong offset, must cow */
5569                 goto out;
5570         }
5571
5572         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5573         found_type = btrfs_file_extent_type(leaf, fi);
5574         if (found_type != BTRFS_FILE_EXTENT_REG &&
5575             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5576                 /* not a regular extent, must cow */
5577                 goto out;
5578         }
5579         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5580         backref_offset = btrfs_file_extent_offset(leaf, fi);
5581
5582         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5583         if (extent_end < offset + len) {
5584                 /* extent doesn't include our full range, must cow */
5585                 goto out;
5586         }
5587
5588         if (btrfs_extent_readonly(root, disk_bytenr))
5589                 goto out;
5590
5591         /*
5592          * look for other files referencing this extent, if we
5593          * find any we must cow
5594          */
5595         if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5596                                   key.offset - backref_offset, disk_bytenr))
5597                 goto out;
5598
5599         /*
5600          * adjust disk_bytenr and num_bytes to cover just the bytes
5601          * in this extent we are about to write.  If there
5602          * are any csums in that range we have to cow in order
5603          * to keep the csums correct
5604          */
5605         disk_bytenr += backref_offset;
5606         disk_bytenr += offset - key.offset;
5607         num_bytes = min(offset + len, extent_end) - offset;
5608         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5609                                 goto out;
5610         /*
5611          * all of the above have passed, it is safe to overwrite this extent
5612          * without cow
5613          */
5614         ret = 1;
5615 out:
5616         btrfs_free_path(path);
5617         return ret;
5618 }
5619
5620 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5621                                    struct buffer_head *bh_result, int create)
5622 {
5623         struct extent_map *em;
5624         struct btrfs_root *root = BTRFS_I(inode)->root;
5625         u64 start = iblock << inode->i_blkbits;
5626         u64 len = bh_result->b_size;
5627         struct btrfs_trans_handle *trans;
5628
5629         em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5630         if (IS_ERR(em))
5631                 return PTR_ERR(em);
5632
5633         /*
5634          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5635          * io.  INLINE is special, and we could probably kludge it in here, but
5636          * it's still buffered so for safety lets just fall back to the generic
5637          * buffered path.
5638          *
5639          * For COMPRESSED we _have_ to read the entire extent in so we can
5640          * decompress it, so there will be buffering required no matter what we
5641          * do, so go ahead and fallback to buffered.
5642          *
5643          * We return -ENOTBLK because thats what makes DIO go ahead and go back
5644          * to buffered IO.  Don't blame me, this is the price we pay for using
5645          * the generic code.
5646          */
5647         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5648             em->block_start == EXTENT_MAP_INLINE) {
5649                 free_extent_map(em);
5650                 return -ENOTBLK;
5651         }
5652
5653         /* Just a good old fashioned hole, return */
5654         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5655                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5656                 free_extent_map(em);
5657                 /* DIO will do one hole at a time, so just unlock a sector */
5658                 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5659                               start + root->sectorsize - 1, GFP_NOFS);
5660                 return 0;
5661         }
5662
5663         /*
5664          * We don't allocate a new extent in the following cases
5665          *
5666          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
5667          * existing extent.
5668          * 2) The extent is marked as PREALLOC.  We're good to go here and can
5669          * just use the extent.
5670          *
5671          */
5672         if (!create) {
5673                 len = em->len - (start - em->start);
5674                 goto map;
5675         }
5676
5677         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5678             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5679              em->block_start != EXTENT_MAP_HOLE)) {
5680                 int type;
5681                 int ret;
5682                 u64 block_start;
5683
5684                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5685                         type = BTRFS_ORDERED_PREALLOC;
5686                 else
5687                         type = BTRFS_ORDERED_NOCOW;
5688                 len = min(len, em->len - (start - em->start));
5689                 block_start = em->block_start + (start - em->start);
5690
5691                 /*
5692                  * we're not going to log anything, but we do need
5693                  * to make sure the current transaction stays open
5694                  * while we look for nocow cross refs
5695                  */
5696                 trans = btrfs_join_transaction(root);
5697                 if (IS_ERR(trans))
5698                         goto must_cow;
5699
5700                 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5701                         ret = btrfs_add_ordered_extent_dio(inode, start,
5702                                            block_start, len, len, type);
5703                         btrfs_end_transaction(trans, root);
5704                         if (ret) {
5705                                 free_extent_map(em);
5706                                 return ret;
5707                         }
5708                         goto unlock;
5709                 }
5710                 btrfs_end_transaction(trans, root);
5711         }
5712 must_cow:
5713         /*
5714          * this will cow the extent, reset the len in case we changed
5715          * it above
5716          */
5717         len = bh_result->b_size;
5718         em = btrfs_new_extent_direct(inode, em, start, len);
5719         if (IS_ERR(em))
5720                 return PTR_ERR(em);
5721         len = min(len, em->len - (start - em->start));
5722 unlock:
5723         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5724                           EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5725                           0, NULL, GFP_NOFS);
5726 map:
5727         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5728                 inode->i_blkbits;
5729         bh_result->b_size = len;
5730         bh_result->b_bdev = em->bdev;
5731         set_buffer_mapped(bh_result);
5732         if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5733                 set_buffer_new(bh_result);
5734
5735         free_extent_map(em);
5736
5737         return 0;
5738 }
5739
5740 struct btrfs_dio_private {
5741         struct inode *inode;
5742         u64 logical_offset;
5743         u64 disk_bytenr;
5744         u64 bytes;
5745         u32 *csums;
5746         void *private;
5747
5748         /* number of bios pending for this dio */
5749         atomic_t pending_bios;
5750
5751         /* IO errors */
5752         int errors;
5753
5754         struct bio *orig_bio;
5755 };
5756
5757 static void btrfs_endio_direct_read(struct bio *bio, int err)
5758 {
5759         struct btrfs_dio_private *dip = bio->bi_private;
5760         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5761         struct bio_vec *bvec = bio->bi_io_vec;
5762         struct inode *inode = dip->inode;
5763         struct btrfs_root *root = BTRFS_I(inode)->root;
5764         u64 start;
5765         u32 *private = dip->csums;
5766
5767         start = dip->logical_offset;
5768         do {
5769                 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5770                         struct page *page = bvec->bv_page;
5771                         char *kaddr;
5772                         u32 csum = ~(u32)0;
5773                         unsigned long flags;
5774
5775                         local_irq_save(flags);
5776                         kaddr = kmap_atomic(page, KM_IRQ0);
5777                         csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5778                                                csum, bvec->bv_len);
5779                         btrfs_csum_final(csum, (char *)&csum);
5780                         kunmap_atomic(kaddr, KM_IRQ0);
5781                         local_irq_restore(flags);
5782
5783                         flush_dcache_page(bvec->bv_page);
5784                         if (csum != *private) {
5785                                 printk(KERN_ERR "btrfs csum failed ino %llu off"
5786                                       " %llu csum %u private %u\n",
5787                                       (unsigned long long)btrfs_ino(inode),
5788                                       (unsigned long long)start,
5789                                       csum, *private);
5790                                 err = -EIO;
5791                         }
5792                 }
5793
5794                 start += bvec->bv_len;
5795                 private++;
5796                 bvec++;
5797         } while (bvec <= bvec_end);
5798
5799         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5800                       dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5801         bio->bi_private = dip->private;
5802
5803         kfree(dip->csums);
5804         kfree(dip);
5805
5806         /* If we had a csum failure make sure to clear the uptodate flag */
5807         if (err)
5808                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5809         dio_end_io(bio, err);
5810 }
5811
5812 static void btrfs_endio_direct_write(struct bio *bio, int err)
5813 {
5814         struct btrfs_dio_private *dip = bio->bi_private;
5815         struct inode *inode = dip->inode;
5816         struct btrfs_root *root = BTRFS_I(inode)->root;
5817         struct btrfs_trans_handle *trans;
5818         struct btrfs_ordered_extent *ordered = NULL;
5819         struct extent_state *cached_state = NULL;
5820         u64 ordered_offset = dip->logical_offset;
5821         u64 ordered_bytes = dip->bytes;
5822         int ret;
5823
5824         if (err)
5825                 goto out_done;
5826 again:
5827         ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5828                                                    &ordered_offset,
5829                                                    ordered_bytes);
5830         if (!ret)
5831                 goto out_test;
5832
5833         BUG_ON(!ordered);
5834
5835         trans = btrfs_join_transaction(root);
5836         if (IS_ERR(trans)) {
5837                 err = -ENOMEM;
5838                 goto out;
5839         }
5840         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5841
5842         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5843                 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5844                 if (!ret)
5845                         err = btrfs_update_inode_fallback(trans, root, inode);
5846                 goto out;
5847         }
5848
5849         lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5850                          ordered->file_offset + ordered->len - 1, 0,
5851                          &cached_state, GFP_NOFS);
5852
5853         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5854                 ret = btrfs_mark_extent_written(trans, inode,
5855                                                 ordered->file_offset,
5856                                                 ordered->file_offset +
5857                                                 ordered->len);
5858                 if (ret) {
5859                         err = ret;
5860                         goto out_unlock;
5861                 }
5862         } else {
5863                 ret = insert_reserved_file_extent(trans, inode,
5864                                                   ordered->file_offset,
5865                                                   ordered->start,
5866                                                   ordered->disk_len,
5867                                                   ordered->len,
5868                                                   ordered->len,
5869                                                   0, 0, 0,
5870                                                   BTRFS_FILE_EXTENT_REG);
5871                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5872                                    ordered->file_offset, ordered->len);
5873                 if (ret) {
5874                         err = ret;
5875                         WARN_ON(1);
5876                         goto out_unlock;
5877                 }
5878         }
5879
5880         add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5881         ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5882         if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags))
5883                 btrfs_update_inode_fallback(trans, root, inode);
5884         ret = 0;
5885 out_unlock:
5886         unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5887                              ordered->file_offset + ordered->len - 1,
5888                              &cached_state, GFP_NOFS);
5889 out:
5890         btrfs_delalloc_release_metadata(inode, ordered->len);
5891         btrfs_end_transaction(trans, root);
5892         ordered_offset = ordered->file_offset + ordered->len;
5893         btrfs_put_ordered_extent(ordered);
5894         btrfs_put_ordered_extent(ordered);
5895
5896 out_test:
5897         /*
5898          * our bio might span multiple ordered extents.  If we haven't
5899          * completed the accounting for the whole dio, go back and try again
5900          */
5901         if (ordered_offset < dip->logical_offset + dip->bytes) {
5902                 ordered_bytes = dip->logical_offset + dip->bytes -
5903                         ordered_offset;
5904                 goto again;
5905         }
5906 out_done:
5907         bio->bi_private = dip->private;
5908
5909         kfree(dip->csums);
5910         kfree(dip);
5911
5912         /* If we had an error make sure to clear the uptodate flag */
5913         if (err)
5914                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5915         dio_end_io(bio, err);
5916 }
5917
5918 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5919                                     struct bio *bio, int mirror_num,
5920                                     unsigned long bio_flags, u64 offset)
5921 {
5922         int ret;
5923         struct btrfs_root *root = BTRFS_I(inode)->root;
5924         ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5925         BUG_ON(ret);
5926         return 0;
5927 }
5928
5929 static void btrfs_end_dio_bio(struct bio *bio, int err)
5930 {
5931         struct btrfs_dio_private *dip = bio->bi_private;
5932
5933         if (err) {
5934                 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
5935                       "sector %#Lx len %u err no %d\n",
5936                       (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
5937                       (unsigned long long)bio->bi_sector, bio->bi_size, err);
5938                 dip->errors = 1;
5939
5940                 /*
5941                  * before atomic variable goto zero, we must make sure
5942                  * dip->errors is perceived to be set.
5943                  */
5944                 smp_mb__before_atomic_dec();
5945         }
5946
5947         /* if there are more bios still pending for this dio, just exit */
5948         if (!atomic_dec_and_test(&dip->pending_bios))
5949                 goto out;
5950
5951         if (dip->errors)
5952                 bio_io_error(dip->orig_bio);
5953         else {
5954                 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5955                 bio_endio(dip->orig_bio, 0);
5956         }
5957 out:
5958         bio_put(bio);
5959 }
5960
5961 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5962                                        u64 first_sector, gfp_t gfp_flags)
5963 {
5964         int nr_vecs = bio_get_nr_vecs(bdev);
5965         return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5966 }
5967
5968 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5969                                          int rw, u64 file_offset, int skip_sum,
5970                                          u32 *csums, int async_submit)
5971 {
5972         int write = rw & REQ_WRITE;
5973         struct btrfs_root *root = BTRFS_I(inode)->root;
5974         int ret;
5975
5976         bio_get(bio);
5977         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5978         if (ret)
5979                 goto err;
5980
5981         if (skip_sum)
5982                 goto map;
5983
5984         if (write && async_submit) {
5985                 ret = btrfs_wq_submit_bio(root->fs_info,
5986                                    inode, rw, bio, 0, 0,
5987                                    file_offset,
5988                                    __btrfs_submit_bio_start_direct_io,
5989                                    __btrfs_submit_bio_done);
5990                 goto err;
5991         } else if (write) {
5992                 /*
5993                  * If we aren't doing async submit, calculate the csum of the
5994                  * bio now.
5995                  */
5996                 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
5997                 if (ret)
5998                         goto err;
5999         } else if (!skip_sum) {
6000                 ret = btrfs_lookup_bio_sums_dio(root, inode, bio,
6001                                           file_offset, csums);
6002                 if (ret)
6003                         goto err;
6004         }
6005
6006 map:
6007         ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6008 err:
6009         bio_put(bio);
6010         return ret;
6011 }
6012
6013 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6014                                     int skip_sum)
6015 {
6016         struct inode *inode = dip->inode;
6017         struct btrfs_root *root = BTRFS_I(inode)->root;
6018         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
6019         struct bio *bio;
6020         struct bio *orig_bio = dip->orig_bio;
6021         struct bio_vec *bvec = orig_bio->bi_io_vec;
6022         u64 start_sector = orig_bio->bi_sector;
6023         u64 file_offset = dip->logical_offset;
6024         u64 submit_len = 0;
6025         u64 map_length;
6026         int nr_pages = 0;
6027         u32 *csums = dip->csums;
6028         int ret = 0;
6029         int async_submit = 0;
6030         int write = rw & REQ_WRITE;
6031
6032         map_length = orig_bio->bi_size;
6033         ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6034                               &map_length, NULL, 0);
6035         if (ret) {
6036                 bio_put(orig_bio);
6037                 return -EIO;
6038         }
6039
6040         if (map_length >= orig_bio->bi_size) {
6041                 bio = orig_bio;
6042                 goto submit;
6043         }
6044
6045         async_submit = 1;
6046         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
6047         if (!bio)
6048                 return -ENOMEM;
6049         bio->bi_private = dip;
6050         bio->bi_end_io = btrfs_end_dio_bio;
6051         atomic_inc(&dip->pending_bios);
6052
6053         while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
6054                 if (unlikely(map_length < submit_len + bvec->bv_len ||
6055                     bio_add_page(bio, bvec->bv_page, bvec->bv_len,
6056                                  bvec->bv_offset) < bvec->bv_len)) {
6057                         /*
6058                          * inc the count before we submit the bio so
6059                          * we know the end IO handler won't happen before
6060                          * we inc the count. Otherwise, the dip might get freed
6061                          * before we're done setting it up
6062                          */
6063                         atomic_inc(&dip->pending_bios);
6064                         ret = __btrfs_submit_dio_bio(bio, inode, rw,
6065                                                      file_offset, skip_sum,
6066                                                      csums, async_submit);
6067                         if (ret) {
6068                                 bio_put(bio);
6069                                 atomic_dec(&dip->pending_bios);
6070                                 goto out_err;
6071                         }
6072
6073                         /* Write's use the ordered csums */
6074                         if (!write && !skip_sum)
6075                                 csums = csums + nr_pages;
6076                         start_sector += submit_len >> 9;
6077                         file_offset += submit_len;
6078
6079                         submit_len = 0;
6080                         nr_pages = 0;
6081
6082                         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6083                                                   start_sector, GFP_NOFS);
6084                         if (!bio)
6085                                 goto out_err;
6086                         bio->bi_private = dip;
6087                         bio->bi_end_io = btrfs_end_dio_bio;
6088
6089                         map_length = orig_bio->bi_size;
6090                         ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6091                                               &map_length, NULL, 0);
6092                         if (ret) {
6093                                 bio_put(bio);
6094                                 goto out_err;
6095                         }
6096                 } else {
6097                         submit_len += bvec->bv_len;
6098                         nr_pages ++;
6099                         bvec++;
6100                 }
6101         }
6102
6103 submit:
6104         ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6105                                      csums, async_submit);
6106         if (!ret)
6107                 return 0;
6108
6109         bio_put(bio);
6110 out_err:
6111         dip->errors = 1;
6112         /*
6113          * before atomic variable goto zero, we must
6114          * make sure dip->errors is perceived to be set.
6115          */
6116         smp_mb__before_atomic_dec();
6117         if (atomic_dec_and_test(&dip->pending_bios))
6118                 bio_io_error(dip->orig_bio);
6119
6120         /* bio_end_io() will handle error, so we needn't return it */
6121         return 0;
6122 }
6123
6124 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6125                                 loff_t file_offset)
6126 {
6127         struct btrfs_root *root = BTRFS_I(inode)->root;
6128         struct btrfs_dio_private *dip;
6129         struct bio_vec *bvec = bio->bi_io_vec;
6130         int skip_sum;
6131         int write = rw & REQ_WRITE;
6132         int ret = 0;
6133
6134         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6135
6136         dip = kmalloc(sizeof(*dip), GFP_NOFS);
6137         if (!dip) {
6138                 ret = -ENOMEM;
6139                 goto free_ordered;
6140         }
6141         dip->csums = NULL;
6142
6143         /* Write's use the ordered csum stuff, so we don't need dip->csums */
6144         if (!write && !skip_sum) {
6145                 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
6146                 if (!dip->csums) {
6147                         kfree(dip);
6148                         ret = -ENOMEM;
6149                         goto free_ordered;
6150                 }
6151         }
6152
6153         dip->private = bio->bi_private;
6154         dip->inode = inode;
6155         dip->logical_offset = file_offset;
6156
6157         dip->bytes = 0;
6158         do {
6159                 dip->bytes += bvec->bv_len;
6160                 bvec++;
6161         } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6162
6163         dip->disk_bytenr = (u64)bio->bi_sector << 9;
6164         bio->bi_private = dip;
6165         dip->errors = 0;
6166         dip->orig_bio = bio;
6167         atomic_set(&dip->pending_bios, 0);
6168
6169         if (write)
6170                 bio->bi_end_io = btrfs_endio_direct_write;
6171         else
6172                 bio->bi_end_io = btrfs_endio_direct_read;
6173
6174         ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6175         if (!ret)
6176                 return;
6177 free_ordered:
6178         /*
6179          * If this is a write, we need to clean up the reserved space and kill
6180          * the ordered extent.
6181          */
6182         if (write) {
6183                 struct btrfs_ordered_extent *ordered;
6184                 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6185                 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6186                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6187                         btrfs_free_reserved_extent(root, ordered->start,
6188                                                    ordered->disk_len);
6189                 btrfs_put_ordered_extent(ordered);
6190                 btrfs_put_ordered_extent(ordered);
6191         }
6192         bio_endio(bio, ret);
6193 }
6194
6195 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6196                         const struct iovec *iov, loff_t offset,
6197                         unsigned long nr_segs)
6198 {
6199         int seg;
6200         int i;
6201         size_t size;
6202         unsigned long addr;
6203         unsigned blocksize_mask = root->sectorsize - 1;
6204         ssize_t retval = -EINVAL;
6205         loff_t end = offset;
6206
6207         if (offset & blocksize_mask)
6208                 goto out;
6209
6210         /* Check the memory alignment.  Blocks cannot straddle pages */
6211         for (seg = 0; seg < nr_segs; seg++) {
6212                 addr = (unsigned long)iov[seg].iov_base;
6213                 size = iov[seg].iov_len;
6214                 end += size;
6215                 if ((addr & blocksize_mask) || (size & blocksize_mask))
6216                         goto out;
6217
6218                 /* If this is a write we don't need to check anymore */
6219                 if (rw & WRITE)
6220                         continue;
6221
6222                 /*
6223                  * Check to make sure we don't have duplicate iov_base's in this
6224                  * iovec, if so return EINVAL, otherwise we'll get csum errors
6225                  * when reading back.
6226                  */
6227                 for (i = seg + 1; i < nr_segs; i++) {
6228                         if (iov[seg].iov_base == iov[i].iov_base)
6229                                 goto out;
6230                 }
6231         }
6232         retval = 0;
6233 out:
6234         return retval;
6235 }
6236 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6237                         const struct iovec *iov, loff_t offset,
6238                         unsigned long nr_segs)
6239 {
6240         struct file *file = iocb->ki_filp;
6241         struct inode *inode = file->f_mapping->host;
6242         struct btrfs_ordered_extent *ordered;
6243         struct extent_state *cached_state = NULL;
6244         u64 lockstart, lockend;
6245         ssize_t ret;
6246         int writing = rw & WRITE;
6247         int write_bits = 0;
6248         size_t count = iov_length(iov, nr_segs);
6249
6250         if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6251                             offset, nr_segs)) {
6252                 return 0;
6253         }
6254
6255         lockstart = offset;
6256         lockend = offset + count - 1;
6257
6258         if (writing) {
6259                 ret = btrfs_delalloc_reserve_space(inode, count);
6260                 if (ret)
6261                         goto out;
6262         }
6263
6264         while (1) {
6265                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6266                                  0, &cached_state, GFP_NOFS);
6267                 /*
6268                  * We're concerned with the entire range that we're going to be
6269                  * doing DIO to, so we need to make sure theres no ordered
6270                  * extents in this range.
6271                  */
6272                 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6273                                                      lockend - lockstart + 1);
6274                 if (!ordered)
6275                         break;
6276                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6277                                      &cached_state, GFP_NOFS);
6278                 btrfs_start_ordered_extent(inode, ordered, 1);
6279                 btrfs_put_ordered_extent(ordered);
6280                 cond_resched();
6281         }
6282
6283         /*
6284          * we don't use btrfs_set_extent_delalloc because we don't want
6285          * the dirty or uptodate bits
6286          */
6287         if (writing) {
6288                 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6289                 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6290                                      EXTENT_DELALLOC, 0, NULL, &cached_state,
6291                                      GFP_NOFS);
6292                 if (ret) {
6293                         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6294                                          lockend, EXTENT_LOCKED | write_bits,
6295                                          1, 0, &cached_state, GFP_NOFS);
6296                         goto out;
6297                 }
6298         }
6299
6300         free_extent_state(cached_state);
6301         cached_state = NULL;
6302
6303         ret = __blockdev_direct_IO(rw, iocb, inode,
6304                    BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6305                    iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6306                    btrfs_submit_direct, 0);
6307
6308         if (ret < 0 && ret != -EIOCBQUEUED) {
6309                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6310                               offset + iov_length(iov, nr_segs) - 1,
6311                               EXTENT_LOCKED | write_bits, 1, 0,
6312                               &cached_state, GFP_NOFS);
6313         } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6314                 /*
6315                  * We're falling back to buffered, unlock the section we didn't
6316                  * do IO on.
6317                  */
6318                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6319                               offset + iov_length(iov, nr_segs) - 1,
6320                               EXTENT_LOCKED | write_bits, 1, 0,
6321                               &cached_state, GFP_NOFS);
6322         }
6323 out:
6324         free_extent_state(cached_state);
6325         return ret;
6326 }
6327
6328 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6329                 __u64 start, __u64 len)
6330 {
6331         return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6332 }
6333
6334 int btrfs_readpage(struct file *file, struct page *page)
6335 {
6336         struct extent_io_tree *tree;
6337         tree = &BTRFS_I(page->mapping->host)->io_tree;
6338         return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6339 }
6340
6341 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6342 {
6343         struct extent_io_tree *tree;
6344
6345
6346         if (current->flags & PF_MEMALLOC) {
6347                 redirty_page_for_writepage(wbc, page);
6348                 unlock_page(page);
6349                 return 0;
6350         }
6351         tree = &BTRFS_I(page->mapping->host)->io_tree;
6352         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6353 }
6354
6355 int btrfs_writepages(struct address_space *mapping,
6356                      struct writeback_control *wbc)
6357 {
6358         struct extent_io_tree *tree;
6359
6360         tree = &BTRFS_I(mapping->host)->io_tree;
6361         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6362 }
6363
6364 static int
6365 btrfs_readpages(struct file *file, struct address_space *mapping,
6366                 struct list_head *pages, unsigned nr_pages)
6367 {
6368         struct extent_io_tree *tree;
6369         tree = &BTRFS_I(mapping->host)->io_tree;
6370         return extent_readpages(tree, mapping, pages, nr_pages,
6371                                 btrfs_get_extent);
6372 }
6373 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6374 {
6375         struct extent_io_tree *tree;
6376         struct extent_map_tree *map;
6377         int ret;
6378
6379         tree = &BTRFS_I(page->mapping->host)->io_tree;
6380         map = &BTRFS_I(page->mapping->host)->extent_tree;
6381         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6382         if (ret == 1) {
6383                 ClearPagePrivate(page);
6384                 set_page_private(page, 0);
6385                 page_cache_release(page);
6386         }
6387         return ret;
6388 }
6389
6390 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6391 {
6392         if (PageWriteback(page) || PageDirty(page))
6393                 return 0;
6394         return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6395 }
6396
6397 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6398 {
6399         struct extent_io_tree *tree;
6400         struct btrfs_ordered_extent *ordered;
6401         struct extent_state *cached_state = NULL;
6402         u64 page_start = page_offset(page);
6403         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6404
6405
6406         /*
6407          * we have the page locked, so new writeback can't start,
6408          * and the dirty bit won't be cleared while we are here.
6409          *
6410          * Wait for IO on this page so that we can safely clear
6411          * the PagePrivate2 bit and do ordered accounting
6412          */
6413         wait_on_page_writeback(page);
6414
6415         tree = &BTRFS_I(page->mapping->host)->io_tree;
6416         if (offset) {
6417                 btrfs_releasepage(page, GFP_NOFS);
6418                 return;
6419         }
6420         lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6421                          GFP_NOFS);
6422         ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6423                                            page_offset(page));
6424         if (ordered) {
6425                 /*
6426                  * IO on this page will never be started, so we need
6427                  * to account for any ordered extents now
6428                  */
6429                 clear_extent_bit(tree, page_start, page_end,
6430                                  EXTENT_DIRTY | EXTENT_DELALLOC |
6431                                  EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6432                                  &cached_state, GFP_NOFS);
6433                 /*
6434                  * whoever cleared the private bit is responsible
6435                  * for the finish_ordered_io
6436                  */
6437                 if (TestClearPagePrivate2(page)) {
6438                         btrfs_finish_ordered_io(page->mapping->host,
6439                                                 page_start, page_end);
6440                 }
6441                 btrfs_put_ordered_extent(ordered);
6442                 cached_state = NULL;
6443                 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6444                                  GFP_NOFS);
6445         }
6446         clear_extent_bit(tree, page_start, page_end,
6447                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6448                  EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6449         __btrfs_releasepage(page, GFP_NOFS);
6450
6451         ClearPageChecked(page);
6452         if (PagePrivate(page)) {
6453                 ClearPagePrivate(page);
6454                 set_page_private(page, 0);
6455                 page_cache_release(page);
6456         }
6457 }
6458
6459 /*
6460  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6461  * called from a page fault handler when a page is first dirtied. Hence we must
6462  * be careful to check for EOF conditions here. We set the page up correctly
6463  * for a written page which means we get ENOSPC checking when writing into
6464  * holes and correct delalloc and unwritten extent mapping on filesystems that
6465  * support these features.
6466  *
6467  * We are not allowed to take the i_mutex here so we have to play games to
6468  * protect against truncate races as the page could now be beyond EOF.  Because
6469  * vmtruncate() writes the inode size before removing pages, once we have the
6470  * page lock we can determine safely if the page is beyond EOF. If it is not
6471  * beyond EOF, then the page is guaranteed safe against truncation until we
6472  * unlock the page.
6473  */
6474 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6475 {
6476         struct page *page = vmf->page;
6477         struct inode *inode = fdentry(vma->vm_file)->d_inode;
6478         struct btrfs_root *root = BTRFS_I(inode)->root;
6479         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6480         struct btrfs_ordered_extent *ordered;
6481         struct extent_state *cached_state = NULL;
6482         char *kaddr;
6483         unsigned long zero_start;
6484         loff_t size;
6485         int ret;
6486         u64 page_start;
6487         u64 page_end;
6488
6489         /* Need this to keep space reservations serialized */
6490         mutex_lock(&inode->i_mutex);
6491         ret  = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6492         mutex_unlock(&inode->i_mutex);
6493         if (!ret)
6494                 ret = btrfs_update_time(vma->vm_file);
6495         if (ret) {
6496                 if (ret == -ENOMEM)
6497                         ret = VM_FAULT_OOM;
6498                 else /* -ENOSPC, -EIO, etc */
6499                         ret = VM_FAULT_SIGBUS;
6500                 goto out;
6501         }
6502
6503         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6504 again:
6505         lock_page(page);
6506         size = i_size_read(inode);
6507         page_start = page_offset(page);
6508         page_end = page_start + PAGE_CACHE_SIZE - 1;
6509
6510         if ((page->mapping != inode->i_mapping) ||
6511             (page_start >= size)) {
6512                 /* page got truncated out from underneath us */
6513                 goto out_unlock;
6514         }
6515         wait_on_page_writeback(page);
6516
6517         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6518                          GFP_NOFS);
6519         set_page_extent_mapped(page);
6520
6521         /*
6522          * we can't set the delalloc bits if there are pending ordered
6523          * extents.  Drop our locks and wait for them to finish
6524          */
6525         ordered = btrfs_lookup_ordered_extent(inode, page_start);
6526         if (ordered) {
6527                 unlock_extent_cached(io_tree, page_start, page_end,
6528                                      &cached_state, GFP_NOFS);
6529                 unlock_page(page);
6530                 btrfs_start_ordered_extent(inode, ordered, 1);
6531                 btrfs_put_ordered_extent(ordered);
6532                 goto again;
6533         }
6534
6535         /*
6536          * XXX - page_mkwrite gets called every time the page is dirtied, even
6537          * if it was already dirty, so for space accounting reasons we need to
6538          * clear any delalloc bits for the range we are fixing to save.  There
6539          * is probably a better way to do this, but for now keep consistent with
6540          * prepare_pages in the normal write path.
6541          */
6542         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6543                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6544                           0, 0, &cached_state, GFP_NOFS);
6545
6546         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6547                                         &cached_state);
6548         if (ret) {
6549                 unlock_extent_cached(io_tree, page_start, page_end,
6550                                      &cached_state, GFP_NOFS);
6551                 ret = VM_FAULT_SIGBUS;
6552                 goto out_unlock;
6553         }
6554         ret = 0;
6555
6556         /* page is wholly or partially inside EOF */
6557         if (page_start + PAGE_CACHE_SIZE > size)
6558                 zero_start = size & ~PAGE_CACHE_MASK;
6559         else
6560                 zero_start = PAGE_CACHE_SIZE;
6561
6562         if (zero_start != PAGE_CACHE_SIZE) {
6563                 kaddr = kmap(page);
6564                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6565                 flush_dcache_page(page);
6566                 kunmap(page);
6567         }
6568         ClearPageChecked(page);
6569         set_page_dirty(page);
6570         SetPageUptodate(page);
6571
6572         BTRFS_I(inode)->last_trans = root->fs_info->generation;
6573         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6574
6575         unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6576
6577 out_unlock:
6578         if (!ret)
6579                 return VM_FAULT_LOCKED;
6580         unlock_page(page);
6581         btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6582 out:
6583         return ret;
6584 }
6585
6586 static int btrfs_truncate(struct inode *inode)
6587 {
6588         struct btrfs_root *root = BTRFS_I(inode)->root;
6589         struct btrfs_block_rsv *rsv;
6590         int ret;
6591         int err = 0;
6592         struct btrfs_trans_handle *trans;
6593         unsigned long nr;
6594         u64 mask = root->sectorsize - 1;
6595         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6596
6597         ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6598         if (ret)
6599                 return ret;
6600
6601         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6602         btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6603
6604         /*
6605          * Yes ladies and gentelment, this is indeed ugly.  The fact is we have
6606          * 3 things going on here
6607          *
6608          * 1) We need to reserve space for our orphan item and the space to
6609          * delete our orphan item.  Lord knows we don't want to have a dangling
6610          * orphan item because we didn't reserve space to remove it.
6611          *
6612          * 2) We need to reserve space to update our inode.
6613          *
6614          * 3) We need to have something to cache all the space that is going to
6615          * be free'd up by the truncate operation, but also have some slack
6616          * space reserved in case it uses space during the truncate (thank you
6617          * very much snapshotting).
6618          *
6619          * And we need these to all be seperate.  The fact is we can use alot of
6620          * space doing the truncate, and we have no earthly idea how much space
6621          * we will use, so we need the truncate reservation to be seperate so it
6622          * doesn't end up using space reserved for updating the inode or
6623          * removing the orphan item.  We also need to be able to stop the
6624          * transaction and start a new one, which means we need to be able to
6625          * update the inode several times, and we have no idea of knowing how
6626          * many times that will be, so we can't just reserve 1 item for the
6627          * entirety of the opration, so that has to be done seperately as well.
6628          * Then there is the orphan item, which does indeed need to be held on
6629          * to for the whole operation, and we need nobody to touch this reserved
6630          * space except the orphan code.
6631          *
6632          * So that leaves us with
6633          *
6634          * 1) root->orphan_block_rsv - for the orphan deletion.
6635          * 2) rsv - for the truncate reservation, which we will steal from the
6636          * transaction reservation.
6637          * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6638          * updating the inode.
6639          */
6640         rsv = btrfs_alloc_block_rsv(root);
6641         if (!rsv)
6642                 return -ENOMEM;
6643         rsv->size = min_size;
6644
6645         /*
6646          * 1 for the truncate slack space
6647          * 1 for the orphan item we're going to add
6648          * 1 for the orphan item deletion
6649          * 1 for updating the inode.
6650          */
6651         trans = btrfs_start_transaction(root, 4);
6652         if (IS_ERR(trans)) {
6653                 err = PTR_ERR(trans);
6654                 goto out;
6655         }
6656
6657         /* Migrate the slack space for the truncate to our reserve */
6658         ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
6659                                       min_size);
6660         BUG_ON(ret);
6661
6662         ret = btrfs_orphan_add(trans, inode);
6663         if (ret) {
6664                 btrfs_end_transaction(trans, root);
6665                 goto out;
6666         }
6667
6668         /*
6669          * setattr is responsible for setting the ordered_data_close flag,
6670          * but that is only tested during the last file release.  That
6671          * could happen well after the next commit, leaving a great big
6672          * window where new writes may get lost if someone chooses to write
6673          * to this file after truncating to zero
6674          *
6675          * The inode doesn't have any dirty data here, and so if we commit
6676          * this is a noop.  If someone immediately starts writing to the inode
6677          * it is very likely we'll catch some of their writes in this
6678          * transaction, and the commit will find this file on the ordered
6679          * data list with good things to send down.
6680          *
6681          * This is a best effort solution, there is still a window where
6682          * using truncate to replace the contents of the file will
6683          * end up with a zero length file after a crash.
6684          */
6685         if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6686                 btrfs_add_ordered_operation(trans, root, inode);
6687
6688         while (1) {
6689                 ret = btrfs_block_rsv_refill(root, rsv, min_size);
6690                 if (ret) {
6691                         /*
6692                          * This can only happen with the original transaction we
6693                          * started above, every other time we shouldn't have a
6694                          * transaction started yet.
6695                          */
6696                         if (ret == -EAGAIN)
6697                                 goto end_trans;
6698                         err = ret;
6699                         break;
6700                 }
6701
6702                 if (!trans) {
6703                         /* Just need the 1 for updating the inode */
6704                         trans = btrfs_start_transaction(root, 1);
6705                         if (IS_ERR(trans)) {
6706                                 ret = err = PTR_ERR(trans);
6707                                 trans = NULL;
6708                                 break;
6709                         }
6710                 }
6711
6712                 trans->block_rsv = rsv;
6713
6714                 ret = btrfs_truncate_inode_items(trans, root, inode,
6715                                                  inode->i_size,
6716                                                  BTRFS_EXTENT_DATA_KEY);
6717                 if (ret != -EAGAIN) {
6718                         err = ret;
6719                         break;
6720                 }
6721
6722                 trans->block_rsv = &root->fs_info->trans_block_rsv;
6723                 ret = btrfs_update_inode(trans, root, inode);
6724                 if (ret) {
6725                         err = ret;
6726                         break;
6727                 }
6728 end_trans:
6729                 nr = trans->blocks_used;
6730                 btrfs_end_transaction(trans, root);
6731                 trans = NULL;
6732                 btrfs_btree_balance_dirty(root, nr);
6733         }
6734
6735         if (ret == 0 && inode->i_nlink > 0) {
6736                 trans->block_rsv = root->orphan_block_rsv;
6737                 ret = btrfs_orphan_del(trans, inode);
6738                 if (ret)
6739                         err = ret;
6740         } else if (ret && inode->i_nlink > 0) {
6741                 /*
6742                  * Failed to do the truncate, remove us from the in memory
6743                  * orphan list.
6744                  */
6745                 ret = btrfs_orphan_del(NULL, inode);
6746         }
6747
6748         if (trans) {
6749                 trans->block_rsv = &root->fs_info->trans_block_rsv;
6750                 ret = btrfs_update_inode(trans, root, inode);
6751                 if (ret && !err)
6752                         err = ret;
6753
6754                 nr = trans->blocks_used;
6755                 ret = btrfs_end_transaction_throttle(trans, root);
6756                 btrfs_btree_balance_dirty(root, nr);
6757         }
6758
6759 out:
6760         btrfs_free_block_rsv(root, rsv);
6761
6762         if (ret && !err)
6763                 err = ret;
6764
6765         return err;
6766 }
6767
6768 /*
6769  * create a new subvolume directory/inode (helper for the ioctl).
6770  */
6771 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6772                              struct btrfs_root *new_root, u64 new_dirid)
6773 {
6774         struct inode *inode;
6775         int err;
6776         u64 index = 0;
6777
6778         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6779                                 new_dirid, S_IFDIR | 0700, &index);
6780         if (IS_ERR(inode))
6781                 return PTR_ERR(inode);
6782         inode->i_op = &btrfs_dir_inode_operations;
6783         inode->i_fop = &btrfs_dir_file_operations;
6784
6785         set_nlink(inode, 1);
6786         btrfs_i_size_write(inode, 0);
6787
6788         err = btrfs_update_inode(trans, new_root, inode);
6789         BUG_ON(err);
6790
6791         iput(inode);
6792         return 0;
6793 }
6794
6795 struct inode *btrfs_alloc_inode(struct super_block *sb)
6796 {
6797         struct btrfs_inode *ei;
6798         struct inode *inode;
6799
6800         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6801         if (!ei)
6802                 return NULL;
6803
6804         ei->root = NULL;
6805         ei->space_info = NULL;
6806         ei->generation = 0;
6807         ei->sequence = 0;
6808         ei->last_trans = 0;
6809         ei->last_sub_trans = 0;
6810         ei->logged_trans = 0;
6811         ei->delalloc_bytes = 0;
6812         ei->disk_i_size = 0;
6813         ei->flags = 0;
6814         ei->csum_bytes = 0;
6815         ei->index_cnt = (u64)-1;
6816         ei->last_unlink_trans = 0;
6817
6818         spin_lock_init(&ei->lock);
6819         ei->outstanding_extents = 0;
6820         ei->reserved_extents = 0;
6821
6822         ei->ordered_data_close = 0;
6823         ei->orphan_meta_reserved = 0;
6824         ei->dummy_inode = 0;
6825         ei->in_defrag = 0;
6826         ei->delalloc_meta_reserved = 0;
6827         ei->force_compress = BTRFS_COMPRESS_NONE;
6828
6829         ei->delayed_node = NULL;
6830
6831         inode = &ei->vfs_inode;
6832         extent_map_tree_init(&ei->extent_tree);
6833         extent_io_tree_init(&ei->io_tree, &inode->i_data);
6834         extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
6835         mutex_init(&ei->log_mutex);
6836         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6837         INIT_LIST_HEAD(&ei->i_orphan);
6838         INIT_LIST_HEAD(&ei->delalloc_inodes);
6839         INIT_LIST_HEAD(&ei->ordered_operations);
6840         RB_CLEAR_NODE(&ei->rb_node);
6841
6842         return inode;
6843 }
6844
6845 static void btrfs_i_callback(struct rcu_head *head)
6846 {
6847         struct inode *inode = container_of(head, struct inode, i_rcu);
6848         INIT_LIST_HEAD(&inode->i_dentry);
6849         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6850 }
6851
6852 void btrfs_destroy_inode(struct inode *inode)
6853 {
6854         struct btrfs_ordered_extent *ordered;
6855         struct btrfs_root *root = BTRFS_I(inode)->root;
6856
6857         WARN_ON(!list_empty(&inode->i_dentry));
6858         WARN_ON(inode->i_data.nrpages);
6859         WARN_ON(BTRFS_I(inode)->outstanding_extents);
6860         WARN_ON(BTRFS_I(inode)->reserved_extents);
6861         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
6862         WARN_ON(BTRFS_I(inode)->csum_bytes);
6863
6864         /*
6865          * This can happen where we create an inode, but somebody else also
6866          * created the same inode and we need to destroy the one we already
6867          * created.
6868          */
6869         if (!root)
6870                 goto free;
6871
6872         /*
6873          * Make sure we're properly removed from the ordered operation
6874          * lists.
6875          */
6876         smp_mb();
6877         if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6878                 spin_lock(&root->fs_info->ordered_extent_lock);
6879                 list_del_init(&BTRFS_I(inode)->ordered_operations);
6880                 spin_unlock(&root->fs_info->ordered_extent_lock);
6881         }
6882
6883         spin_lock(&root->orphan_lock);
6884         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6885                 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
6886                        (unsigned long long)btrfs_ino(inode));
6887                 list_del_init(&BTRFS_I(inode)->i_orphan);
6888         }
6889         spin_unlock(&root->orphan_lock);
6890
6891         while (1) {
6892                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6893                 if (!ordered)
6894                         break;
6895                 else {
6896                         printk(KERN_ERR "btrfs found ordered "
6897                                "extent %llu %llu on inode cleanup\n",
6898                                (unsigned long long)ordered->file_offset,
6899                                (unsigned long long)ordered->len);
6900                         btrfs_remove_ordered_extent(inode, ordered);
6901                         btrfs_put_ordered_extent(ordered);
6902                         btrfs_put_ordered_extent(ordered);
6903                 }
6904         }
6905         inode_tree_del(inode);
6906         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6907 free:
6908         btrfs_remove_delayed_node(inode);
6909         call_rcu(&inode->i_rcu, btrfs_i_callback);
6910 }
6911
6912 int btrfs_drop_inode(struct inode *inode)
6913 {
6914         struct btrfs_root *root = BTRFS_I(inode)->root;
6915
6916         if (btrfs_root_refs(&root->root_item) == 0 &&
6917             !btrfs_is_free_space_inode(root, inode))
6918                 return 1;
6919         else
6920                 return generic_drop_inode(inode);
6921 }
6922
6923 static void init_once(void *foo)
6924 {
6925         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6926
6927         inode_init_once(&ei->vfs_inode);
6928 }
6929
6930 void btrfs_destroy_cachep(void)
6931 {
6932         if (btrfs_inode_cachep)
6933                 kmem_cache_destroy(btrfs_inode_cachep);
6934         if (btrfs_trans_handle_cachep)
6935                 kmem_cache_destroy(btrfs_trans_handle_cachep);
6936         if (btrfs_transaction_cachep)
6937                 kmem_cache_destroy(btrfs_transaction_cachep);
6938         if (btrfs_path_cachep)
6939                 kmem_cache_destroy(btrfs_path_cachep);
6940         if (btrfs_free_space_cachep)
6941                 kmem_cache_destroy(btrfs_free_space_cachep);
6942 }
6943
6944 int btrfs_init_cachep(void)
6945 {
6946         btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6947                         sizeof(struct btrfs_inode), 0,
6948                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6949         if (!btrfs_inode_cachep)
6950                 goto fail;
6951
6952         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6953                         sizeof(struct btrfs_trans_handle), 0,
6954                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6955         if (!btrfs_trans_handle_cachep)
6956                 goto fail;
6957
6958         btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6959                         sizeof(struct btrfs_transaction), 0,
6960                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6961         if (!btrfs_transaction_cachep)
6962                 goto fail;
6963
6964         btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6965                         sizeof(struct btrfs_path), 0,
6966                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6967         if (!btrfs_path_cachep)
6968                 goto fail;
6969
6970         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
6971                         sizeof(struct btrfs_free_space), 0,
6972                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6973         if (!btrfs_free_space_cachep)
6974                 goto fail;
6975
6976         return 0;
6977 fail:
6978         btrfs_destroy_cachep();
6979         return -ENOMEM;
6980 }
6981
6982 static int btrfs_getattr(struct vfsmount *mnt,
6983                          struct dentry *dentry, struct kstat *stat)
6984 {
6985         struct inode *inode = dentry->d_inode;
6986         u32 blocksize = inode->i_sb->s_blocksize;
6987
6988         generic_fillattr(inode, stat);
6989         stat->dev = BTRFS_I(inode)->root->anon_dev;
6990         stat->blksize = PAGE_CACHE_SIZE;
6991         stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
6992                 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
6993         return 0;
6994 }
6995
6996 /*
6997  * If a file is moved, it will inherit the cow and compression flags of the new
6998  * directory.
6999  */
7000 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
7001 {
7002         struct btrfs_inode *b_dir = BTRFS_I(dir);
7003         struct btrfs_inode *b_inode = BTRFS_I(inode);
7004
7005         if (b_dir->flags & BTRFS_INODE_NODATACOW)
7006                 b_inode->flags |= BTRFS_INODE_NODATACOW;
7007         else
7008                 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
7009
7010         if (b_dir->flags & BTRFS_INODE_COMPRESS)
7011                 b_inode->flags |= BTRFS_INODE_COMPRESS;
7012         else
7013                 b_inode->flags &= ~BTRFS_INODE_COMPRESS;
7014 }
7015
7016 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7017                            struct inode *new_dir, struct dentry *new_dentry)
7018 {
7019         struct btrfs_trans_handle *trans;
7020         struct btrfs_root *root = BTRFS_I(old_dir)->root;
7021         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7022         struct inode *new_inode = new_dentry->d_inode;
7023         struct inode *old_inode = old_dentry->d_inode;
7024         struct timespec ctime = CURRENT_TIME;
7025         u64 index = 0;
7026         u64 root_objectid;
7027         int ret;
7028         u64 old_ino = btrfs_ino(old_inode);
7029
7030         if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7031                 return -EPERM;
7032
7033         /* we only allow rename subvolume link between subvolumes */
7034         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7035                 return -EXDEV;
7036
7037         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7038             (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7039                 return -ENOTEMPTY;
7040
7041         if (S_ISDIR(old_inode->i_mode) && new_inode &&
7042             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7043                 return -ENOTEMPTY;
7044         /*
7045          * we're using rename to replace one file with another.
7046          * and the replacement file is large.  Start IO on it now so
7047          * we don't add too much work to the end of the transaction
7048          */
7049         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
7050             old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
7051                 filemap_flush(old_inode->i_mapping);
7052
7053         /* close the racy window with snapshot create/destroy ioctl */
7054         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7055                 down_read(&root->fs_info->subvol_sem);
7056         /*
7057          * We want to reserve the absolute worst case amount of items.  So if
7058          * both inodes are subvols and we need to unlink them then that would
7059          * require 4 item modifications, but if they are both normal inodes it
7060          * would require 5 item modifications, so we'll assume their normal
7061          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
7062          * should cover the worst case number of items we'll modify.
7063          */
7064         trans = btrfs_start_transaction(root, 20);
7065         if (IS_ERR(trans)) {
7066                 ret = PTR_ERR(trans);
7067                 goto out_notrans;
7068         }
7069
7070         if (dest != root)
7071                 btrfs_record_root_in_trans(trans, dest);
7072
7073         ret = btrfs_set_inode_index(new_dir, &index);
7074         if (ret)
7075                 goto out_fail;
7076
7077         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7078                 /* force full log commit if subvolume involved. */
7079                 root->fs_info->last_trans_log_full_commit = trans->transid;
7080         } else {
7081                 ret = btrfs_insert_inode_ref(trans, dest,
7082                                              new_dentry->d_name.name,
7083                                              new_dentry->d_name.len,
7084                                              old_ino,
7085                                              btrfs_ino(new_dir), index);
7086                 if (ret)
7087                         goto out_fail;
7088                 /*
7089                  * this is an ugly little race, but the rename is required
7090                  * to make sure that if we crash, the inode is either at the
7091                  * old name or the new one.  pinning the log transaction lets
7092                  * us make sure we don't allow a log commit to come in after
7093                  * we unlink the name but before we add the new name back in.
7094                  */
7095                 btrfs_pin_log_trans(root);
7096         }
7097         /*
7098          * make sure the inode gets flushed if it is replacing
7099          * something.
7100          */
7101         if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
7102                 btrfs_add_ordered_operation(trans, root, old_inode);
7103
7104         old_dir->i_ctime = old_dir->i_mtime = ctime;
7105         new_dir->i_ctime = new_dir->i_mtime = ctime;
7106         old_inode->i_ctime = ctime;
7107
7108         if (old_dentry->d_parent != new_dentry->d_parent)
7109                 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
7110
7111         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7112                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
7113                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
7114                                         old_dentry->d_name.name,
7115                                         old_dentry->d_name.len);
7116         } else {
7117                 ret = __btrfs_unlink_inode(trans, root, old_dir,
7118                                         old_dentry->d_inode,
7119                                         old_dentry->d_name.name,
7120                                         old_dentry->d_name.len);
7121                 if (!ret)
7122                         ret = btrfs_update_inode(trans, root, old_inode);
7123         }
7124         BUG_ON(ret);
7125
7126         if (new_inode) {
7127                 new_inode->i_ctime = CURRENT_TIME;
7128                 if (unlikely(btrfs_ino(new_inode) ==
7129                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7130                         root_objectid = BTRFS_I(new_inode)->location.objectid;
7131                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
7132                                                 root_objectid,
7133                                                 new_dentry->d_name.name,
7134                                                 new_dentry->d_name.len);
7135                         BUG_ON(new_inode->i_nlink == 0);
7136                 } else {
7137                         ret = btrfs_unlink_inode(trans, dest, new_dir,
7138                                                  new_dentry->d_inode,
7139                                                  new_dentry->d_name.name,
7140                                                  new_dentry->d_name.len);
7141                 }
7142                 BUG_ON(ret);
7143                 if (new_inode->i_nlink == 0) {
7144                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7145                         BUG_ON(ret);
7146                 }
7147         }
7148
7149         fixup_inode_flags(new_dir, old_inode);
7150
7151         ret = btrfs_add_link(trans, new_dir, old_inode,
7152                              new_dentry->d_name.name,
7153                              new_dentry->d_name.len, 0, index);
7154         BUG_ON(ret);
7155
7156         if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7157                 struct dentry *parent = new_dentry->d_parent;
7158                 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7159                 btrfs_end_log_trans(root);
7160         }
7161 out_fail:
7162         btrfs_end_transaction_throttle(trans, root);
7163 out_notrans:
7164         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7165                 up_read(&root->fs_info->subvol_sem);
7166
7167         return ret;
7168 }
7169
7170 /*
7171  * some fairly slow code that needs optimization. This walks the list
7172  * of all the inodes with pending delalloc and forces them to disk.
7173  */
7174 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7175 {
7176         struct list_head *head = &root->fs_info->delalloc_inodes;
7177         struct btrfs_inode *binode;
7178         struct inode *inode;
7179
7180         if (root->fs_info->sb->s_flags & MS_RDONLY)
7181                 return -EROFS;
7182
7183         spin_lock(&root->fs_info->delalloc_lock);
7184         while (!list_empty(head)) {
7185                 binode = list_entry(head->next, struct btrfs_inode,
7186                                     delalloc_inodes);
7187                 inode = igrab(&binode->vfs_inode);
7188                 if (!inode)
7189                         list_del_init(&binode->delalloc_inodes);
7190                 spin_unlock(&root->fs_info->delalloc_lock);
7191                 if (inode) {
7192                         filemap_flush(inode->i_mapping);
7193                         if (delay_iput)
7194                                 btrfs_add_delayed_iput(inode);
7195                         else
7196                                 iput(inode);
7197                 }
7198                 cond_resched();
7199                 spin_lock(&root->fs_info->delalloc_lock);
7200         }
7201         spin_unlock(&root->fs_info->delalloc_lock);
7202
7203         /* the filemap_flush will queue IO into the worker threads, but
7204          * we have to make sure the IO is actually started and that
7205          * ordered extents get created before we return
7206          */
7207         atomic_inc(&root->fs_info->async_submit_draining);
7208         while (atomic_read(&root->fs_info->nr_async_submits) ||
7209               atomic_read(&root->fs_info->async_delalloc_pages)) {
7210                 wait_event(root->fs_info->async_submit_wait,
7211                    (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7212                     atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7213         }
7214         atomic_dec(&root->fs_info->async_submit_draining);
7215         return 0;
7216 }
7217
7218 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7219                          const char *symname)
7220 {
7221         struct btrfs_trans_handle *trans;
7222         struct btrfs_root *root = BTRFS_I(dir)->root;
7223         struct btrfs_path *path;
7224         struct btrfs_key key;
7225         struct inode *inode = NULL;
7226         int err;
7227         int drop_inode = 0;
7228         u64 objectid;
7229         u64 index = 0 ;
7230         int name_len;
7231         int datasize;
7232         unsigned long ptr;
7233         struct btrfs_file_extent_item *ei;
7234         struct extent_buffer *leaf;
7235         unsigned long nr = 0;
7236
7237         name_len = strlen(symname) + 1;
7238         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7239                 return -ENAMETOOLONG;
7240
7241         /*
7242          * 2 items for inode item and ref
7243          * 2 items for dir items
7244          * 1 item for xattr if selinux is on
7245          */
7246         trans = btrfs_start_transaction(root, 5);
7247         if (IS_ERR(trans))
7248                 return PTR_ERR(trans);
7249
7250         err = btrfs_find_free_ino(root, &objectid);
7251         if (err)
7252                 goto out_unlock;
7253
7254         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7255                                 dentry->d_name.len, btrfs_ino(dir), objectid,
7256                                 S_IFLNK|S_IRWXUGO, &index);
7257         if (IS_ERR(inode)) {
7258                 err = PTR_ERR(inode);
7259                 goto out_unlock;
7260         }
7261
7262         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7263         if (err) {
7264                 drop_inode = 1;
7265                 goto out_unlock;
7266         }
7267
7268         /*
7269         * If the active LSM wants to access the inode during
7270         * d_instantiate it needs these. Smack checks to see
7271         * if the filesystem supports xattrs by looking at the
7272         * ops vector.
7273         */
7274         inode->i_fop = &btrfs_file_operations;
7275         inode->i_op = &btrfs_file_inode_operations;
7276
7277         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7278         if (err)
7279                 drop_inode = 1;
7280         else {
7281                 inode->i_mapping->a_ops = &btrfs_aops;
7282                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7283                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7284         }
7285         if (drop_inode)
7286                 goto out_unlock;
7287
7288         path = btrfs_alloc_path();
7289         if (!path) {
7290                 err = -ENOMEM;
7291                 drop_inode = 1;
7292                 goto out_unlock;
7293         }
7294         key.objectid = btrfs_ino(inode);
7295         key.offset = 0;
7296         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7297         datasize = btrfs_file_extent_calc_inline_size(name_len);
7298         err = btrfs_insert_empty_item(trans, root, path, &key,
7299                                       datasize);
7300         if (err) {
7301                 drop_inode = 1;
7302                 btrfs_free_path(path);
7303                 goto out_unlock;
7304         }
7305         leaf = path->nodes[0];
7306         ei = btrfs_item_ptr(leaf, path->slots[0],
7307                             struct btrfs_file_extent_item);
7308         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7309         btrfs_set_file_extent_type(leaf, ei,
7310                                    BTRFS_FILE_EXTENT_INLINE);
7311         btrfs_set_file_extent_encryption(leaf, ei, 0);
7312         btrfs_set_file_extent_compression(leaf, ei, 0);
7313         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7314         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7315
7316         ptr = btrfs_file_extent_inline_start(ei);
7317         write_extent_buffer(leaf, symname, ptr, name_len);
7318         btrfs_mark_buffer_dirty(leaf);
7319         btrfs_free_path(path);
7320
7321         inode->i_op = &btrfs_symlink_inode_operations;
7322         inode->i_mapping->a_ops = &btrfs_symlink_aops;
7323         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7324         inode_set_bytes(inode, name_len);
7325         btrfs_i_size_write(inode, name_len - 1);
7326         err = btrfs_update_inode(trans, root, inode);
7327         if (err)
7328                 drop_inode = 1;
7329
7330 out_unlock:
7331         if (!err)
7332                 d_instantiate(dentry, inode);
7333         nr = trans->blocks_used;
7334         btrfs_end_transaction_throttle(trans, root);
7335         if (drop_inode) {
7336                 inode_dec_link_count(inode);
7337                 iput(inode);
7338         }
7339         btrfs_btree_balance_dirty(root, nr);
7340         return err;
7341 }
7342
7343 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7344                                        u64 start, u64 num_bytes, u64 min_size,
7345                                        loff_t actual_len, u64 *alloc_hint,
7346                                        struct btrfs_trans_handle *trans)
7347 {
7348         struct btrfs_root *root = BTRFS_I(inode)->root;
7349         struct btrfs_key ins;
7350         u64 cur_offset = start;
7351         u64 i_size;
7352         int ret = 0;
7353         bool own_trans = true;
7354
7355         if (trans)
7356                 own_trans = false;
7357         while (num_bytes > 0) {
7358                 if (own_trans) {
7359                         trans = btrfs_start_transaction(root, 3);
7360                         if (IS_ERR(trans)) {
7361                                 ret = PTR_ERR(trans);
7362                                 break;
7363                         }
7364                 }
7365
7366                 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7367                                            0, *alloc_hint, (u64)-1, &ins, 1);
7368                 if (ret) {
7369                         if (own_trans)
7370                                 btrfs_end_transaction(trans, root);
7371                         break;
7372                 }
7373
7374                 ret = insert_reserved_file_extent(trans, inode,
7375                                                   cur_offset, ins.objectid,
7376                                                   ins.offset, ins.offset,
7377                                                   ins.offset, 0, 0, 0,
7378                                                   BTRFS_FILE_EXTENT_PREALLOC);
7379                 BUG_ON(ret);
7380                 btrfs_drop_extent_cache(inode, cur_offset,
7381                                         cur_offset + ins.offset -1, 0);
7382
7383                 num_bytes -= ins.offset;
7384                 cur_offset += ins.offset;
7385                 *alloc_hint = ins.objectid + ins.offset;
7386
7387                 inode->i_ctime = CURRENT_TIME;
7388                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7389                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7390                     (actual_len > inode->i_size) &&
7391                     (cur_offset > inode->i_size)) {
7392                         if (cur_offset > actual_len)
7393                                 i_size = actual_len;
7394                         else
7395                                 i_size = cur_offset;
7396                         i_size_write(inode, i_size);
7397                         btrfs_ordered_update_i_size(inode, i_size, NULL);
7398                 }
7399
7400                 ret = btrfs_update_inode(trans, root, inode);
7401                 BUG_ON(ret);
7402
7403                 if (own_trans)
7404                         btrfs_end_transaction(trans, root);
7405         }
7406         return ret;
7407 }
7408
7409 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7410                               u64 start, u64 num_bytes, u64 min_size,
7411                               loff_t actual_len, u64 *alloc_hint)
7412 {
7413         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7414                                            min_size, actual_len, alloc_hint,
7415                                            NULL);
7416 }
7417
7418 int btrfs_prealloc_file_range_trans(struct inode *inode,
7419                                     struct btrfs_trans_handle *trans, int mode,
7420                                     u64 start, u64 num_bytes, u64 min_size,
7421                                     loff_t actual_len, u64 *alloc_hint)
7422 {
7423         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7424                                            min_size, actual_len, alloc_hint, trans);
7425 }
7426
7427 static int btrfs_set_page_dirty(struct page *page)
7428 {
7429         return __set_page_dirty_nobuffers(page);
7430 }
7431
7432 static int btrfs_permission(struct inode *inode, int mask)
7433 {
7434         struct btrfs_root *root = BTRFS_I(inode)->root;
7435         umode_t mode = inode->i_mode;
7436
7437         if (mask & MAY_WRITE &&
7438             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7439                 if (btrfs_root_readonly(root))
7440                         return -EROFS;
7441                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7442                         return -EACCES;
7443         }
7444         return generic_permission(inode, mask);
7445 }
7446
7447 static const struct inode_operations btrfs_dir_inode_operations = {
7448         .getattr        = btrfs_getattr,
7449         .lookup         = btrfs_lookup,
7450         .create         = btrfs_create,
7451         .unlink         = btrfs_unlink,
7452         .link           = btrfs_link,
7453         .mkdir          = btrfs_mkdir,
7454         .rmdir          = btrfs_rmdir,
7455         .rename         = btrfs_rename,
7456         .symlink        = btrfs_symlink,
7457         .setattr        = btrfs_setattr,
7458         .mknod          = btrfs_mknod,
7459         .setxattr       = btrfs_setxattr,
7460         .getxattr       = btrfs_getxattr,
7461         .listxattr      = btrfs_listxattr,
7462         .removexattr    = btrfs_removexattr,
7463         .permission     = btrfs_permission,
7464         .get_acl        = btrfs_get_acl,
7465 };
7466 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7467         .lookup         = btrfs_lookup,
7468         .permission     = btrfs_permission,
7469         .get_acl        = btrfs_get_acl,
7470 };
7471
7472 static const struct file_operations btrfs_dir_file_operations = {
7473         .llseek         = generic_file_llseek,
7474         .read           = generic_read_dir,
7475         .readdir        = btrfs_real_readdir,
7476         .unlocked_ioctl = btrfs_ioctl,
7477 #ifdef CONFIG_COMPAT
7478         .compat_ioctl   = btrfs_ioctl,
7479 #endif
7480         .release        = btrfs_release_file,
7481         .fsync          = btrfs_sync_file,
7482 };
7483
7484 static struct extent_io_ops btrfs_extent_io_ops = {
7485         .fill_delalloc = run_delalloc_range,
7486         .submit_bio_hook = btrfs_submit_bio_hook,
7487         .merge_bio_hook = btrfs_merge_bio_hook,
7488         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7489         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7490         .writepage_start_hook = btrfs_writepage_start_hook,
7491         .set_bit_hook = btrfs_set_bit_hook,
7492         .clear_bit_hook = btrfs_clear_bit_hook,
7493         .merge_extent_hook = btrfs_merge_extent_hook,
7494         .split_extent_hook = btrfs_split_extent_hook,
7495 };
7496
7497 /*
7498  * btrfs doesn't support the bmap operation because swapfiles
7499  * use bmap to make a mapping of extents in the file.  They assume
7500  * these extents won't change over the life of the file and they
7501  * use the bmap result to do IO directly to the drive.
7502  *
7503  * the btrfs bmap call would return logical addresses that aren't
7504  * suitable for IO and they also will change frequently as COW
7505  * operations happen.  So, swapfile + btrfs == corruption.
7506  *
7507  * For now we're avoiding this by dropping bmap.
7508  */
7509 static const struct address_space_operations btrfs_aops = {
7510         .readpage       = btrfs_readpage,
7511         .writepage      = btrfs_writepage,
7512         .writepages     = btrfs_writepages,
7513         .readpages      = btrfs_readpages,
7514         .direct_IO      = btrfs_direct_IO,
7515         .invalidatepage = btrfs_invalidatepage,
7516         .releasepage    = btrfs_releasepage,
7517         .set_page_dirty = btrfs_set_page_dirty,
7518         .error_remove_page = generic_error_remove_page,
7519 };
7520
7521 static const struct address_space_operations btrfs_symlink_aops = {
7522         .readpage       = btrfs_readpage,
7523         .writepage      = btrfs_writepage,
7524         .invalidatepage = btrfs_invalidatepage,
7525         .releasepage    = btrfs_releasepage,
7526 };
7527
7528 static const struct inode_operations btrfs_file_inode_operations = {
7529         .getattr        = btrfs_getattr,
7530         .setattr        = btrfs_setattr,
7531         .setxattr       = btrfs_setxattr,
7532         .getxattr       = btrfs_getxattr,
7533         .listxattr      = btrfs_listxattr,
7534         .removexattr    = btrfs_removexattr,
7535         .permission     = btrfs_permission,
7536         .fiemap         = btrfs_fiemap,
7537         .get_acl        = btrfs_get_acl,
7538 };
7539 static const struct inode_operations btrfs_special_inode_operations = {
7540         .getattr        = btrfs_getattr,
7541         .setattr        = btrfs_setattr,
7542         .permission     = btrfs_permission,
7543         .setxattr       = btrfs_setxattr,
7544         .getxattr       = btrfs_getxattr,
7545         .listxattr      = btrfs_listxattr,
7546         .removexattr    = btrfs_removexattr,
7547         .get_acl        = btrfs_get_acl,
7548 };
7549 static const struct inode_operations btrfs_symlink_inode_operations = {
7550         .readlink       = generic_readlink,
7551         .follow_link    = page_follow_link_light,
7552         .put_link       = page_put_link,
7553         .getattr        = btrfs_getattr,
7554         .setattr        = btrfs_setattr,
7555         .permission     = btrfs_permission,
7556         .setxattr       = btrfs_setxattr,
7557         .getxattr       = btrfs_getxattr,
7558         .listxattr      = btrfs_listxattr,
7559         .removexattr    = btrfs_removexattr,
7560         .get_acl        = btrfs_get_acl,
7561 };
7562
7563 const struct dentry_operations btrfs_dentry_operations = {
7564         .d_delete       = btrfs_dentry_delete,
7565         .d_release      = btrfs_dentry_release,
7566 };