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