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