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