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