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