Merge branch 'work.splice_read' of git://git.kernel.org/pub/scm/linux/kernel/git...
[cascardo/linux.git] / fs / btrfs / inode.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/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 #include "dedupe.h"
64
65 struct btrfs_iget_args {
66         struct btrfs_key *location;
67         struct btrfs_root *root;
68 };
69
70 struct btrfs_dio_data {
71         u64 outstanding_extents;
72         u64 reserve;
73         u64 unsubmitted_oe_range_start;
74         u64 unsubmitted_oe_range_end;
75 };
76
77 static const struct inode_operations btrfs_dir_inode_operations;
78 static const struct inode_operations btrfs_symlink_inode_operations;
79 static const struct inode_operations btrfs_dir_ro_inode_operations;
80 static const struct inode_operations btrfs_special_inode_operations;
81 static const struct inode_operations btrfs_file_inode_operations;
82 static const struct address_space_operations btrfs_aops;
83 static const struct address_space_operations btrfs_symlink_aops;
84 static const struct file_operations btrfs_dir_file_operations;
85 static const struct extent_io_ops btrfs_extent_io_ops;
86
87 static struct kmem_cache *btrfs_inode_cachep;
88 struct kmem_cache *btrfs_trans_handle_cachep;
89 struct kmem_cache *btrfs_transaction_cachep;
90 struct kmem_cache *btrfs_path_cachep;
91 struct kmem_cache *btrfs_free_space_cachep;
92
93 #define S_SHIFT 12
94 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
95         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
96         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
97         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
98         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
99         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
100         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
101         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
102 };
103
104 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
105 static int btrfs_truncate(struct inode *inode);
106 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
107 static noinline int cow_file_range(struct inode *inode,
108                                    struct page *locked_page,
109                                    u64 start, u64 end, u64 delalloc_end,
110                                    int *page_started, unsigned long *nr_written,
111                                    int unlock, struct btrfs_dedupe_hash *hash);
112 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
113                                            u64 len, u64 orig_start,
114                                            u64 block_start, u64 block_len,
115                                            u64 orig_block_len, u64 ram_bytes,
116                                            int type);
117
118 static int btrfs_dirty_inode(struct inode *inode);
119
120 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
121 void btrfs_test_inode_set_ops(struct inode *inode)
122 {
123         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
124 }
125 #endif
126
127 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
128                                      struct inode *inode,  struct inode *dir,
129                                      const struct qstr *qstr)
130 {
131         int err;
132
133         err = btrfs_init_acl(trans, inode, dir);
134         if (!err)
135                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
136         return err;
137 }
138
139 /*
140  * this does all the hard work for inserting an inline extent into
141  * the btree.  The caller should have done a btrfs_drop_extents so that
142  * no overlapping inline items exist in the btree
143  */
144 static int insert_inline_extent(struct btrfs_trans_handle *trans,
145                                 struct btrfs_path *path, int extent_inserted,
146                                 struct btrfs_root *root, struct inode *inode,
147                                 u64 start, size_t size, size_t compressed_size,
148                                 int compress_type,
149                                 struct page **compressed_pages)
150 {
151         struct extent_buffer *leaf;
152         struct page *page = NULL;
153         char *kaddr;
154         unsigned long ptr;
155         struct btrfs_file_extent_item *ei;
156         int err = 0;
157         int ret;
158         size_t cur_size = size;
159         unsigned long offset;
160
161         if (compressed_size && compressed_pages)
162                 cur_size = compressed_size;
163
164         inode_add_bytes(inode, size);
165
166         if (!extent_inserted) {
167                 struct btrfs_key key;
168                 size_t datasize;
169
170                 key.objectid = btrfs_ino(inode);
171                 key.offset = start;
172                 key.type = BTRFS_EXTENT_DATA_KEY;
173
174                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
175                 path->leave_spinning = 1;
176                 ret = btrfs_insert_empty_item(trans, root, path, &key,
177                                               datasize);
178                 if (ret) {
179                         err = ret;
180                         goto fail;
181                 }
182         }
183         leaf = path->nodes[0];
184         ei = btrfs_item_ptr(leaf, path->slots[0],
185                             struct btrfs_file_extent_item);
186         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
187         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
188         btrfs_set_file_extent_encryption(leaf, ei, 0);
189         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
190         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
191         ptr = btrfs_file_extent_inline_start(ei);
192
193         if (compress_type != BTRFS_COMPRESS_NONE) {
194                 struct page *cpage;
195                 int i = 0;
196                 while (compressed_size > 0) {
197                         cpage = compressed_pages[i];
198                         cur_size = min_t(unsigned long, compressed_size,
199                                        PAGE_SIZE);
200
201                         kaddr = kmap_atomic(cpage);
202                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
203                         kunmap_atomic(kaddr);
204
205                         i++;
206                         ptr += cur_size;
207                         compressed_size -= cur_size;
208                 }
209                 btrfs_set_file_extent_compression(leaf, ei,
210                                                   compress_type);
211         } else {
212                 page = find_get_page(inode->i_mapping,
213                                      start >> PAGE_SHIFT);
214                 btrfs_set_file_extent_compression(leaf, ei, 0);
215                 kaddr = kmap_atomic(page);
216                 offset = start & (PAGE_SIZE - 1);
217                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
218                 kunmap_atomic(kaddr);
219                 put_page(page);
220         }
221         btrfs_mark_buffer_dirty(leaf);
222         btrfs_release_path(path);
223
224         /*
225          * we're an inline extent, so nobody can
226          * extend the file past i_size without locking
227          * a page we already have locked.
228          *
229          * We must do any isize and inode updates
230          * before we unlock the pages.  Otherwise we
231          * could end up racing with unlink.
232          */
233         BTRFS_I(inode)->disk_i_size = inode->i_size;
234         ret = btrfs_update_inode(trans, root, inode);
235
236         return ret;
237 fail:
238         return err;
239 }
240
241
242 /*
243  * conditionally insert an inline extent into the file.  This
244  * does the checks required to make sure the data is small enough
245  * to fit as an inline extent.
246  */
247 static noinline int cow_file_range_inline(struct btrfs_root *root,
248                                           struct inode *inode, u64 start,
249                                           u64 end, size_t compressed_size,
250                                           int compress_type,
251                                           struct page **compressed_pages)
252 {
253         struct btrfs_trans_handle *trans;
254         u64 isize = i_size_read(inode);
255         u64 actual_end = min(end + 1, isize);
256         u64 inline_len = actual_end - start;
257         u64 aligned_end = ALIGN(end, root->sectorsize);
258         u64 data_len = inline_len;
259         int ret;
260         struct btrfs_path *path;
261         int extent_inserted = 0;
262         u32 extent_item_size;
263
264         if (compressed_size)
265                 data_len = compressed_size;
266
267         if (start > 0 ||
268             actual_end > root->sectorsize ||
269             data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
270             (!compressed_size &&
271             (actual_end & (root->sectorsize - 1)) == 0) ||
272             end + 1 < isize ||
273             data_len > root->fs_info->max_inline) {
274                 return 1;
275         }
276
277         path = btrfs_alloc_path();
278         if (!path)
279                 return -ENOMEM;
280
281         trans = btrfs_join_transaction(root);
282         if (IS_ERR(trans)) {
283                 btrfs_free_path(path);
284                 return PTR_ERR(trans);
285         }
286         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
287
288         if (compressed_size && compressed_pages)
289                 extent_item_size = btrfs_file_extent_calc_inline_size(
290                    compressed_size);
291         else
292                 extent_item_size = btrfs_file_extent_calc_inline_size(
293                     inline_len);
294
295         ret = __btrfs_drop_extents(trans, root, inode, path,
296                                    start, aligned_end, NULL,
297                                    1, 1, extent_item_size, &extent_inserted);
298         if (ret) {
299                 btrfs_abort_transaction(trans, ret);
300                 goto out;
301         }
302
303         if (isize > actual_end)
304                 inline_len = min_t(u64, isize, actual_end);
305         ret = insert_inline_extent(trans, path, extent_inserted,
306                                    root, inode, start,
307                                    inline_len, compressed_size,
308                                    compress_type, compressed_pages);
309         if (ret && ret != -ENOSPC) {
310                 btrfs_abort_transaction(trans, ret);
311                 goto out;
312         } else if (ret == -ENOSPC) {
313                 ret = 1;
314                 goto out;
315         }
316
317         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
318         btrfs_delalloc_release_metadata(inode, end + 1 - start);
319         btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
320 out:
321         /*
322          * Don't forget to free the reserved space, as for inlined extent
323          * it won't count as data extent, free them directly here.
324          * And at reserve time, it's always aligned to page size, so
325          * just free one page here.
326          */
327         btrfs_qgroup_free_data(inode, 0, PAGE_SIZE);
328         btrfs_free_path(path);
329         btrfs_end_transaction(trans, root);
330         return ret;
331 }
332
333 struct async_extent {
334         u64 start;
335         u64 ram_size;
336         u64 compressed_size;
337         struct page **pages;
338         unsigned long nr_pages;
339         int compress_type;
340         struct list_head list;
341 };
342
343 struct async_cow {
344         struct inode *inode;
345         struct btrfs_root *root;
346         struct page *locked_page;
347         u64 start;
348         u64 end;
349         struct list_head extents;
350         struct btrfs_work work;
351 };
352
353 static noinline int add_async_extent(struct async_cow *cow,
354                                      u64 start, u64 ram_size,
355                                      u64 compressed_size,
356                                      struct page **pages,
357                                      unsigned long nr_pages,
358                                      int compress_type)
359 {
360         struct async_extent *async_extent;
361
362         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
363         BUG_ON(!async_extent); /* -ENOMEM */
364         async_extent->start = start;
365         async_extent->ram_size = ram_size;
366         async_extent->compressed_size = compressed_size;
367         async_extent->pages = pages;
368         async_extent->nr_pages = nr_pages;
369         async_extent->compress_type = compress_type;
370         list_add_tail(&async_extent->list, &cow->extents);
371         return 0;
372 }
373
374 static inline int inode_need_compress(struct inode *inode)
375 {
376         struct btrfs_root *root = BTRFS_I(inode)->root;
377
378         /* force compress */
379         if (btrfs_test_opt(root->fs_info, FORCE_COMPRESS))
380                 return 1;
381         /* bad compression ratios */
382         if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
383                 return 0;
384         if (btrfs_test_opt(root->fs_info, COMPRESS) ||
385             BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
386             BTRFS_I(inode)->force_compress)
387                 return 1;
388         return 0;
389 }
390
391 /*
392  * we create compressed extents in two phases.  The first
393  * phase compresses a range of pages that have already been
394  * locked (both pages and state bits are locked).
395  *
396  * This is done inside an ordered work queue, and the compression
397  * is spread across many cpus.  The actual IO submission is step
398  * two, and the ordered work queue takes care of making sure that
399  * happens in the same order things were put onto the queue by
400  * writepages and friends.
401  *
402  * If this code finds it can't get good compression, it puts an
403  * entry onto the work queue to write the uncompressed bytes.  This
404  * makes sure that both compressed inodes and uncompressed inodes
405  * are written in the same order that the flusher thread sent them
406  * down.
407  */
408 static noinline void compress_file_range(struct inode *inode,
409                                         struct page *locked_page,
410                                         u64 start, u64 end,
411                                         struct async_cow *async_cow,
412                                         int *num_added)
413 {
414         struct btrfs_root *root = BTRFS_I(inode)->root;
415         u64 num_bytes;
416         u64 blocksize = root->sectorsize;
417         u64 actual_end;
418         u64 isize = i_size_read(inode);
419         int ret = 0;
420         struct page **pages = NULL;
421         unsigned long nr_pages;
422         unsigned long nr_pages_ret = 0;
423         unsigned long total_compressed = 0;
424         unsigned long total_in = 0;
425         unsigned long max_compressed = SZ_128K;
426         unsigned long max_uncompressed = SZ_128K;
427         int i;
428         int will_compress;
429         int compress_type = root->fs_info->compress_type;
430         int redirty = 0;
431
432         /* if this is a small write inside eof, kick off a defrag */
433         if ((end - start + 1) < SZ_16K &&
434             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
435                 btrfs_add_inode_defrag(NULL, inode);
436
437         actual_end = min_t(u64, isize, end + 1);
438 again:
439         will_compress = 0;
440         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
441         nr_pages = min_t(unsigned long, nr_pages, SZ_128K / PAGE_SIZE);
442
443         /*
444          * we don't want to send crud past the end of i_size through
445          * compression, that's just a waste of CPU time.  So, if the
446          * end of the file is before the start of our current
447          * requested range of bytes, we bail out to the uncompressed
448          * cleanup code that can deal with all of this.
449          *
450          * It isn't really the fastest way to fix things, but this is a
451          * very uncommon corner.
452          */
453         if (actual_end <= start)
454                 goto cleanup_and_bail_uncompressed;
455
456         total_compressed = actual_end - start;
457
458         /*
459          * skip compression for a small file range(<=blocksize) that
460          * isn't an inline extent, since it doesn't save disk space at all.
461          */
462         if (total_compressed <= blocksize &&
463            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
464                 goto cleanup_and_bail_uncompressed;
465
466         /* we want to make sure that amount of ram required to uncompress
467          * an extent is reasonable, so we limit the total size in ram
468          * of a compressed extent to 128k.  This is a crucial number
469          * because it also controls how easily we can spread reads across
470          * cpus for decompression.
471          *
472          * We also want to make sure the amount of IO required to do
473          * a random read is reasonably small, so we limit the size of
474          * a compressed extent to 128k.
475          */
476         total_compressed = min(total_compressed, max_uncompressed);
477         num_bytes = ALIGN(end - start + 1, blocksize);
478         num_bytes = max(blocksize,  num_bytes);
479         total_in = 0;
480         ret = 0;
481
482         /*
483          * we do compression for mount -o compress and when the
484          * inode has not been flagged as nocompress.  This flag can
485          * change at any time if we discover bad compression ratios.
486          */
487         if (inode_need_compress(inode)) {
488                 WARN_ON(pages);
489                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
490                 if (!pages) {
491                         /* just bail out to the uncompressed code */
492                         goto cont;
493                 }
494
495                 if (BTRFS_I(inode)->force_compress)
496                         compress_type = BTRFS_I(inode)->force_compress;
497
498                 /*
499                  * we need to call clear_page_dirty_for_io on each
500                  * page in the range.  Otherwise applications with the file
501                  * mmap'd can wander in and change the page contents while
502                  * we are compressing them.
503                  *
504                  * If the compression fails for any reason, we set the pages
505                  * dirty again later on.
506                  */
507                 extent_range_clear_dirty_for_io(inode, start, end);
508                 redirty = 1;
509                 ret = btrfs_compress_pages(compress_type,
510                                            inode->i_mapping, start,
511                                            total_compressed, pages,
512                                            nr_pages, &nr_pages_ret,
513                                            &total_in,
514                                            &total_compressed,
515                                            max_compressed);
516
517                 if (!ret) {
518                         unsigned long offset = total_compressed &
519                                 (PAGE_SIZE - 1);
520                         struct page *page = pages[nr_pages_ret - 1];
521                         char *kaddr;
522
523                         /* zero the tail end of the last page, we might be
524                          * sending it down to disk
525                          */
526                         if (offset) {
527                                 kaddr = kmap_atomic(page);
528                                 memset(kaddr + offset, 0,
529                                        PAGE_SIZE - offset);
530                                 kunmap_atomic(kaddr);
531                         }
532                         will_compress = 1;
533                 }
534         }
535 cont:
536         if (start == 0) {
537                 /* lets try to make an inline extent */
538                 if (ret || total_in < (actual_end - start)) {
539                         /* we didn't compress the entire range, try
540                          * to make an uncompressed inline extent.
541                          */
542                         ret = cow_file_range_inline(root, inode, start, end,
543                                                     0, 0, NULL);
544                 } else {
545                         /* try making a compressed inline extent */
546                         ret = cow_file_range_inline(root, inode, start, end,
547                                                     total_compressed,
548                                                     compress_type, pages);
549                 }
550                 if (ret <= 0) {
551                         unsigned long clear_flags = EXTENT_DELALLOC |
552                                 EXTENT_DEFRAG;
553                         unsigned long page_error_op;
554
555                         clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
556                         page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
557
558                         /*
559                          * inline extent creation worked or returned error,
560                          * we don't need to create any more async work items.
561                          * Unlock and free up our temp pages.
562                          */
563                         extent_clear_unlock_delalloc(inode, start, end, NULL,
564                                                      clear_flags, PAGE_UNLOCK |
565                                                      PAGE_CLEAR_DIRTY |
566                                                      PAGE_SET_WRITEBACK |
567                                                      page_error_op |
568                                                      PAGE_END_WRITEBACK);
569                         btrfs_free_reserved_data_space_noquota(inode, start,
570                                                 end - start + 1);
571                         goto free_pages_out;
572                 }
573         }
574
575         if (will_compress) {
576                 /*
577                  * we aren't doing an inline extent round the compressed size
578                  * up to a block size boundary so the allocator does sane
579                  * things
580                  */
581                 total_compressed = ALIGN(total_compressed, blocksize);
582
583                 /*
584                  * one last check to make sure the compression is really a
585                  * win, compare the page count read with the blocks on disk
586                  */
587                 total_in = ALIGN(total_in, PAGE_SIZE);
588                 if (total_compressed >= total_in) {
589                         will_compress = 0;
590                 } else {
591                         num_bytes = total_in;
592                         *num_added += 1;
593
594                         /*
595                          * The async work queues will take care of doing actual
596                          * allocation on disk for these compressed pages, and
597                          * will submit them to the elevator.
598                          */
599                         add_async_extent(async_cow, start, num_bytes,
600                                         total_compressed, pages, nr_pages_ret,
601                                         compress_type);
602
603                         if (start + num_bytes < end) {
604                                 start += num_bytes;
605                                 pages = NULL;
606                                 cond_resched();
607                                 goto again;
608                         }
609                         return;
610                 }
611         }
612         if (pages) {
613                 /*
614                  * the compression code ran but failed to make things smaller,
615                  * free any pages it allocated and our page pointer array
616                  */
617                 for (i = 0; i < nr_pages_ret; i++) {
618                         WARN_ON(pages[i]->mapping);
619                         put_page(pages[i]);
620                 }
621                 kfree(pages);
622                 pages = NULL;
623                 total_compressed = 0;
624                 nr_pages_ret = 0;
625
626                 /* flag the file so we don't compress in the future */
627                 if (!btrfs_test_opt(root->fs_info, FORCE_COMPRESS) &&
628                     !(BTRFS_I(inode)->force_compress)) {
629                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
630                 }
631         }
632 cleanup_and_bail_uncompressed:
633         /*
634          * No compression, but we still need to write the pages in the file
635          * we've been given so far.  redirty the locked page if it corresponds
636          * to our extent and set things up for the async work queue to run
637          * cow_file_range to do the normal delalloc dance.
638          */
639         if (page_offset(locked_page) >= start &&
640             page_offset(locked_page) <= end)
641                 __set_page_dirty_nobuffers(locked_page);
642                 /* unlocked later on in the async handlers */
643
644         if (redirty)
645                 extent_range_redirty_for_io(inode, start, end);
646         add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
647                          BTRFS_COMPRESS_NONE);
648         *num_added += 1;
649
650         return;
651
652 free_pages_out:
653         for (i = 0; i < nr_pages_ret; i++) {
654                 WARN_ON(pages[i]->mapping);
655                 put_page(pages[i]);
656         }
657         kfree(pages);
658 }
659
660 static void free_async_extent_pages(struct async_extent *async_extent)
661 {
662         int i;
663
664         if (!async_extent->pages)
665                 return;
666
667         for (i = 0; i < async_extent->nr_pages; i++) {
668                 WARN_ON(async_extent->pages[i]->mapping);
669                 put_page(async_extent->pages[i]);
670         }
671         kfree(async_extent->pages);
672         async_extent->nr_pages = 0;
673         async_extent->pages = NULL;
674 }
675
676 /*
677  * phase two of compressed writeback.  This is the ordered portion
678  * of the code, which only gets called in the order the work was
679  * queued.  We walk all the async extents created by compress_file_range
680  * and send them down to the disk.
681  */
682 static noinline void submit_compressed_extents(struct inode *inode,
683                                               struct async_cow *async_cow)
684 {
685         struct async_extent *async_extent;
686         u64 alloc_hint = 0;
687         struct btrfs_key ins;
688         struct extent_map *em;
689         struct btrfs_root *root = BTRFS_I(inode)->root;
690         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
691         struct extent_io_tree *io_tree;
692         int ret = 0;
693
694 again:
695         while (!list_empty(&async_cow->extents)) {
696                 async_extent = list_entry(async_cow->extents.next,
697                                           struct async_extent, list);
698                 list_del(&async_extent->list);
699
700                 io_tree = &BTRFS_I(inode)->io_tree;
701
702 retry:
703                 /* did the compression code fall back to uncompressed IO? */
704                 if (!async_extent->pages) {
705                         int page_started = 0;
706                         unsigned long nr_written = 0;
707
708                         lock_extent(io_tree, async_extent->start,
709                                          async_extent->start +
710                                          async_extent->ram_size - 1);
711
712                         /* allocate blocks */
713                         ret = cow_file_range(inode, async_cow->locked_page,
714                                              async_extent->start,
715                                              async_extent->start +
716                                              async_extent->ram_size - 1,
717                                              async_extent->start +
718                                              async_extent->ram_size - 1,
719                                              &page_started, &nr_written, 0,
720                                              NULL);
721
722                         /* JDM XXX */
723
724                         /*
725                          * if page_started, cow_file_range inserted an
726                          * inline extent and took care of all the unlocking
727                          * and IO for us.  Otherwise, we need to submit
728                          * all those pages down to the drive.
729                          */
730                         if (!page_started && !ret)
731                                 extent_write_locked_range(io_tree,
732                                                   inode, async_extent->start,
733                                                   async_extent->start +
734                                                   async_extent->ram_size - 1,
735                                                   btrfs_get_extent,
736                                                   WB_SYNC_ALL);
737                         else if (ret)
738                                 unlock_page(async_cow->locked_page);
739                         kfree(async_extent);
740                         cond_resched();
741                         continue;
742                 }
743
744                 lock_extent(io_tree, async_extent->start,
745                             async_extent->start + async_extent->ram_size - 1);
746
747                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
748                                            async_extent->compressed_size,
749                                            async_extent->compressed_size,
750                                            0, alloc_hint, &ins, 1, 1);
751                 if (ret) {
752                         free_async_extent_pages(async_extent);
753
754                         if (ret == -ENOSPC) {
755                                 unlock_extent(io_tree, async_extent->start,
756                                               async_extent->start +
757                                               async_extent->ram_size - 1);
758
759                                 /*
760                                  * we need to redirty the pages if we decide to
761                                  * fallback to uncompressed IO, otherwise we
762                                  * will not submit these pages down to lower
763                                  * layers.
764                                  */
765                                 extent_range_redirty_for_io(inode,
766                                                 async_extent->start,
767                                                 async_extent->start +
768                                                 async_extent->ram_size - 1);
769
770                                 goto retry;
771                         }
772                         goto out_free;
773                 }
774                 /*
775                  * here we're doing allocation and writeback of the
776                  * compressed pages
777                  */
778                 btrfs_drop_extent_cache(inode, async_extent->start,
779                                         async_extent->start +
780                                         async_extent->ram_size - 1, 0);
781
782                 em = alloc_extent_map();
783                 if (!em) {
784                         ret = -ENOMEM;
785                         goto out_free_reserve;
786                 }
787                 em->start = async_extent->start;
788                 em->len = async_extent->ram_size;
789                 em->orig_start = em->start;
790                 em->mod_start = em->start;
791                 em->mod_len = em->len;
792
793                 em->block_start = ins.objectid;
794                 em->block_len = ins.offset;
795                 em->orig_block_len = ins.offset;
796                 em->ram_bytes = async_extent->ram_size;
797                 em->bdev = root->fs_info->fs_devices->latest_bdev;
798                 em->compress_type = async_extent->compress_type;
799                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
800                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
801                 em->generation = -1;
802
803                 while (1) {
804                         write_lock(&em_tree->lock);
805                         ret = add_extent_mapping(em_tree, em, 1);
806                         write_unlock(&em_tree->lock);
807                         if (ret != -EEXIST) {
808                                 free_extent_map(em);
809                                 break;
810                         }
811                         btrfs_drop_extent_cache(inode, async_extent->start,
812                                                 async_extent->start +
813                                                 async_extent->ram_size - 1, 0);
814                 }
815
816                 if (ret)
817                         goto out_free_reserve;
818
819                 ret = btrfs_add_ordered_extent_compress(inode,
820                                                 async_extent->start,
821                                                 ins.objectid,
822                                                 async_extent->ram_size,
823                                                 ins.offset,
824                                                 BTRFS_ORDERED_COMPRESSED,
825                                                 async_extent->compress_type);
826                 if (ret) {
827                         btrfs_drop_extent_cache(inode, async_extent->start,
828                                                 async_extent->start +
829                                                 async_extent->ram_size - 1, 0);
830                         goto out_free_reserve;
831                 }
832                 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
833
834                 /*
835                  * clear dirty, set writeback and unlock the pages.
836                  */
837                 extent_clear_unlock_delalloc(inode, async_extent->start,
838                                 async_extent->start +
839                                 async_extent->ram_size - 1,
840                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
841                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
842                                 PAGE_SET_WRITEBACK);
843                 ret = btrfs_submit_compressed_write(inode,
844                                     async_extent->start,
845                                     async_extent->ram_size,
846                                     ins.objectid,
847                                     ins.offset, async_extent->pages,
848                                     async_extent->nr_pages);
849                 if (ret) {
850                         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
851                         struct page *p = async_extent->pages[0];
852                         const u64 start = async_extent->start;
853                         const u64 end = start + async_extent->ram_size - 1;
854
855                         p->mapping = inode->i_mapping;
856                         tree->ops->writepage_end_io_hook(p, start, end,
857                                                          NULL, 0);
858                         p->mapping = NULL;
859                         extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
860                                                      PAGE_END_WRITEBACK |
861                                                      PAGE_SET_ERROR);
862                         free_async_extent_pages(async_extent);
863                 }
864                 alloc_hint = ins.objectid + ins.offset;
865                 kfree(async_extent);
866                 cond_resched();
867         }
868         return;
869 out_free_reserve:
870         btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
871         btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
872 out_free:
873         extent_clear_unlock_delalloc(inode, async_extent->start,
874                                      async_extent->start +
875                                      async_extent->ram_size - 1,
876                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
877                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
878                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
879                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
880                                      PAGE_SET_ERROR);
881         free_async_extent_pages(async_extent);
882         kfree(async_extent);
883         goto again;
884 }
885
886 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
887                                       u64 num_bytes)
888 {
889         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
890         struct extent_map *em;
891         u64 alloc_hint = 0;
892
893         read_lock(&em_tree->lock);
894         em = search_extent_mapping(em_tree, start, num_bytes);
895         if (em) {
896                 /*
897                  * if block start isn't an actual block number then find the
898                  * first block in this inode and use that as a hint.  If that
899                  * block is also bogus then just don't worry about it.
900                  */
901                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
902                         free_extent_map(em);
903                         em = search_extent_mapping(em_tree, 0, 0);
904                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
905                                 alloc_hint = em->block_start;
906                         if (em)
907                                 free_extent_map(em);
908                 } else {
909                         alloc_hint = em->block_start;
910                         free_extent_map(em);
911                 }
912         }
913         read_unlock(&em_tree->lock);
914
915         return alloc_hint;
916 }
917
918 /*
919  * when extent_io.c finds a delayed allocation range in the file,
920  * the call backs end up in this code.  The basic idea is to
921  * allocate extents on disk for the range, and create ordered data structs
922  * in ram to track those extents.
923  *
924  * locked_page is the page that writepage had locked already.  We use
925  * it to make sure we don't do extra locks or unlocks.
926  *
927  * *page_started is set to one if we unlock locked_page and do everything
928  * required to start IO on it.  It may be clean and already done with
929  * IO when we return.
930  */
931 static noinline int cow_file_range(struct inode *inode,
932                                    struct page *locked_page,
933                                    u64 start, u64 end, u64 delalloc_end,
934                                    int *page_started, unsigned long *nr_written,
935                                    int unlock, struct btrfs_dedupe_hash *hash)
936 {
937         struct btrfs_root *root = BTRFS_I(inode)->root;
938         u64 alloc_hint = 0;
939         u64 num_bytes;
940         unsigned long ram_size;
941         u64 disk_num_bytes;
942         u64 cur_alloc_size;
943         u64 blocksize = root->sectorsize;
944         struct btrfs_key ins;
945         struct extent_map *em;
946         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
947         int ret = 0;
948
949         if (btrfs_is_free_space_inode(inode)) {
950                 WARN_ON_ONCE(1);
951                 ret = -EINVAL;
952                 goto out_unlock;
953         }
954
955         num_bytes = ALIGN(end - start + 1, blocksize);
956         num_bytes = max(blocksize,  num_bytes);
957         disk_num_bytes = num_bytes;
958
959         /* if this is a small write inside eof, kick off defrag */
960         if (num_bytes < SZ_64K &&
961             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
962                 btrfs_add_inode_defrag(NULL, inode);
963
964         if (start == 0) {
965                 /* lets try to make an inline extent */
966                 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
967                                             NULL);
968                 if (ret == 0) {
969                         extent_clear_unlock_delalloc(inode, start, end, NULL,
970                                      EXTENT_LOCKED | EXTENT_DELALLOC |
971                                      EXTENT_DEFRAG, PAGE_UNLOCK |
972                                      PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
973                                      PAGE_END_WRITEBACK);
974                         btrfs_free_reserved_data_space_noquota(inode, start,
975                                                 end - start + 1);
976                         *nr_written = *nr_written +
977                              (end - start + PAGE_SIZE) / PAGE_SIZE;
978                         *page_started = 1;
979                         goto out;
980                 } else if (ret < 0) {
981                         goto out_unlock;
982                 }
983         }
984
985         BUG_ON(disk_num_bytes >
986                btrfs_super_total_bytes(root->fs_info->super_copy));
987
988         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
989         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
990
991         while (disk_num_bytes > 0) {
992                 unsigned long op;
993
994                 cur_alloc_size = disk_num_bytes;
995                 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
996                                            root->sectorsize, 0, alloc_hint,
997                                            &ins, 1, 1);
998                 if (ret < 0)
999                         goto out_unlock;
1000
1001                 em = alloc_extent_map();
1002                 if (!em) {
1003                         ret = -ENOMEM;
1004                         goto out_reserve;
1005                 }
1006                 em->start = start;
1007                 em->orig_start = em->start;
1008                 ram_size = ins.offset;
1009                 em->len = ins.offset;
1010                 em->mod_start = em->start;
1011                 em->mod_len = em->len;
1012
1013                 em->block_start = ins.objectid;
1014                 em->block_len = ins.offset;
1015                 em->orig_block_len = ins.offset;
1016                 em->ram_bytes = ram_size;
1017                 em->bdev = root->fs_info->fs_devices->latest_bdev;
1018                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1019                 em->generation = -1;
1020
1021                 while (1) {
1022                         write_lock(&em_tree->lock);
1023                         ret = add_extent_mapping(em_tree, em, 1);
1024                         write_unlock(&em_tree->lock);
1025                         if (ret != -EEXIST) {
1026                                 free_extent_map(em);
1027                                 break;
1028                         }
1029                         btrfs_drop_extent_cache(inode, start,
1030                                                 start + ram_size - 1, 0);
1031                 }
1032                 if (ret)
1033                         goto out_reserve;
1034
1035                 cur_alloc_size = ins.offset;
1036                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1037                                                ram_size, cur_alloc_size, 0);
1038                 if (ret)
1039                         goto out_drop_extent_cache;
1040
1041                 if (root->root_key.objectid ==
1042                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1043                         ret = btrfs_reloc_clone_csums(inode, start,
1044                                                       cur_alloc_size);
1045                         if (ret)
1046                                 goto out_drop_extent_cache;
1047                 }
1048
1049                 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1050
1051                 if (disk_num_bytes < cur_alloc_size)
1052                         break;
1053
1054                 /* we're not doing compressed IO, don't unlock the first
1055                  * page (which the caller expects to stay locked), don't
1056                  * clear any dirty bits and don't set any writeback bits
1057                  *
1058                  * Do set the Private2 bit so we know this page was properly
1059                  * setup for writepage
1060                  */
1061                 op = unlock ? PAGE_UNLOCK : 0;
1062                 op |= PAGE_SET_PRIVATE2;
1063
1064                 extent_clear_unlock_delalloc(inode, start,
1065                                              start + ram_size - 1, locked_page,
1066                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1067                                              op);
1068                 disk_num_bytes -= cur_alloc_size;
1069                 num_bytes -= cur_alloc_size;
1070                 alloc_hint = ins.objectid + ins.offset;
1071                 start += cur_alloc_size;
1072         }
1073 out:
1074         return ret;
1075
1076 out_drop_extent_cache:
1077         btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1078 out_reserve:
1079         btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1080         btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1081 out_unlock:
1082         extent_clear_unlock_delalloc(inode, start, end, locked_page,
1083                                      EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1084                                      EXTENT_DELALLOC | EXTENT_DEFRAG,
1085                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1086                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1087         goto out;
1088 }
1089
1090 /*
1091  * work queue call back to started compression on a file and pages
1092  */
1093 static noinline void async_cow_start(struct btrfs_work *work)
1094 {
1095         struct async_cow *async_cow;
1096         int num_added = 0;
1097         async_cow = container_of(work, struct async_cow, work);
1098
1099         compress_file_range(async_cow->inode, async_cow->locked_page,
1100                             async_cow->start, async_cow->end, async_cow,
1101                             &num_added);
1102         if (num_added == 0) {
1103                 btrfs_add_delayed_iput(async_cow->inode);
1104                 async_cow->inode = NULL;
1105         }
1106 }
1107
1108 /*
1109  * work queue call back to submit previously compressed pages
1110  */
1111 static noinline void async_cow_submit(struct btrfs_work *work)
1112 {
1113         struct async_cow *async_cow;
1114         struct btrfs_root *root;
1115         unsigned long nr_pages;
1116
1117         async_cow = container_of(work, struct async_cow, work);
1118
1119         root = async_cow->root;
1120         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1121                 PAGE_SHIFT;
1122
1123         /*
1124          * atomic_sub_return implies a barrier for waitqueue_active
1125          */
1126         if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1127             5 * SZ_1M &&
1128             waitqueue_active(&root->fs_info->async_submit_wait))
1129                 wake_up(&root->fs_info->async_submit_wait);
1130
1131         if (async_cow->inode)
1132                 submit_compressed_extents(async_cow->inode, async_cow);
1133 }
1134
1135 static noinline void async_cow_free(struct btrfs_work *work)
1136 {
1137         struct async_cow *async_cow;
1138         async_cow = container_of(work, struct async_cow, work);
1139         if (async_cow->inode)
1140                 btrfs_add_delayed_iput(async_cow->inode);
1141         kfree(async_cow);
1142 }
1143
1144 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1145                                 u64 start, u64 end, int *page_started,
1146                                 unsigned long *nr_written)
1147 {
1148         struct async_cow *async_cow;
1149         struct btrfs_root *root = BTRFS_I(inode)->root;
1150         unsigned long nr_pages;
1151         u64 cur_end;
1152         int limit = 10 * SZ_1M;
1153
1154         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1155                          1, 0, NULL, GFP_NOFS);
1156         while (start < end) {
1157                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1158                 BUG_ON(!async_cow); /* -ENOMEM */
1159                 async_cow->inode = igrab(inode);
1160                 async_cow->root = root;
1161                 async_cow->locked_page = locked_page;
1162                 async_cow->start = start;
1163
1164                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1165                     !btrfs_test_opt(root->fs_info, FORCE_COMPRESS))
1166                         cur_end = end;
1167                 else
1168                         cur_end = min(end, start + SZ_512K - 1);
1169
1170                 async_cow->end = cur_end;
1171                 INIT_LIST_HEAD(&async_cow->extents);
1172
1173                 btrfs_init_work(&async_cow->work,
1174                                 btrfs_delalloc_helper,
1175                                 async_cow_start, async_cow_submit,
1176                                 async_cow_free);
1177
1178                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1179                         PAGE_SHIFT;
1180                 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1181
1182                 btrfs_queue_work(root->fs_info->delalloc_workers,
1183                                  &async_cow->work);
1184
1185                 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1186                         wait_event(root->fs_info->async_submit_wait,
1187                            (atomic_read(&root->fs_info->async_delalloc_pages) <
1188                             limit));
1189                 }
1190
1191                 while (atomic_read(&root->fs_info->async_submit_draining) &&
1192                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1193                         wait_event(root->fs_info->async_submit_wait,
1194                           (atomic_read(&root->fs_info->async_delalloc_pages) ==
1195                            0));
1196                 }
1197
1198                 *nr_written += nr_pages;
1199                 start = cur_end + 1;
1200         }
1201         *page_started = 1;
1202         return 0;
1203 }
1204
1205 static noinline int csum_exist_in_range(struct btrfs_root *root,
1206                                         u64 bytenr, u64 num_bytes)
1207 {
1208         int ret;
1209         struct btrfs_ordered_sum *sums;
1210         LIST_HEAD(list);
1211
1212         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1213                                        bytenr + num_bytes - 1, &list, 0);
1214         if (ret == 0 && list_empty(&list))
1215                 return 0;
1216
1217         while (!list_empty(&list)) {
1218                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1219                 list_del(&sums->list);
1220                 kfree(sums);
1221         }
1222         return 1;
1223 }
1224
1225 /*
1226  * when nowcow writeback call back.  This checks for snapshots or COW copies
1227  * of the extents that exist in the file, and COWs the file as required.
1228  *
1229  * If no cow copies or snapshots exist, we write directly to the existing
1230  * blocks on disk
1231  */
1232 static noinline int run_delalloc_nocow(struct inode *inode,
1233                                        struct page *locked_page,
1234                               u64 start, u64 end, int *page_started, int force,
1235                               unsigned long *nr_written)
1236 {
1237         struct btrfs_root *root = BTRFS_I(inode)->root;
1238         struct btrfs_trans_handle *trans;
1239         struct extent_buffer *leaf;
1240         struct btrfs_path *path;
1241         struct btrfs_file_extent_item *fi;
1242         struct btrfs_key found_key;
1243         u64 cow_start;
1244         u64 cur_offset;
1245         u64 extent_end;
1246         u64 extent_offset;
1247         u64 disk_bytenr;
1248         u64 num_bytes;
1249         u64 disk_num_bytes;
1250         u64 ram_bytes;
1251         int extent_type;
1252         int ret, err;
1253         int type;
1254         int nocow;
1255         int check_prev = 1;
1256         bool nolock;
1257         u64 ino = btrfs_ino(inode);
1258
1259         path = btrfs_alloc_path();
1260         if (!path) {
1261                 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1262                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1263                                              EXTENT_DO_ACCOUNTING |
1264                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1265                                              PAGE_CLEAR_DIRTY |
1266                                              PAGE_SET_WRITEBACK |
1267                                              PAGE_END_WRITEBACK);
1268                 return -ENOMEM;
1269         }
1270
1271         nolock = btrfs_is_free_space_inode(inode);
1272
1273         if (nolock)
1274                 trans = btrfs_join_transaction_nolock(root);
1275         else
1276                 trans = btrfs_join_transaction(root);
1277
1278         if (IS_ERR(trans)) {
1279                 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1280                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1281                                              EXTENT_DO_ACCOUNTING |
1282                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1283                                              PAGE_CLEAR_DIRTY |
1284                                              PAGE_SET_WRITEBACK |
1285                                              PAGE_END_WRITEBACK);
1286                 btrfs_free_path(path);
1287                 return PTR_ERR(trans);
1288         }
1289
1290         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1291
1292         cow_start = (u64)-1;
1293         cur_offset = start;
1294         while (1) {
1295                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1296                                                cur_offset, 0);
1297                 if (ret < 0)
1298                         goto error;
1299                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1300                         leaf = path->nodes[0];
1301                         btrfs_item_key_to_cpu(leaf, &found_key,
1302                                               path->slots[0] - 1);
1303                         if (found_key.objectid == ino &&
1304                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1305                                 path->slots[0]--;
1306                 }
1307                 check_prev = 0;
1308 next_slot:
1309                 leaf = path->nodes[0];
1310                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1311                         ret = btrfs_next_leaf(root, path);
1312                         if (ret < 0)
1313                                 goto error;
1314                         if (ret > 0)
1315                                 break;
1316                         leaf = path->nodes[0];
1317                 }
1318
1319                 nocow = 0;
1320                 disk_bytenr = 0;
1321                 num_bytes = 0;
1322                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1323
1324                 if (found_key.objectid > ino)
1325                         break;
1326                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1327                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1328                         path->slots[0]++;
1329                         goto next_slot;
1330                 }
1331                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1332                     found_key.offset > end)
1333                         break;
1334
1335                 if (found_key.offset > cur_offset) {
1336                         extent_end = found_key.offset;
1337                         extent_type = 0;
1338                         goto out_check;
1339                 }
1340
1341                 fi = btrfs_item_ptr(leaf, path->slots[0],
1342                                     struct btrfs_file_extent_item);
1343                 extent_type = btrfs_file_extent_type(leaf, fi);
1344
1345                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1346                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1347                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1348                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1349                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1350                         extent_end = found_key.offset +
1351                                 btrfs_file_extent_num_bytes(leaf, fi);
1352                         disk_num_bytes =
1353                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1354                         if (extent_end <= start) {
1355                                 path->slots[0]++;
1356                                 goto next_slot;
1357                         }
1358                         if (disk_bytenr == 0)
1359                                 goto out_check;
1360                         if (btrfs_file_extent_compression(leaf, fi) ||
1361                             btrfs_file_extent_encryption(leaf, fi) ||
1362                             btrfs_file_extent_other_encoding(leaf, fi))
1363                                 goto out_check;
1364                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1365                                 goto out_check;
1366                         if (btrfs_extent_readonly(root, disk_bytenr))
1367                                 goto out_check;
1368                         if (btrfs_cross_ref_exist(trans, root, ino,
1369                                                   found_key.offset -
1370                                                   extent_offset, disk_bytenr))
1371                                 goto out_check;
1372                         disk_bytenr += extent_offset;
1373                         disk_bytenr += cur_offset - found_key.offset;
1374                         num_bytes = min(end + 1, extent_end) - cur_offset;
1375                         /*
1376                          * if there are pending snapshots for this root,
1377                          * we fall into common COW way.
1378                          */
1379                         if (!nolock) {
1380                                 err = btrfs_start_write_no_snapshoting(root);
1381                                 if (!err)
1382                                         goto out_check;
1383                         }
1384                         /*
1385                          * force cow if csum exists in the range.
1386                          * this ensure that csum for a given extent are
1387                          * either valid or do not exist.
1388                          */
1389                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1390                                 goto out_check;
1391                         if (!btrfs_inc_nocow_writers(root->fs_info,
1392                                                      disk_bytenr))
1393                                 goto out_check;
1394                         nocow = 1;
1395                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1396                         extent_end = found_key.offset +
1397                                 btrfs_file_extent_inline_len(leaf,
1398                                                      path->slots[0], fi);
1399                         extent_end = ALIGN(extent_end, root->sectorsize);
1400                 } else {
1401                         BUG_ON(1);
1402                 }
1403 out_check:
1404                 if (extent_end <= start) {
1405                         path->slots[0]++;
1406                         if (!nolock && nocow)
1407                                 btrfs_end_write_no_snapshoting(root);
1408                         if (nocow)
1409                                 btrfs_dec_nocow_writers(root->fs_info,
1410                                                         disk_bytenr);
1411                         goto next_slot;
1412                 }
1413                 if (!nocow) {
1414                         if (cow_start == (u64)-1)
1415                                 cow_start = cur_offset;
1416                         cur_offset = extent_end;
1417                         if (cur_offset > end)
1418                                 break;
1419                         path->slots[0]++;
1420                         goto next_slot;
1421                 }
1422
1423                 btrfs_release_path(path);
1424                 if (cow_start != (u64)-1) {
1425                         ret = cow_file_range(inode, locked_page,
1426                                              cow_start, found_key.offset - 1,
1427                                              end, page_started, nr_written, 1,
1428                                              NULL);
1429                         if (ret) {
1430                                 if (!nolock && nocow)
1431                                         btrfs_end_write_no_snapshoting(root);
1432                                 if (nocow)
1433                                         btrfs_dec_nocow_writers(root->fs_info,
1434                                                                 disk_bytenr);
1435                                 goto error;
1436                         }
1437                         cow_start = (u64)-1;
1438                 }
1439
1440                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1441                         struct extent_map *em;
1442                         struct extent_map_tree *em_tree;
1443                         em_tree = &BTRFS_I(inode)->extent_tree;
1444                         em = alloc_extent_map();
1445                         BUG_ON(!em); /* -ENOMEM */
1446                         em->start = cur_offset;
1447                         em->orig_start = found_key.offset - extent_offset;
1448                         em->len = num_bytes;
1449                         em->block_len = num_bytes;
1450                         em->block_start = disk_bytenr;
1451                         em->orig_block_len = disk_num_bytes;
1452                         em->ram_bytes = ram_bytes;
1453                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1454                         em->mod_start = em->start;
1455                         em->mod_len = em->len;
1456                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1457                         set_bit(EXTENT_FLAG_FILLING, &em->flags);
1458                         em->generation = -1;
1459                         while (1) {
1460                                 write_lock(&em_tree->lock);
1461                                 ret = add_extent_mapping(em_tree, em, 1);
1462                                 write_unlock(&em_tree->lock);
1463                                 if (ret != -EEXIST) {
1464                                         free_extent_map(em);
1465                                         break;
1466                                 }
1467                                 btrfs_drop_extent_cache(inode, em->start,
1468                                                 em->start + em->len - 1, 0);
1469                         }
1470                         type = BTRFS_ORDERED_PREALLOC;
1471                 } else {
1472                         type = BTRFS_ORDERED_NOCOW;
1473                 }
1474
1475                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1476                                                num_bytes, num_bytes, type);
1477                 if (nocow)
1478                         btrfs_dec_nocow_writers(root->fs_info, disk_bytenr);
1479                 BUG_ON(ret); /* -ENOMEM */
1480
1481                 if (root->root_key.objectid ==
1482                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1483                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1484                                                       num_bytes);
1485                         if (ret) {
1486                                 if (!nolock && nocow)
1487                                         btrfs_end_write_no_snapshoting(root);
1488                                 goto error;
1489                         }
1490                 }
1491
1492                 extent_clear_unlock_delalloc(inode, cur_offset,
1493                                              cur_offset + num_bytes - 1,
1494                                              locked_page, EXTENT_LOCKED |
1495                                              EXTENT_DELALLOC |
1496                                              EXTENT_CLEAR_DATA_RESV,
1497                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1498
1499                 if (!nolock && nocow)
1500                         btrfs_end_write_no_snapshoting(root);
1501                 cur_offset = extent_end;
1502                 if (cur_offset > end)
1503                         break;
1504         }
1505         btrfs_release_path(path);
1506
1507         if (cur_offset <= end && cow_start == (u64)-1) {
1508                 cow_start = cur_offset;
1509                 cur_offset = end;
1510         }
1511
1512         if (cow_start != (u64)-1) {
1513                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1514                                      page_started, nr_written, 1, NULL);
1515                 if (ret)
1516                         goto error;
1517         }
1518
1519 error:
1520         err = btrfs_end_transaction(trans, root);
1521         if (!ret)
1522                 ret = err;
1523
1524         if (ret && cur_offset < end)
1525                 extent_clear_unlock_delalloc(inode, cur_offset, end,
1526                                              locked_page, EXTENT_LOCKED |
1527                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1528                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1529                                              PAGE_CLEAR_DIRTY |
1530                                              PAGE_SET_WRITEBACK |
1531                                              PAGE_END_WRITEBACK);
1532         btrfs_free_path(path);
1533         return ret;
1534 }
1535
1536 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1537 {
1538
1539         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1540             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1541                 return 0;
1542
1543         /*
1544          * @defrag_bytes is a hint value, no spinlock held here,
1545          * if is not zero, it means the file is defragging.
1546          * Force cow if given extent needs to be defragged.
1547          */
1548         if (BTRFS_I(inode)->defrag_bytes &&
1549             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1550                            EXTENT_DEFRAG, 0, NULL))
1551                 return 1;
1552
1553         return 0;
1554 }
1555
1556 /*
1557  * extent_io.c call back to do delayed allocation processing
1558  */
1559 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1560                               u64 start, u64 end, int *page_started,
1561                               unsigned long *nr_written)
1562 {
1563         int ret;
1564         int force_cow = need_force_cow(inode, start, end);
1565
1566         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1567                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1568                                          page_started, 1, nr_written);
1569         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1570                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1571                                          page_started, 0, nr_written);
1572         } else if (!inode_need_compress(inode)) {
1573                 ret = cow_file_range(inode, locked_page, start, end, end,
1574                                       page_started, nr_written, 1, NULL);
1575         } else {
1576                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1577                         &BTRFS_I(inode)->runtime_flags);
1578                 ret = cow_file_range_async(inode, locked_page, start, end,
1579                                            page_started, nr_written);
1580         }
1581         return ret;
1582 }
1583
1584 static void btrfs_split_extent_hook(struct inode *inode,
1585                                     struct extent_state *orig, u64 split)
1586 {
1587         u64 size;
1588
1589         /* not delalloc, ignore it */
1590         if (!(orig->state & EXTENT_DELALLOC))
1591                 return;
1592
1593         size = orig->end - orig->start + 1;
1594         if (size > BTRFS_MAX_EXTENT_SIZE) {
1595                 u64 num_extents;
1596                 u64 new_size;
1597
1598                 /*
1599                  * See the explanation in btrfs_merge_extent_hook, the same
1600                  * applies here, just in reverse.
1601                  */
1602                 new_size = orig->end - split + 1;
1603                 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1604                                         BTRFS_MAX_EXTENT_SIZE);
1605                 new_size = split - orig->start;
1606                 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1607                                         BTRFS_MAX_EXTENT_SIZE);
1608                 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1609                               BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1610                         return;
1611         }
1612
1613         spin_lock(&BTRFS_I(inode)->lock);
1614         BTRFS_I(inode)->outstanding_extents++;
1615         spin_unlock(&BTRFS_I(inode)->lock);
1616 }
1617
1618 /*
1619  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1620  * extents so we can keep track of new extents that are just merged onto old
1621  * extents, such as when we are doing sequential writes, so we can properly
1622  * account for the metadata space we'll need.
1623  */
1624 static void btrfs_merge_extent_hook(struct inode *inode,
1625                                     struct extent_state *new,
1626                                     struct extent_state *other)
1627 {
1628         u64 new_size, old_size;
1629         u64 num_extents;
1630
1631         /* not delalloc, ignore it */
1632         if (!(other->state & EXTENT_DELALLOC))
1633                 return;
1634
1635         if (new->start > other->start)
1636                 new_size = new->end - other->start + 1;
1637         else
1638                 new_size = other->end - new->start + 1;
1639
1640         /* we're not bigger than the max, unreserve the space and go */
1641         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1642                 spin_lock(&BTRFS_I(inode)->lock);
1643                 BTRFS_I(inode)->outstanding_extents--;
1644                 spin_unlock(&BTRFS_I(inode)->lock);
1645                 return;
1646         }
1647
1648         /*
1649          * We have to add up either side to figure out how many extents were
1650          * accounted for before we merged into one big extent.  If the number of
1651          * extents we accounted for is <= the amount we need for the new range
1652          * then we can return, otherwise drop.  Think of it like this
1653          *
1654          * [ 4k][MAX_SIZE]
1655          *
1656          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1657          * need 2 outstanding extents, on one side we have 1 and the other side
1658          * we have 1 so they are == and we can return.  But in this case
1659          *
1660          * [MAX_SIZE+4k][MAX_SIZE+4k]
1661          *
1662          * Each range on their own accounts for 2 extents, but merged together
1663          * they are only 3 extents worth of accounting, so we need to drop in
1664          * this case.
1665          */
1666         old_size = other->end - other->start + 1;
1667         num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1668                                 BTRFS_MAX_EXTENT_SIZE);
1669         old_size = new->end - new->start + 1;
1670         num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1671                                  BTRFS_MAX_EXTENT_SIZE);
1672
1673         if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1674                       BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1675                 return;
1676
1677         spin_lock(&BTRFS_I(inode)->lock);
1678         BTRFS_I(inode)->outstanding_extents--;
1679         spin_unlock(&BTRFS_I(inode)->lock);
1680 }
1681
1682 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1683                                       struct inode *inode)
1684 {
1685         spin_lock(&root->delalloc_lock);
1686         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1687                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1688                               &root->delalloc_inodes);
1689                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1690                         &BTRFS_I(inode)->runtime_flags);
1691                 root->nr_delalloc_inodes++;
1692                 if (root->nr_delalloc_inodes == 1) {
1693                         spin_lock(&root->fs_info->delalloc_root_lock);
1694                         BUG_ON(!list_empty(&root->delalloc_root));
1695                         list_add_tail(&root->delalloc_root,
1696                                       &root->fs_info->delalloc_roots);
1697                         spin_unlock(&root->fs_info->delalloc_root_lock);
1698                 }
1699         }
1700         spin_unlock(&root->delalloc_lock);
1701 }
1702
1703 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1704                                      struct inode *inode)
1705 {
1706         spin_lock(&root->delalloc_lock);
1707         if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1708                 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1709                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1710                           &BTRFS_I(inode)->runtime_flags);
1711                 root->nr_delalloc_inodes--;
1712                 if (!root->nr_delalloc_inodes) {
1713                         spin_lock(&root->fs_info->delalloc_root_lock);
1714                         BUG_ON(list_empty(&root->delalloc_root));
1715                         list_del_init(&root->delalloc_root);
1716                         spin_unlock(&root->fs_info->delalloc_root_lock);
1717                 }
1718         }
1719         spin_unlock(&root->delalloc_lock);
1720 }
1721
1722 /*
1723  * extent_io.c set_bit_hook, used to track delayed allocation
1724  * bytes in this file, and to maintain the list of inodes that
1725  * have pending delalloc work to be done.
1726  */
1727 static void btrfs_set_bit_hook(struct inode *inode,
1728                                struct extent_state *state, unsigned *bits)
1729 {
1730
1731         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1732                 WARN_ON(1);
1733         /*
1734          * set_bit and clear bit hooks normally require _irqsave/restore
1735          * but in this case, we are only testing for the DELALLOC
1736          * bit, which is only set or cleared with irqs on
1737          */
1738         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1739                 struct btrfs_root *root = BTRFS_I(inode)->root;
1740                 u64 len = state->end + 1 - state->start;
1741                 bool do_list = !btrfs_is_free_space_inode(inode);
1742
1743                 if (*bits & EXTENT_FIRST_DELALLOC) {
1744                         *bits &= ~EXTENT_FIRST_DELALLOC;
1745                 } else {
1746                         spin_lock(&BTRFS_I(inode)->lock);
1747                         BTRFS_I(inode)->outstanding_extents++;
1748                         spin_unlock(&BTRFS_I(inode)->lock);
1749                 }
1750
1751                 /* For sanity tests */
1752                 if (btrfs_is_testing(root->fs_info))
1753                         return;
1754
1755                 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1756                                      root->fs_info->delalloc_batch);
1757                 spin_lock(&BTRFS_I(inode)->lock);
1758                 BTRFS_I(inode)->delalloc_bytes += len;
1759                 if (*bits & EXTENT_DEFRAG)
1760                         BTRFS_I(inode)->defrag_bytes += len;
1761                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1762                                          &BTRFS_I(inode)->runtime_flags))
1763                         btrfs_add_delalloc_inodes(root, inode);
1764                 spin_unlock(&BTRFS_I(inode)->lock);
1765         }
1766 }
1767
1768 /*
1769  * extent_io.c clear_bit_hook, see set_bit_hook for why
1770  */
1771 static void btrfs_clear_bit_hook(struct inode *inode,
1772                                  struct extent_state *state,
1773                                  unsigned *bits)
1774 {
1775         u64 len = state->end + 1 - state->start;
1776         u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1777                                     BTRFS_MAX_EXTENT_SIZE);
1778
1779         spin_lock(&BTRFS_I(inode)->lock);
1780         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1781                 BTRFS_I(inode)->defrag_bytes -= len;
1782         spin_unlock(&BTRFS_I(inode)->lock);
1783
1784         /*
1785          * set_bit and clear bit hooks normally require _irqsave/restore
1786          * but in this case, we are only testing for the DELALLOC
1787          * bit, which is only set or cleared with irqs on
1788          */
1789         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1790                 struct btrfs_root *root = BTRFS_I(inode)->root;
1791                 bool do_list = !btrfs_is_free_space_inode(inode);
1792
1793                 if (*bits & EXTENT_FIRST_DELALLOC) {
1794                         *bits &= ~EXTENT_FIRST_DELALLOC;
1795                 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1796                         spin_lock(&BTRFS_I(inode)->lock);
1797                         BTRFS_I(inode)->outstanding_extents -= num_extents;
1798                         spin_unlock(&BTRFS_I(inode)->lock);
1799                 }
1800
1801                 /*
1802                  * We don't reserve metadata space for space cache inodes so we
1803                  * don't need to call dellalloc_release_metadata if there is an
1804                  * error.
1805                  */
1806                 if (*bits & EXTENT_DO_ACCOUNTING &&
1807                     root != root->fs_info->tree_root)
1808                         btrfs_delalloc_release_metadata(inode, len);
1809
1810                 /* For sanity tests. */
1811                 if (btrfs_is_testing(root->fs_info))
1812                         return;
1813
1814                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1815                     && do_list && !(state->state & EXTENT_NORESERVE)
1816                     && (*bits & (EXTENT_DO_ACCOUNTING |
1817                     EXTENT_CLEAR_DATA_RESV)))
1818                         btrfs_free_reserved_data_space_noquota(inode,
1819                                         state->start, len);
1820
1821                 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1822                                      root->fs_info->delalloc_batch);
1823                 spin_lock(&BTRFS_I(inode)->lock);
1824                 BTRFS_I(inode)->delalloc_bytes -= len;
1825                 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1826                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1827                              &BTRFS_I(inode)->runtime_flags))
1828                         btrfs_del_delalloc_inode(root, inode);
1829                 spin_unlock(&BTRFS_I(inode)->lock);
1830         }
1831 }
1832
1833 /*
1834  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1835  * we don't create bios that span stripes or chunks
1836  *
1837  * return 1 if page cannot be merged to bio
1838  * return 0 if page can be merged to bio
1839  * return error otherwise
1840  */
1841 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1842                          size_t size, struct bio *bio,
1843                          unsigned long bio_flags)
1844 {
1845         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1846         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1847         u64 length = 0;
1848         u64 map_length;
1849         int ret;
1850
1851         if (bio_flags & EXTENT_BIO_COMPRESSED)
1852                 return 0;
1853
1854         length = bio->bi_iter.bi_size;
1855         map_length = length;
1856         ret = btrfs_map_block(root->fs_info, bio_op(bio), logical,
1857                               &map_length, NULL, 0);
1858         if (ret < 0)
1859                 return ret;
1860         if (map_length < length + size)
1861                 return 1;
1862         return 0;
1863 }
1864
1865 /*
1866  * in order to insert checksums into the metadata in large chunks,
1867  * we wait until bio submission time.   All the pages in the bio are
1868  * checksummed and sums are attached onto the ordered extent record.
1869  *
1870  * At IO completion time the cums attached on the ordered extent record
1871  * are inserted into the btree
1872  */
1873 static int __btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
1874                                     int mirror_num, unsigned long bio_flags,
1875                                     u64 bio_offset)
1876 {
1877         struct btrfs_root *root = BTRFS_I(inode)->root;
1878         int ret = 0;
1879
1880         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1881         BUG_ON(ret); /* -ENOMEM */
1882         return 0;
1883 }
1884
1885 /*
1886  * in order to insert checksums into the metadata in large chunks,
1887  * we wait until bio submission time.   All the pages in the bio are
1888  * checksummed and sums are attached onto the ordered extent record.
1889  *
1890  * At IO completion time the cums attached on the ordered extent record
1891  * are inserted into the btree
1892  */
1893 static int __btrfs_submit_bio_done(struct inode *inode, struct bio *bio,
1894                           int mirror_num, unsigned long bio_flags,
1895                           u64 bio_offset)
1896 {
1897         struct btrfs_root *root = BTRFS_I(inode)->root;
1898         int ret;
1899
1900         ret = btrfs_map_bio(root, bio, mirror_num, 1);
1901         if (ret) {
1902                 bio->bi_error = ret;
1903                 bio_endio(bio);
1904         }
1905         return ret;
1906 }
1907
1908 /*
1909  * extent_io.c submission hook. This does the right thing for csum calculation
1910  * on write, or reading the csums from the tree before a read
1911  */
1912 static int btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1913                           int mirror_num, unsigned long bio_flags,
1914                           u64 bio_offset)
1915 {
1916         struct btrfs_root *root = BTRFS_I(inode)->root;
1917         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1918         int ret = 0;
1919         int skip_sum;
1920         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1921
1922         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1923
1924         if (btrfs_is_free_space_inode(inode))
1925                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1926
1927         if (bio_op(bio) != REQ_OP_WRITE) {
1928                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1929                 if (ret)
1930                         goto out;
1931
1932                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1933                         ret = btrfs_submit_compressed_read(inode, bio,
1934                                                            mirror_num,
1935                                                            bio_flags);
1936                         goto out;
1937                 } else if (!skip_sum) {
1938                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1939                         if (ret)
1940                                 goto out;
1941                 }
1942                 goto mapit;
1943         } else if (async && !skip_sum) {
1944                 /* csum items have already been cloned */
1945                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1946                         goto mapit;
1947                 /* we're doing a write, do the async checksumming */
1948                 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1949                                    inode, bio, mirror_num,
1950                                    bio_flags, bio_offset,
1951                                    __btrfs_submit_bio_start,
1952                                    __btrfs_submit_bio_done);
1953                 goto out;
1954         } else if (!skip_sum) {
1955                 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1956                 if (ret)
1957                         goto out;
1958         }
1959
1960 mapit:
1961         ret = btrfs_map_bio(root, bio, mirror_num, 0);
1962
1963 out:
1964         if (ret < 0) {
1965                 bio->bi_error = ret;
1966                 bio_endio(bio);
1967         }
1968         return ret;
1969 }
1970
1971 /*
1972  * given a list of ordered sums record them in the inode.  This happens
1973  * at IO completion time based on sums calculated at bio submission time.
1974  */
1975 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1976                              struct inode *inode, u64 file_offset,
1977                              struct list_head *list)
1978 {
1979         struct btrfs_ordered_sum *sum;
1980
1981         list_for_each_entry(sum, list, list) {
1982                 trans->adding_csums = 1;
1983                 btrfs_csum_file_blocks(trans,
1984                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1985                 trans->adding_csums = 0;
1986         }
1987         return 0;
1988 }
1989
1990 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1991                               struct extent_state **cached_state)
1992 {
1993         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
1994         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1995                                    cached_state);
1996 }
1997
1998 /* see btrfs_writepage_start_hook for details on why this is required */
1999 struct btrfs_writepage_fixup {
2000         struct page *page;
2001         struct btrfs_work work;
2002 };
2003
2004 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2005 {
2006         struct btrfs_writepage_fixup *fixup;
2007         struct btrfs_ordered_extent *ordered;
2008         struct extent_state *cached_state = NULL;
2009         struct page *page;
2010         struct inode *inode;
2011         u64 page_start;
2012         u64 page_end;
2013         int ret;
2014
2015         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2016         page = fixup->page;
2017 again:
2018         lock_page(page);
2019         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2020                 ClearPageChecked(page);
2021                 goto out_page;
2022         }
2023
2024         inode = page->mapping->host;
2025         page_start = page_offset(page);
2026         page_end = page_offset(page) + PAGE_SIZE - 1;
2027
2028         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2029                          &cached_state);
2030
2031         /* already ordered? We're done */
2032         if (PagePrivate2(page))
2033                 goto out;
2034
2035         ordered = btrfs_lookup_ordered_range(inode, page_start,
2036                                         PAGE_SIZE);
2037         if (ordered) {
2038                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2039                                      page_end, &cached_state, GFP_NOFS);
2040                 unlock_page(page);
2041                 btrfs_start_ordered_extent(inode, ordered, 1);
2042                 btrfs_put_ordered_extent(ordered);
2043                 goto again;
2044         }
2045
2046         ret = btrfs_delalloc_reserve_space(inode, page_start,
2047                                            PAGE_SIZE);
2048         if (ret) {
2049                 mapping_set_error(page->mapping, ret);
2050                 end_extent_writepage(page, ret, page_start, page_end);
2051                 ClearPageChecked(page);
2052                 goto out;
2053          }
2054
2055         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
2056         ClearPageChecked(page);
2057         set_page_dirty(page);
2058 out:
2059         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2060                              &cached_state, GFP_NOFS);
2061 out_page:
2062         unlock_page(page);
2063         put_page(page);
2064         kfree(fixup);
2065 }
2066
2067 /*
2068  * There are a few paths in the higher layers of the kernel that directly
2069  * set the page dirty bit without asking the filesystem if it is a
2070  * good idea.  This causes problems because we want to make sure COW
2071  * properly happens and the data=ordered rules are followed.
2072  *
2073  * In our case any range that doesn't have the ORDERED bit set
2074  * hasn't been properly setup for IO.  We kick off an async process
2075  * to fix it up.  The async helper will wait for ordered extents, set
2076  * the delalloc bit and make it safe to write the page.
2077  */
2078 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2079 {
2080         struct inode *inode = page->mapping->host;
2081         struct btrfs_writepage_fixup *fixup;
2082         struct btrfs_root *root = BTRFS_I(inode)->root;
2083
2084         /* this page is properly in the ordered list */
2085         if (TestClearPagePrivate2(page))
2086                 return 0;
2087
2088         if (PageChecked(page))
2089                 return -EAGAIN;
2090
2091         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2092         if (!fixup)
2093                 return -EAGAIN;
2094
2095         SetPageChecked(page);
2096         get_page(page);
2097         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2098                         btrfs_writepage_fixup_worker, NULL, NULL);
2099         fixup->page = page;
2100         btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2101         return -EBUSY;
2102 }
2103
2104 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2105                                        struct inode *inode, u64 file_pos,
2106                                        u64 disk_bytenr, u64 disk_num_bytes,
2107                                        u64 num_bytes, u64 ram_bytes,
2108                                        u8 compression, u8 encryption,
2109                                        u16 other_encoding, int extent_type)
2110 {
2111         struct btrfs_root *root = BTRFS_I(inode)->root;
2112         struct btrfs_file_extent_item *fi;
2113         struct btrfs_path *path;
2114         struct extent_buffer *leaf;
2115         struct btrfs_key ins;
2116         int extent_inserted = 0;
2117         int ret;
2118
2119         path = btrfs_alloc_path();
2120         if (!path)
2121                 return -ENOMEM;
2122
2123         /*
2124          * we may be replacing one extent in the tree with another.
2125          * The new extent is pinned in the extent map, and we don't want
2126          * to drop it from the cache until it is completely in the btree.
2127          *
2128          * So, tell btrfs_drop_extents to leave this extent in the cache.
2129          * the caller is expected to unpin it and allow it to be merged
2130          * with the others.
2131          */
2132         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2133                                    file_pos + num_bytes, NULL, 0,
2134                                    1, sizeof(*fi), &extent_inserted);
2135         if (ret)
2136                 goto out;
2137
2138         if (!extent_inserted) {
2139                 ins.objectid = btrfs_ino(inode);
2140                 ins.offset = file_pos;
2141                 ins.type = BTRFS_EXTENT_DATA_KEY;
2142
2143                 path->leave_spinning = 1;
2144                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2145                                               sizeof(*fi));
2146                 if (ret)
2147                         goto out;
2148         }
2149         leaf = path->nodes[0];
2150         fi = btrfs_item_ptr(leaf, path->slots[0],
2151                             struct btrfs_file_extent_item);
2152         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2153         btrfs_set_file_extent_type(leaf, fi, extent_type);
2154         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2155         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2156         btrfs_set_file_extent_offset(leaf, fi, 0);
2157         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2158         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2159         btrfs_set_file_extent_compression(leaf, fi, compression);
2160         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2161         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2162
2163         btrfs_mark_buffer_dirty(leaf);
2164         btrfs_release_path(path);
2165
2166         inode_add_bytes(inode, num_bytes);
2167
2168         ins.objectid = disk_bytenr;
2169         ins.offset = disk_num_bytes;
2170         ins.type = BTRFS_EXTENT_ITEM_KEY;
2171         ret = btrfs_alloc_reserved_file_extent(trans, root,
2172                                         root->root_key.objectid,
2173                                         btrfs_ino(inode), file_pos,
2174                                         ram_bytes, &ins);
2175         /*
2176          * Release the reserved range from inode dirty range map, as it is
2177          * already moved into delayed_ref_head
2178          */
2179         btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2180 out:
2181         btrfs_free_path(path);
2182
2183         return ret;
2184 }
2185
2186 /* snapshot-aware defrag */
2187 struct sa_defrag_extent_backref {
2188         struct rb_node node;
2189         struct old_sa_defrag_extent *old;
2190         u64 root_id;
2191         u64 inum;
2192         u64 file_pos;
2193         u64 extent_offset;
2194         u64 num_bytes;
2195         u64 generation;
2196 };
2197
2198 struct old_sa_defrag_extent {
2199         struct list_head list;
2200         struct new_sa_defrag_extent *new;
2201
2202         u64 extent_offset;
2203         u64 bytenr;
2204         u64 offset;
2205         u64 len;
2206         int count;
2207 };
2208
2209 struct new_sa_defrag_extent {
2210         struct rb_root root;
2211         struct list_head head;
2212         struct btrfs_path *path;
2213         struct inode *inode;
2214         u64 file_pos;
2215         u64 len;
2216         u64 bytenr;
2217         u64 disk_len;
2218         u8 compress_type;
2219 };
2220
2221 static int backref_comp(struct sa_defrag_extent_backref *b1,
2222                         struct sa_defrag_extent_backref *b2)
2223 {
2224         if (b1->root_id < b2->root_id)
2225                 return -1;
2226         else if (b1->root_id > b2->root_id)
2227                 return 1;
2228
2229         if (b1->inum < b2->inum)
2230                 return -1;
2231         else if (b1->inum > b2->inum)
2232                 return 1;
2233
2234         if (b1->file_pos < b2->file_pos)
2235                 return -1;
2236         else if (b1->file_pos > b2->file_pos)
2237                 return 1;
2238
2239         /*
2240          * [------------------------------] ===> (a range of space)
2241          *     |<--->|   |<---->| =============> (fs/file tree A)
2242          * |<---------------------------->| ===> (fs/file tree B)
2243          *
2244          * A range of space can refer to two file extents in one tree while
2245          * refer to only one file extent in another tree.
2246          *
2247          * So we may process a disk offset more than one time(two extents in A)
2248          * and locate at the same extent(one extent in B), then insert two same
2249          * backrefs(both refer to the extent in B).
2250          */
2251         return 0;
2252 }
2253
2254 static void backref_insert(struct rb_root *root,
2255                            struct sa_defrag_extent_backref *backref)
2256 {
2257         struct rb_node **p = &root->rb_node;
2258         struct rb_node *parent = NULL;
2259         struct sa_defrag_extent_backref *entry;
2260         int ret;
2261
2262         while (*p) {
2263                 parent = *p;
2264                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2265
2266                 ret = backref_comp(backref, entry);
2267                 if (ret < 0)
2268                         p = &(*p)->rb_left;
2269                 else
2270                         p = &(*p)->rb_right;
2271         }
2272
2273         rb_link_node(&backref->node, parent, p);
2274         rb_insert_color(&backref->node, root);
2275 }
2276
2277 /*
2278  * Note the backref might has changed, and in this case we just return 0.
2279  */
2280 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2281                                        void *ctx)
2282 {
2283         struct btrfs_file_extent_item *extent;
2284         struct btrfs_fs_info *fs_info;
2285         struct old_sa_defrag_extent *old = ctx;
2286         struct new_sa_defrag_extent *new = old->new;
2287         struct btrfs_path *path = new->path;
2288         struct btrfs_key key;
2289         struct btrfs_root *root;
2290         struct sa_defrag_extent_backref *backref;
2291         struct extent_buffer *leaf;
2292         struct inode *inode = new->inode;
2293         int slot;
2294         int ret;
2295         u64 extent_offset;
2296         u64 num_bytes;
2297
2298         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2299             inum == btrfs_ino(inode))
2300                 return 0;
2301
2302         key.objectid = root_id;
2303         key.type = BTRFS_ROOT_ITEM_KEY;
2304         key.offset = (u64)-1;
2305
2306         fs_info = BTRFS_I(inode)->root->fs_info;
2307         root = btrfs_read_fs_root_no_name(fs_info, &key);
2308         if (IS_ERR(root)) {
2309                 if (PTR_ERR(root) == -ENOENT)
2310                         return 0;
2311                 WARN_ON(1);
2312                 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2313                          inum, offset, root_id);
2314                 return PTR_ERR(root);
2315         }
2316
2317         key.objectid = inum;
2318         key.type = BTRFS_EXTENT_DATA_KEY;
2319         if (offset > (u64)-1 << 32)
2320                 key.offset = 0;
2321         else
2322                 key.offset = offset;
2323
2324         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2325         if (WARN_ON(ret < 0))
2326                 return ret;
2327         ret = 0;
2328
2329         while (1) {
2330                 cond_resched();
2331
2332                 leaf = path->nodes[0];
2333                 slot = path->slots[0];
2334
2335                 if (slot >= btrfs_header_nritems(leaf)) {
2336                         ret = btrfs_next_leaf(root, path);
2337                         if (ret < 0) {
2338                                 goto out;
2339                         } else if (ret > 0) {
2340                                 ret = 0;
2341                                 goto out;
2342                         }
2343                         continue;
2344                 }
2345
2346                 path->slots[0]++;
2347
2348                 btrfs_item_key_to_cpu(leaf, &key, slot);
2349
2350                 if (key.objectid > inum)
2351                         goto out;
2352
2353                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2354                         continue;
2355
2356                 extent = btrfs_item_ptr(leaf, slot,
2357                                         struct btrfs_file_extent_item);
2358
2359                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2360                         continue;
2361
2362                 /*
2363                  * 'offset' refers to the exact key.offset,
2364                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2365                  * (key.offset - extent_offset).
2366                  */
2367                 if (key.offset != offset)
2368                         continue;
2369
2370                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2371                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2372
2373                 if (extent_offset >= old->extent_offset + old->offset +
2374                     old->len || extent_offset + num_bytes <=
2375                     old->extent_offset + old->offset)
2376                         continue;
2377                 break;
2378         }
2379
2380         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2381         if (!backref) {
2382                 ret = -ENOENT;
2383                 goto out;
2384         }
2385
2386         backref->root_id = root_id;
2387         backref->inum = inum;
2388         backref->file_pos = offset;
2389         backref->num_bytes = num_bytes;
2390         backref->extent_offset = extent_offset;
2391         backref->generation = btrfs_file_extent_generation(leaf, extent);
2392         backref->old = old;
2393         backref_insert(&new->root, backref);
2394         old->count++;
2395 out:
2396         btrfs_release_path(path);
2397         WARN_ON(ret);
2398         return ret;
2399 }
2400
2401 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2402                                    struct new_sa_defrag_extent *new)
2403 {
2404         struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2405         struct old_sa_defrag_extent *old, *tmp;
2406         int ret;
2407
2408         new->path = path;
2409
2410         list_for_each_entry_safe(old, tmp, &new->head, list) {
2411                 ret = iterate_inodes_from_logical(old->bytenr +
2412                                                   old->extent_offset, fs_info,
2413                                                   path, record_one_backref,
2414                                                   old);
2415                 if (ret < 0 && ret != -ENOENT)
2416                         return false;
2417
2418                 /* no backref to be processed for this extent */
2419                 if (!old->count) {
2420                         list_del(&old->list);
2421                         kfree(old);
2422                 }
2423         }
2424
2425         if (list_empty(&new->head))
2426                 return false;
2427
2428         return true;
2429 }
2430
2431 static int relink_is_mergable(struct extent_buffer *leaf,
2432                               struct btrfs_file_extent_item *fi,
2433                               struct new_sa_defrag_extent *new)
2434 {
2435         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2436                 return 0;
2437
2438         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2439                 return 0;
2440
2441         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2442                 return 0;
2443
2444         if (btrfs_file_extent_encryption(leaf, fi) ||
2445             btrfs_file_extent_other_encoding(leaf, fi))
2446                 return 0;
2447
2448         return 1;
2449 }
2450
2451 /*
2452  * Note the backref might has changed, and in this case we just return 0.
2453  */
2454 static noinline int relink_extent_backref(struct btrfs_path *path,
2455                                  struct sa_defrag_extent_backref *prev,
2456                                  struct sa_defrag_extent_backref *backref)
2457 {
2458         struct btrfs_file_extent_item *extent;
2459         struct btrfs_file_extent_item *item;
2460         struct btrfs_ordered_extent *ordered;
2461         struct btrfs_trans_handle *trans;
2462         struct btrfs_fs_info *fs_info;
2463         struct btrfs_root *root;
2464         struct btrfs_key key;
2465         struct extent_buffer *leaf;
2466         struct old_sa_defrag_extent *old = backref->old;
2467         struct new_sa_defrag_extent *new = old->new;
2468         struct inode *src_inode = new->inode;
2469         struct inode *inode;
2470         struct extent_state *cached = NULL;
2471         int ret = 0;
2472         u64 start;
2473         u64 len;
2474         u64 lock_start;
2475         u64 lock_end;
2476         bool merge = false;
2477         int index;
2478
2479         if (prev && prev->root_id == backref->root_id &&
2480             prev->inum == backref->inum &&
2481             prev->file_pos + prev->num_bytes == backref->file_pos)
2482                 merge = true;
2483
2484         /* step 1: get root */
2485         key.objectid = backref->root_id;
2486         key.type = BTRFS_ROOT_ITEM_KEY;
2487         key.offset = (u64)-1;
2488
2489         fs_info = BTRFS_I(src_inode)->root->fs_info;
2490         index = srcu_read_lock(&fs_info->subvol_srcu);
2491
2492         root = btrfs_read_fs_root_no_name(fs_info, &key);
2493         if (IS_ERR(root)) {
2494                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2495                 if (PTR_ERR(root) == -ENOENT)
2496                         return 0;
2497                 return PTR_ERR(root);
2498         }
2499
2500         if (btrfs_root_readonly(root)) {
2501                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2502                 return 0;
2503         }
2504
2505         /* step 2: get inode */
2506         key.objectid = backref->inum;
2507         key.type = BTRFS_INODE_ITEM_KEY;
2508         key.offset = 0;
2509
2510         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2511         if (IS_ERR(inode)) {
2512                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2513                 return 0;
2514         }
2515
2516         srcu_read_unlock(&fs_info->subvol_srcu, index);
2517
2518         /* step 3: relink backref */
2519         lock_start = backref->file_pos;
2520         lock_end = backref->file_pos + backref->num_bytes - 1;
2521         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2522                          &cached);
2523
2524         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2525         if (ordered) {
2526                 btrfs_put_ordered_extent(ordered);
2527                 goto out_unlock;
2528         }
2529
2530         trans = btrfs_join_transaction(root);
2531         if (IS_ERR(trans)) {
2532                 ret = PTR_ERR(trans);
2533                 goto out_unlock;
2534         }
2535
2536         key.objectid = backref->inum;
2537         key.type = BTRFS_EXTENT_DATA_KEY;
2538         key.offset = backref->file_pos;
2539
2540         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2541         if (ret < 0) {
2542                 goto out_free_path;
2543         } else if (ret > 0) {
2544                 ret = 0;
2545                 goto out_free_path;
2546         }
2547
2548         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2549                                 struct btrfs_file_extent_item);
2550
2551         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2552             backref->generation)
2553                 goto out_free_path;
2554
2555         btrfs_release_path(path);
2556
2557         start = backref->file_pos;
2558         if (backref->extent_offset < old->extent_offset + old->offset)
2559                 start += old->extent_offset + old->offset -
2560                          backref->extent_offset;
2561
2562         len = min(backref->extent_offset + backref->num_bytes,
2563                   old->extent_offset + old->offset + old->len);
2564         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2565
2566         ret = btrfs_drop_extents(trans, root, inode, start,
2567                                  start + len, 1);
2568         if (ret)
2569                 goto out_free_path;
2570 again:
2571         key.objectid = btrfs_ino(inode);
2572         key.type = BTRFS_EXTENT_DATA_KEY;
2573         key.offset = start;
2574
2575         path->leave_spinning = 1;
2576         if (merge) {
2577                 struct btrfs_file_extent_item *fi;
2578                 u64 extent_len;
2579                 struct btrfs_key found_key;
2580
2581                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2582                 if (ret < 0)
2583                         goto out_free_path;
2584
2585                 path->slots[0]--;
2586                 leaf = path->nodes[0];
2587                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2588
2589                 fi = btrfs_item_ptr(leaf, path->slots[0],
2590                                     struct btrfs_file_extent_item);
2591                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2592
2593                 if (extent_len + found_key.offset == start &&
2594                     relink_is_mergable(leaf, fi, new)) {
2595                         btrfs_set_file_extent_num_bytes(leaf, fi,
2596                                                         extent_len + len);
2597                         btrfs_mark_buffer_dirty(leaf);
2598                         inode_add_bytes(inode, len);
2599
2600                         ret = 1;
2601                         goto out_free_path;
2602                 } else {
2603                         merge = false;
2604                         btrfs_release_path(path);
2605                         goto again;
2606                 }
2607         }
2608
2609         ret = btrfs_insert_empty_item(trans, root, path, &key,
2610                                         sizeof(*extent));
2611         if (ret) {
2612                 btrfs_abort_transaction(trans, ret);
2613                 goto out_free_path;
2614         }
2615
2616         leaf = path->nodes[0];
2617         item = btrfs_item_ptr(leaf, path->slots[0],
2618                                 struct btrfs_file_extent_item);
2619         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2620         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2621         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2622         btrfs_set_file_extent_num_bytes(leaf, item, len);
2623         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2624         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2625         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2626         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2627         btrfs_set_file_extent_encryption(leaf, item, 0);
2628         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2629
2630         btrfs_mark_buffer_dirty(leaf);
2631         inode_add_bytes(inode, len);
2632         btrfs_release_path(path);
2633
2634         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2635                         new->disk_len, 0,
2636                         backref->root_id, backref->inum,
2637                         new->file_pos); /* start - extent_offset */
2638         if (ret) {
2639                 btrfs_abort_transaction(trans, ret);
2640                 goto out_free_path;
2641         }
2642
2643         ret = 1;
2644 out_free_path:
2645         btrfs_release_path(path);
2646         path->leave_spinning = 0;
2647         btrfs_end_transaction(trans, root);
2648 out_unlock:
2649         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2650                              &cached, GFP_NOFS);
2651         iput(inode);
2652         return ret;
2653 }
2654
2655 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2656 {
2657         struct old_sa_defrag_extent *old, *tmp;
2658
2659         if (!new)
2660                 return;
2661
2662         list_for_each_entry_safe(old, tmp, &new->head, list) {
2663                 kfree(old);
2664         }
2665         kfree(new);
2666 }
2667
2668 static void relink_file_extents(struct new_sa_defrag_extent *new)
2669 {
2670         struct btrfs_path *path;
2671         struct sa_defrag_extent_backref *backref;
2672         struct sa_defrag_extent_backref *prev = NULL;
2673         struct inode *inode;
2674         struct btrfs_root *root;
2675         struct rb_node *node;
2676         int ret;
2677
2678         inode = new->inode;
2679         root = BTRFS_I(inode)->root;
2680
2681         path = btrfs_alloc_path();
2682         if (!path)
2683                 return;
2684
2685         if (!record_extent_backrefs(path, new)) {
2686                 btrfs_free_path(path);
2687                 goto out;
2688         }
2689         btrfs_release_path(path);
2690
2691         while (1) {
2692                 node = rb_first(&new->root);
2693                 if (!node)
2694                         break;
2695                 rb_erase(node, &new->root);
2696
2697                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2698
2699                 ret = relink_extent_backref(path, prev, backref);
2700                 WARN_ON(ret < 0);
2701
2702                 kfree(prev);
2703
2704                 if (ret == 1)
2705                         prev = backref;
2706                 else
2707                         prev = NULL;
2708                 cond_resched();
2709         }
2710         kfree(prev);
2711
2712         btrfs_free_path(path);
2713 out:
2714         free_sa_defrag_extent(new);
2715
2716         atomic_dec(&root->fs_info->defrag_running);
2717         wake_up(&root->fs_info->transaction_wait);
2718 }
2719
2720 static struct new_sa_defrag_extent *
2721 record_old_file_extents(struct inode *inode,
2722                         struct btrfs_ordered_extent *ordered)
2723 {
2724         struct btrfs_root *root = BTRFS_I(inode)->root;
2725         struct btrfs_path *path;
2726         struct btrfs_key key;
2727         struct old_sa_defrag_extent *old;
2728         struct new_sa_defrag_extent *new;
2729         int ret;
2730
2731         new = kmalloc(sizeof(*new), GFP_NOFS);
2732         if (!new)
2733                 return NULL;
2734
2735         new->inode = inode;
2736         new->file_pos = ordered->file_offset;
2737         new->len = ordered->len;
2738         new->bytenr = ordered->start;
2739         new->disk_len = ordered->disk_len;
2740         new->compress_type = ordered->compress_type;
2741         new->root = RB_ROOT;
2742         INIT_LIST_HEAD(&new->head);
2743
2744         path = btrfs_alloc_path();
2745         if (!path)
2746                 goto out_kfree;
2747
2748         key.objectid = btrfs_ino(inode);
2749         key.type = BTRFS_EXTENT_DATA_KEY;
2750         key.offset = new->file_pos;
2751
2752         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2753         if (ret < 0)
2754                 goto out_free_path;
2755         if (ret > 0 && path->slots[0] > 0)
2756                 path->slots[0]--;
2757
2758         /* find out all the old extents for the file range */
2759         while (1) {
2760                 struct btrfs_file_extent_item *extent;
2761                 struct extent_buffer *l;
2762                 int slot;
2763                 u64 num_bytes;
2764                 u64 offset;
2765                 u64 end;
2766                 u64 disk_bytenr;
2767                 u64 extent_offset;
2768
2769                 l = path->nodes[0];
2770                 slot = path->slots[0];
2771
2772                 if (slot >= btrfs_header_nritems(l)) {
2773                         ret = btrfs_next_leaf(root, path);
2774                         if (ret < 0)
2775                                 goto out_free_path;
2776                         else if (ret > 0)
2777                                 break;
2778                         continue;
2779                 }
2780
2781                 btrfs_item_key_to_cpu(l, &key, slot);
2782
2783                 if (key.objectid != btrfs_ino(inode))
2784                         break;
2785                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2786                         break;
2787                 if (key.offset >= new->file_pos + new->len)
2788                         break;
2789
2790                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2791
2792                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2793                 if (key.offset + num_bytes < new->file_pos)
2794                         goto next;
2795
2796                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2797                 if (!disk_bytenr)
2798                         goto next;
2799
2800                 extent_offset = btrfs_file_extent_offset(l, extent);
2801
2802                 old = kmalloc(sizeof(*old), GFP_NOFS);
2803                 if (!old)
2804                         goto out_free_path;
2805
2806                 offset = max(new->file_pos, key.offset);
2807                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2808
2809                 old->bytenr = disk_bytenr;
2810                 old->extent_offset = extent_offset;
2811                 old->offset = offset - key.offset;
2812                 old->len = end - offset;
2813                 old->new = new;
2814                 old->count = 0;
2815                 list_add_tail(&old->list, &new->head);
2816 next:
2817                 path->slots[0]++;
2818                 cond_resched();
2819         }
2820
2821         btrfs_free_path(path);
2822         atomic_inc(&root->fs_info->defrag_running);
2823
2824         return new;
2825
2826 out_free_path:
2827         btrfs_free_path(path);
2828 out_kfree:
2829         free_sa_defrag_extent(new);
2830         return NULL;
2831 }
2832
2833 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2834                                          u64 start, u64 len)
2835 {
2836         struct btrfs_block_group_cache *cache;
2837
2838         cache = btrfs_lookup_block_group(root->fs_info, start);
2839         ASSERT(cache);
2840
2841         spin_lock(&cache->lock);
2842         cache->delalloc_bytes -= len;
2843         spin_unlock(&cache->lock);
2844
2845         btrfs_put_block_group(cache);
2846 }
2847
2848 /* as ordered data IO finishes, this gets called so we can finish
2849  * an ordered extent if the range of bytes in the file it covers are
2850  * fully written.
2851  */
2852 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2853 {
2854         struct inode *inode = ordered_extent->inode;
2855         struct btrfs_root *root = BTRFS_I(inode)->root;
2856         struct btrfs_trans_handle *trans = NULL;
2857         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2858         struct extent_state *cached_state = NULL;
2859         struct new_sa_defrag_extent *new = NULL;
2860         int compress_type = 0;
2861         int ret = 0;
2862         u64 logical_len = ordered_extent->len;
2863         bool nolock;
2864         bool truncated = false;
2865
2866         nolock = btrfs_is_free_space_inode(inode);
2867
2868         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2869                 ret = -EIO;
2870                 goto out;
2871         }
2872
2873         btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2874                                      ordered_extent->file_offset +
2875                                      ordered_extent->len - 1);
2876
2877         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2878                 truncated = true;
2879                 logical_len = ordered_extent->truncated_len;
2880                 /* Truncated the entire extent, don't bother adding */
2881                 if (!logical_len)
2882                         goto out;
2883         }
2884
2885         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2886                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2887
2888                 /*
2889                  * For mwrite(mmap + memset to write) case, we still reserve
2890                  * space for NOCOW range.
2891                  * As NOCOW won't cause a new delayed ref, just free the space
2892                  */
2893                 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2894                                        ordered_extent->len);
2895                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2896                 if (nolock)
2897                         trans = btrfs_join_transaction_nolock(root);
2898                 else
2899                         trans = btrfs_join_transaction(root);
2900                 if (IS_ERR(trans)) {
2901                         ret = PTR_ERR(trans);
2902                         trans = NULL;
2903                         goto out;
2904                 }
2905                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2906                 ret = btrfs_update_inode_fallback(trans, root, inode);
2907                 if (ret) /* -ENOMEM or corruption */
2908                         btrfs_abort_transaction(trans, ret);
2909                 goto out;
2910         }
2911
2912         lock_extent_bits(io_tree, ordered_extent->file_offset,
2913                          ordered_extent->file_offset + ordered_extent->len - 1,
2914                          &cached_state);
2915
2916         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2917                         ordered_extent->file_offset + ordered_extent->len - 1,
2918                         EXTENT_DEFRAG, 1, cached_state);
2919         if (ret) {
2920                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2921                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2922                         /* the inode is shared */
2923                         new = record_old_file_extents(inode, ordered_extent);
2924
2925                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2926                         ordered_extent->file_offset + ordered_extent->len - 1,
2927                         EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2928         }
2929
2930         if (nolock)
2931                 trans = btrfs_join_transaction_nolock(root);
2932         else
2933                 trans = btrfs_join_transaction(root);
2934         if (IS_ERR(trans)) {
2935                 ret = PTR_ERR(trans);
2936                 trans = NULL;
2937                 goto out_unlock;
2938         }
2939
2940         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2941
2942         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2943                 compress_type = ordered_extent->compress_type;
2944         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2945                 BUG_ON(compress_type);
2946                 ret = btrfs_mark_extent_written(trans, inode,
2947                                                 ordered_extent->file_offset,
2948                                                 ordered_extent->file_offset +
2949                                                 logical_len);
2950         } else {
2951                 BUG_ON(root == root->fs_info->tree_root);
2952                 ret = insert_reserved_file_extent(trans, inode,
2953                                                 ordered_extent->file_offset,
2954                                                 ordered_extent->start,
2955                                                 ordered_extent->disk_len,
2956                                                 logical_len, logical_len,
2957                                                 compress_type, 0, 0,
2958                                                 BTRFS_FILE_EXTENT_REG);
2959                 if (!ret)
2960                         btrfs_release_delalloc_bytes(root,
2961                                                      ordered_extent->start,
2962                                                      ordered_extent->disk_len);
2963         }
2964         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2965                            ordered_extent->file_offset, ordered_extent->len,
2966                            trans->transid);
2967         if (ret < 0) {
2968                 btrfs_abort_transaction(trans, ret);
2969                 goto out_unlock;
2970         }
2971
2972         add_pending_csums(trans, inode, ordered_extent->file_offset,
2973                           &ordered_extent->list);
2974
2975         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2976         ret = btrfs_update_inode_fallback(trans, root, inode);
2977         if (ret) { /* -ENOMEM or corruption */
2978                 btrfs_abort_transaction(trans, ret);
2979                 goto out_unlock;
2980         }
2981         ret = 0;
2982 out_unlock:
2983         unlock_extent_cached(io_tree, ordered_extent->file_offset,
2984                              ordered_extent->file_offset +
2985                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
2986 out:
2987         if (root != root->fs_info->tree_root)
2988                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2989         if (trans)
2990                 btrfs_end_transaction(trans, root);
2991
2992         if (ret || truncated) {
2993                 u64 start, end;
2994
2995                 if (truncated)
2996                         start = ordered_extent->file_offset + logical_len;
2997                 else
2998                         start = ordered_extent->file_offset;
2999                 end = ordered_extent->file_offset + ordered_extent->len - 1;
3000                 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3001
3002                 /* Drop the cache for the part of the extent we didn't write. */
3003                 btrfs_drop_extent_cache(inode, start, end, 0);
3004
3005                 /*
3006                  * If the ordered extent had an IOERR or something else went
3007                  * wrong we need to return the space for this ordered extent
3008                  * back to the allocator.  We only free the extent in the
3009                  * truncated case if we didn't write out the extent at all.
3010                  */
3011                 if ((ret || !logical_len) &&
3012                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3013                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3014                         btrfs_free_reserved_extent(root, ordered_extent->start,
3015                                                    ordered_extent->disk_len, 1);
3016         }
3017
3018
3019         /*
3020          * This needs to be done to make sure anybody waiting knows we are done
3021          * updating everything for this ordered extent.
3022          */
3023         btrfs_remove_ordered_extent(inode, ordered_extent);
3024
3025         /* for snapshot-aware defrag */
3026         if (new) {
3027                 if (ret) {
3028                         free_sa_defrag_extent(new);
3029                         atomic_dec(&root->fs_info->defrag_running);
3030                 } else {
3031                         relink_file_extents(new);
3032                 }
3033         }
3034
3035         /* once for us */
3036         btrfs_put_ordered_extent(ordered_extent);
3037         /* once for the tree */
3038         btrfs_put_ordered_extent(ordered_extent);
3039
3040         return ret;
3041 }
3042
3043 static void finish_ordered_fn(struct btrfs_work *work)
3044 {
3045         struct btrfs_ordered_extent *ordered_extent;
3046         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3047         btrfs_finish_ordered_io(ordered_extent);
3048 }
3049
3050 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3051                                 struct extent_state *state, int uptodate)
3052 {
3053         struct inode *inode = page->mapping->host;
3054         struct btrfs_root *root = BTRFS_I(inode)->root;
3055         struct btrfs_ordered_extent *ordered_extent = NULL;
3056         struct btrfs_workqueue *wq;
3057         btrfs_work_func_t func;
3058
3059         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3060
3061         ClearPagePrivate2(page);
3062         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3063                                             end - start + 1, uptodate))
3064                 return 0;
3065
3066         if (btrfs_is_free_space_inode(inode)) {
3067                 wq = root->fs_info->endio_freespace_worker;
3068                 func = btrfs_freespace_write_helper;
3069         } else {
3070                 wq = root->fs_info->endio_write_workers;
3071                 func = btrfs_endio_write_helper;
3072         }
3073
3074         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3075                         NULL);
3076         btrfs_queue_work(wq, &ordered_extent->work);
3077
3078         return 0;
3079 }
3080
3081 static int __readpage_endio_check(struct inode *inode,
3082                                   struct btrfs_io_bio *io_bio,
3083                                   int icsum, struct page *page,
3084                                   int pgoff, u64 start, size_t len)
3085 {
3086         char *kaddr;
3087         u32 csum_expected;
3088         u32 csum = ~(u32)0;
3089
3090         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3091
3092         kaddr = kmap_atomic(page);
3093         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3094         btrfs_csum_final(csum, (char *)&csum);
3095         if (csum != csum_expected)
3096                 goto zeroit;
3097
3098         kunmap_atomic(kaddr);
3099         return 0;
3100 zeroit:
3101         btrfs_warn_rl(BTRFS_I(inode)->root->fs_info,
3102                 "csum failed ino %llu off %llu csum %u expected csum %u",
3103                            btrfs_ino(inode), start, csum, csum_expected);
3104         memset(kaddr + pgoff, 1, len);
3105         flush_dcache_page(page);
3106         kunmap_atomic(kaddr);
3107         if (csum_expected == 0)
3108                 return 0;
3109         return -EIO;
3110 }
3111
3112 /*
3113  * when reads are done, we need to check csums to verify the data is correct
3114  * if there's a match, we allow the bio to finish.  If not, the code in
3115  * extent_io.c will try to find good copies for us.
3116  */
3117 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3118                                       u64 phy_offset, struct page *page,
3119                                       u64 start, u64 end, int mirror)
3120 {
3121         size_t offset = start - page_offset(page);
3122         struct inode *inode = page->mapping->host;
3123         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3124         struct btrfs_root *root = BTRFS_I(inode)->root;
3125
3126         if (PageChecked(page)) {
3127                 ClearPageChecked(page);
3128                 return 0;
3129         }
3130
3131         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3132                 return 0;
3133
3134         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3135             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3136                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3137                 return 0;
3138         }
3139
3140         phy_offset >>= inode->i_sb->s_blocksize_bits;
3141         return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3142                                       start, (size_t)(end - start + 1));
3143 }
3144
3145 void btrfs_add_delayed_iput(struct inode *inode)
3146 {
3147         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3148         struct btrfs_inode *binode = BTRFS_I(inode);
3149
3150         if (atomic_add_unless(&inode->i_count, -1, 1))
3151                 return;
3152
3153         spin_lock(&fs_info->delayed_iput_lock);
3154         if (binode->delayed_iput_count == 0) {
3155                 ASSERT(list_empty(&binode->delayed_iput));
3156                 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3157         } else {
3158                 binode->delayed_iput_count++;
3159         }
3160         spin_unlock(&fs_info->delayed_iput_lock);
3161 }
3162
3163 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3164 {
3165         struct btrfs_fs_info *fs_info = root->fs_info;
3166
3167         spin_lock(&fs_info->delayed_iput_lock);
3168         while (!list_empty(&fs_info->delayed_iputs)) {
3169                 struct btrfs_inode *inode;
3170
3171                 inode = list_first_entry(&fs_info->delayed_iputs,
3172                                 struct btrfs_inode, delayed_iput);
3173                 if (inode->delayed_iput_count) {
3174                         inode->delayed_iput_count--;
3175                         list_move_tail(&inode->delayed_iput,
3176                                         &fs_info->delayed_iputs);
3177                 } else {
3178                         list_del_init(&inode->delayed_iput);
3179                 }
3180                 spin_unlock(&fs_info->delayed_iput_lock);
3181                 iput(&inode->vfs_inode);
3182                 spin_lock(&fs_info->delayed_iput_lock);
3183         }
3184         spin_unlock(&fs_info->delayed_iput_lock);
3185 }
3186
3187 /*
3188  * This is called in transaction commit time. If there are no orphan
3189  * files in the subvolume, it removes orphan item and frees block_rsv
3190  * structure.
3191  */
3192 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3193                               struct btrfs_root *root)
3194 {
3195         struct btrfs_block_rsv *block_rsv;
3196         int ret;
3197
3198         if (atomic_read(&root->orphan_inodes) ||
3199             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3200                 return;
3201
3202         spin_lock(&root->orphan_lock);
3203         if (atomic_read(&root->orphan_inodes)) {
3204                 spin_unlock(&root->orphan_lock);
3205                 return;