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