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