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