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