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