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