btrfs: replace async_cow::root with fs_info
[sfrench/cifs-2.6.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 <linux/swap.h>
31 #include <asm/unaligned.h>
32 #include "ctree.h"
33 #include "disk-io.h"
34 #include "transaction.h"
35 #include "btrfs_inode.h"
36 #include "print-tree.h"
37 #include "ordered-data.h"
38 #include "xattr.h"
39 #include "tree-log.h"
40 #include "volumes.h"
41 #include "compression.h"
42 #include "locking.h"
43 #include "free-space-cache.h"
44 #include "inode-map.h"
45 #include "backref.h"
46 #include "props.h"
47 #include "qgroup.h"
48 #include "dedupe.h"
49
50 struct btrfs_iget_args {
51         struct btrfs_key *location;
52         struct btrfs_root *root;
53 };
54
55 struct btrfs_dio_data {
56         u64 reserve;
57         u64 unsubmitted_oe_range_start;
58         u64 unsubmitted_oe_range_end;
59         int overwrite;
60 };
61
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_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
114  * btrfs_run_delalloc_range 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_fs_info *fs_info;
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                         nr_pages = 0;
507                         goto cont;
508                 }
509
510                 if (BTRFS_I(inode)->defrag_compress)
511                         compress_type = BTRFS_I(inode)->defrag_compress;
512                 else if (BTRFS_I(inode)->prop_compress)
513                         compress_type = BTRFS_I(inode)->prop_compress;
514
515                 /*
516                  * we need to call clear_page_dirty_for_io on each
517                  * page in the range.  Otherwise applications with the file
518                  * mmap'd can wander in and change the page contents while
519                  * we are compressing them.
520                  *
521                  * If the compression fails for any reason, we set the pages
522                  * dirty again later on.
523                  *
524                  * Note that the remaining part is redirtied, the start pointer
525                  * has moved, the end is the original one.
526                  */
527                 if (!redirty) {
528                         extent_range_clear_dirty_for_io(inode, start, end);
529                         redirty = 1;
530                 }
531
532                 /* Compression level is applied here and only here */
533                 ret = btrfs_compress_pages(
534                         compress_type | (fs_info->compress_level << 4),
535                                            inode->i_mapping, start,
536                                            pages,
537                                            &nr_pages,
538                                            &total_in,
539                                            &total_compressed);
540
541                 if (!ret) {
542                         unsigned long offset = total_compressed &
543                                 (PAGE_SIZE - 1);
544                         struct page *page = pages[nr_pages - 1];
545                         char *kaddr;
546
547                         /* zero the tail end of the last page, we might be
548                          * sending it down to disk
549                          */
550                         if (offset) {
551                                 kaddr = kmap_atomic(page);
552                                 memset(kaddr + offset, 0,
553                                        PAGE_SIZE - offset);
554                                 kunmap_atomic(kaddr);
555                         }
556                         will_compress = 1;
557                 }
558         }
559 cont:
560         if (start == 0) {
561                 /* lets try to make an inline extent */
562                 if (ret || total_in < actual_end) {
563                         /* we didn't compress the entire range, try
564                          * to make an uncompressed inline extent.
565                          */
566                         ret = cow_file_range_inline(inode, start, end, 0,
567                                                     BTRFS_COMPRESS_NONE, NULL);
568                 } else {
569                         /* try making a compressed inline extent */
570                         ret = cow_file_range_inline(inode, start, end,
571                                                     total_compressed,
572                                                     compress_type, pages);
573                 }
574                 if (ret <= 0) {
575                         unsigned long clear_flags = EXTENT_DELALLOC |
576                                 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
577                                 EXTENT_DO_ACCOUNTING;
578                         unsigned long page_error_op;
579
580                         page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
581
582                         /*
583                          * inline extent creation worked or returned error,
584                          * we don't need to create any more async work items.
585                          * Unlock and free up our temp pages.
586                          *
587                          * We use DO_ACCOUNTING here because we need the
588                          * delalloc_release_metadata to be done _after_ we drop
589                          * our outstanding extent for clearing delalloc for this
590                          * range.
591                          */
592                         extent_clear_unlock_delalloc(inode, start, end, end,
593                                                      NULL, clear_flags,
594                                                      PAGE_UNLOCK |
595                                                      PAGE_CLEAR_DIRTY |
596                                                      PAGE_SET_WRITEBACK |
597                                                      page_error_op |
598                                                      PAGE_END_WRITEBACK);
599                         goto free_pages_out;
600                 }
601         }
602
603         if (will_compress) {
604                 /*
605                  * we aren't doing an inline extent round the compressed size
606                  * up to a block size boundary so the allocator does sane
607                  * things
608                  */
609                 total_compressed = ALIGN(total_compressed, blocksize);
610
611                 /*
612                  * one last check to make sure the compression is really a
613                  * win, compare the page count read with the blocks on disk,
614                  * compression must free at least one sector size
615                  */
616                 total_in = ALIGN(total_in, PAGE_SIZE);
617                 if (total_compressed + blocksize <= total_in) {
618                         *num_added += 1;
619
620                         /*
621                          * The async work queues will take care of doing actual
622                          * allocation on disk for these compressed pages, and
623                          * will submit them to the elevator.
624                          */
625                         add_async_extent(async_cow, start, total_in,
626                                         total_compressed, pages, nr_pages,
627                                         compress_type);
628
629                         if (start + total_in < end) {
630                                 start += total_in;
631                                 pages = NULL;
632                                 cond_resched();
633                                 goto again;
634                         }
635                         return;
636                 }
637         }
638         if (pages) {
639                 /*
640                  * the compression code ran but failed to make things smaller,
641                  * free any pages it allocated and our page pointer array
642                  */
643                 for (i = 0; i < nr_pages; i++) {
644                         WARN_ON(pages[i]->mapping);
645                         put_page(pages[i]);
646                 }
647                 kfree(pages);
648                 pages = NULL;
649                 total_compressed = 0;
650                 nr_pages = 0;
651
652                 /* flag the file so we don't compress in the future */
653                 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
654                     !(BTRFS_I(inode)->prop_compress)) {
655                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
656                 }
657         }
658 cleanup_and_bail_uncompressed:
659         /*
660          * No compression, but we still need to write the pages in the file
661          * we've been given so far.  redirty the locked page if it corresponds
662          * to our extent and set things up for the async work queue to run
663          * cow_file_range to do the normal delalloc dance.
664          */
665         if (page_offset(locked_page) >= start &&
666             page_offset(locked_page) <= end)
667                 __set_page_dirty_nobuffers(locked_page);
668                 /* unlocked later on in the async handlers */
669
670         if (redirty)
671                 extent_range_redirty_for_io(inode, start, end);
672         add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
673                          BTRFS_COMPRESS_NONE);
674         *num_added += 1;
675
676         return;
677
678 free_pages_out:
679         for (i = 0; i < nr_pages; i++) {
680                 WARN_ON(pages[i]->mapping);
681                 put_page(pages[i]);
682         }
683         kfree(pages);
684 }
685
686 static void free_async_extent_pages(struct async_extent *async_extent)
687 {
688         int i;
689
690         if (!async_extent->pages)
691                 return;
692
693         for (i = 0; i < async_extent->nr_pages; i++) {
694                 WARN_ON(async_extent->pages[i]->mapping);
695                 put_page(async_extent->pages[i]);
696         }
697         kfree(async_extent->pages);
698         async_extent->nr_pages = 0;
699         async_extent->pages = NULL;
700 }
701
702 /*
703  * phase two of compressed writeback.  This is the ordered portion
704  * of the code, which only gets called in the order the work was
705  * queued.  We walk all the async extents created by compress_file_range
706  * and send them down to the disk.
707  */
708 static noinline void submit_compressed_extents(struct inode *inode,
709                                               struct async_cow *async_cow)
710 {
711         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
712         struct async_extent *async_extent;
713         u64 alloc_hint = 0;
714         struct btrfs_key ins;
715         struct extent_map *em;
716         struct btrfs_root *root = BTRFS_I(inode)->root;
717         struct extent_io_tree *io_tree;
718         int ret = 0;
719
720 again:
721         while (!list_empty(&async_cow->extents)) {
722                 async_extent = list_entry(async_cow->extents.next,
723                                           struct async_extent, list);
724                 list_del(&async_extent->list);
725
726                 io_tree = &BTRFS_I(inode)->io_tree;
727
728 retry:
729                 /* did the compression code fall back to uncompressed IO? */
730                 if (!async_extent->pages) {
731                         int page_started = 0;
732                         unsigned long nr_written = 0;
733
734                         lock_extent(io_tree, async_extent->start,
735                                          async_extent->start +
736                                          async_extent->ram_size - 1);
737
738                         /* allocate blocks */
739                         ret = cow_file_range(inode, async_cow->locked_page,
740                                              async_extent->start,
741                                              async_extent->start +
742                                              async_extent->ram_size - 1,
743                                              async_extent->start +
744                                              async_extent->ram_size - 1,
745                                              &page_started, &nr_written, 0,
746                                              NULL);
747
748                         /* JDM XXX */
749
750                         /*
751                          * if page_started, cow_file_range inserted an
752                          * inline extent and took care of all the unlocking
753                          * and IO for us.  Otherwise, we need to submit
754                          * all those pages down to the drive.
755                          */
756                         if (!page_started && !ret)
757                                 extent_write_locked_range(inode,
758                                                   async_extent->start,
759                                                   async_extent->start +
760                                                   async_extent->ram_size - 1,
761                                                   WB_SYNC_ALL);
762                         else if (ret)
763                                 unlock_page(async_cow->locked_page);
764                         kfree(async_extent);
765                         cond_resched();
766                         continue;
767                 }
768
769                 lock_extent(io_tree, async_extent->start,
770                             async_extent->start + async_extent->ram_size - 1);
771
772                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
773                                            async_extent->compressed_size,
774                                            async_extent->compressed_size,
775                                            0, alloc_hint, &ins, 1, 1);
776                 if (ret) {
777                         free_async_extent_pages(async_extent);
778
779                         if (ret == -ENOSPC) {
780                                 unlock_extent(io_tree, async_extent->start,
781                                               async_extent->start +
782                                               async_extent->ram_size - 1);
783
784                                 /*
785                                  * we need to redirty the pages if we decide to
786                                  * fallback to uncompressed IO, otherwise we
787                                  * will not submit these pages down to lower
788                                  * layers.
789                                  */
790                                 extent_range_redirty_for_io(inode,
791                                                 async_extent->start,
792                                                 async_extent->start +
793                                                 async_extent->ram_size - 1);
794
795                                 goto retry;
796                         }
797                         goto out_free;
798                 }
799                 /*
800                  * here we're doing allocation and writeback of the
801                  * compressed pages
802                  */
803                 em = create_io_em(inode, async_extent->start,
804                                   async_extent->ram_size, /* len */
805                                   async_extent->start, /* orig_start */
806                                   ins.objectid, /* block_start */
807                                   ins.offset, /* block_len */
808                                   ins.offset, /* orig_block_len */
809                                   async_extent->ram_size, /* ram_bytes */
810                                   async_extent->compress_type,
811                                   BTRFS_ORDERED_COMPRESSED);
812                 if (IS_ERR(em))
813                         /* ret value is not necessary due to void function */
814                         goto out_free_reserve;
815                 free_extent_map(em);
816
817                 ret = btrfs_add_ordered_extent_compress(inode,
818                                                 async_extent->start,
819                                                 ins.objectid,
820                                                 async_extent->ram_size,
821                                                 ins.offset,
822                                                 BTRFS_ORDERED_COMPRESSED,
823                                                 async_extent->compress_type);
824                 if (ret) {
825                         btrfs_drop_extent_cache(BTRFS_I(inode),
826                                                 async_extent->start,
827                                                 async_extent->start +
828                                                 async_extent->ram_size - 1, 0);
829                         goto out_free_reserve;
830                 }
831                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
832
833                 /*
834                  * clear dirty, set writeback and unlock the pages.
835                  */
836                 extent_clear_unlock_delalloc(inode, async_extent->start,
837                                 async_extent->start +
838                                 async_extent->ram_size - 1,
839                                 async_extent->start +
840                                 async_extent->ram_size - 1,
841                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
842                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
843                                 PAGE_SET_WRITEBACK);
844                 if (btrfs_submit_compressed_write(inode,
845                                     async_extent->start,
846                                     async_extent->ram_size,
847                                     ins.objectid,
848                                     ins.offset, async_extent->pages,
849                                     async_extent->nr_pages,
850                                     async_cow->write_flags)) {
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                         btrfs_writepage_endio_finish_ordered(p, start, end, 0);
857
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         unsigned long nr_pages;
1148
1149         async_cow = container_of(work, struct async_cow, work);
1150
1151         fs_info = async_cow->fs_info;
1152         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1153                 PAGE_SHIFT;
1154
1155         /* atomic_sub_return implies a barrier */
1156         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1157             5 * SZ_1M)
1158                 cond_wake_up_nomb(&fs_info->async_submit_wait);
1159
1160         if (async_cow->inode)
1161                 submit_compressed_extents(async_cow->inode, async_cow);
1162 }
1163
1164 static noinline void async_cow_free(struct btrfs_work *work)
1165 {
1166         struct async_cow *async_cow;
1167         async_cow = container_of(work, struct async_cow, work);
1168         if (async_cow->inode)
1169                 btrfs_add_delayed_iput(async_cow->inode);
1170         kfree(async_cow);
1171 }
1172
1173 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1174                                 u64 start, u64 end, int *page_started,
1175                                 unsigned long *nr_written,
1176                                 unsigned int write_flags)
1177 {
1178         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1179         struct async_cow *async_cow;
1180         unsigned long nr_pages;
1181         u64 cur_end;
1182
1183         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1184                          1, 0, NULL);
1185         while (start < end) {
1186                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1187                 BUG_ON(!async_cow); /* -ENOMEM */
1188                 async_cow->inode = igrab(inode);
1189                 async_cow->fs_info = fs_info;
1190                 async_cow->locked_page = locked_page;
1191                 async_cow->start = start;
1192                 async_cow->write_flags = write_flags;
1193
1194                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1195                     !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1196                         cur_end = end;
1197                 else
1198                         cur_end = min(end, start + SZ_512K - 1);
1199
1200                 async_cow->end = cur_end;
1201                 INIT_LIST_HEAD(&async_cow->extents);
1202
1203                 btrfs_init_work(&async_cow->work,
1204                                 btrfs_delalloc_helper,
1205                                 async_cow_start, async_cow_submit,
1206                                 async_cow_free);
1207
1208                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1209                         PAGE_SHIFT;
1210                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1211
1212                 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1213
1214                 *nr_written += nr_pages;
1215                 start = cur_end + 1;
1216         }
1217         *page_started = 1;
1218         return 0;
1219 }
1220
1221 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1222                                         u64 bytenr, u64 num_bytes)
1223 {
1224         int ret;
1225         struct btrfs_ordered_sum *sums;
1226         LIST_HEAD(list);
1227
1228         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1229                                        bytenr + num_bytes - 1, &list, 0);
1230         if (ret == 0 && list_empty(&list))
1231                 return 0;
1232
1233         while (!list_empty(&list)) {
1234                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1235                 list_del(&sums->list);
1236                 kfree(sums);
1237         }
1238         if (ret < 0)
1239                 return ret;
1240         return 1;
1241 }
1242
1243 /*
1244  * when nowcow writeback call back.  This checks for snapshots or COW copies
1245  * of the extents that exist in the file, and COWs the file as required.
1246  *
1247  * If no cow copies or snapshots exist, we write directly to the existing
1248  * blocks on disk
1249  */
1250 static noinline int run_delalloc_nocow(struct inode *inode,
1251                                        struct page *locked_page,
1252                               u64 start, u64 end, int *page_started, int force,
1253                               unsigned long *nr_written)
1254 {
1255         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1256         struct btrfs_root *root = BTRFS_I(inode)->root;
1257         struct extent_buffer *leaf;
1258         struct btrfs_path *path;
1259         struct btrfs_file_extent_item *fi;
1260         struct btrfs_key found_key;
1261         struct extent_map *em;
1262         u64 cow_start;
1263         u64 cur_offset;
1264         u64 extent_end;
1265         u64 extent_offset;
1266         u64 disk_bytenr;
1267         u64 num_bytes;
1268         u64 disk_num_bytes;
1269         u64 ram_bytes;
1270         int extent_type;
1271         int ret;
1272         int type;
1273         int nocow;
1274         int check_prev = 1;
1275         bool nolock;
1276         u64 ino = btrfs_ino(BTRFS_I(inode));
1277
1278         path = btrfs_alloc_path();
1279         if (!path) {
1280                 extent_clear_unlock_delalloc(inode, start, end, end,
1281                                              locked_page,
1282                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1283                                              EXTENT_DO_ACCOUNTING |
1284                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1285                                              PAGE_CLEAR_DIRTY |
1286                                              PAGE_SET_WRITEBACK |
1287                                              PAGE_END_WRITEBACK);
1288                 return -ENOMEM;
1289         }
1290
1291         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1292
1293         cow_start = (u64)-1;
1294         cur_offset = start;
1295         while (1) {
1296                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1297                                                cur_offset, 0);
1298                 if (ret < 0)
1299                         goto error;
1300                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1301                         leaf = path->nodes[0];
1302                         btrfs_item_key_to_cpu(leaf, &found_key,
1303                                               path->slots[0] - 1);
1304                         if (found_key.objectid == ino &&
1305                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1306                                 path->slots[0]--;
1307                 }
1308                 check_prev = 0;
1309 next_slot:
1310                 leaf = path->nodes[0];
1311                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1312                         ret = btrfs_next_leaf(root, path);
1313                         if (ret < 0) {
1314                                 if (cow_start != (u64)-1)
1315                                         cur_offset = cow_start;
1316                                 goto error;
1317                         }
1318                         if (ret > 0)
1319                                 break;
1320                         leaf = path->nodes[0];
1321                 }
1322
1323                 nocow = 0;
1324                 disk_bytenr = 0;
1325                 num_bytes = 0;
1326                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1327
1328                 if (found_key.objectid > ino)
1329                         break;
1330                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1331                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1332                         path->slots[0]++;
1333                         goto next_slot;
1334                 }
1335                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1336                     found_key.offset > end)
1337                         break;
1338
1339                 if (found_key.offset > cur_offset) {
1340                         extent_end = found_key.offset;
1341                         extent_type = 0;
1342                         goto out_check;
1343                 }
1344
1345                 fi = btrfs_item_ptr(leaf, path->slots[0],
1346                                     struct btrfs_file_extent_item);
1347                 extent_type = btrfs_file_extent_type(leaf, fi);
1348
1349                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1350                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1351                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1352                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1353                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1354                         extent_end = found_key.offset +
1355                                 btrfs_file_extent_num_bytes(leaf, fi);
1356                         disk_num_bytes =
1357                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1358                         if (extent_end <= start) {
1359                                 path->slots[0]++;
1360                                 goto next_slot;
1361                         }
1362                         if (disk_bytenr == 0)
1363                                 goto out_check;
1364                         if (btrfs_file_extent_compression(leaf, fi) ||
1365                             btrfs_file_extent_encryption(leaf, fi) ||
1366                             btrfs_file_extent_other_encoding(leaf, fi))
1367                                 goto out_check;
1368                         /*
1369                          * Do the same check as in btrfs_cross_ref_exist but
1370                          * without the unnecessary search.
1371                          */
1372                         if (btrfs_file_extent_generation(leaf, fi) <=
1373                             btrfs_root_last_snapshot(&root->root_item))
1374                                 goto out_check;
1375                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1376                                 goto out_check;
1377                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1378                                 goto out_check;
1379                         ret = btrfs_cross_ref_exist(root, ino,
1380                                                     found_key.offset -
1381                                                     extent_offset, disk_bytenr);
1382                         if (ret) {
1383                                 /*
1384                                  * ret could be -EIO if the above fails to read
1385                                  * metadata.
1386                                  */
1387                                 if (ret < 0) {
1388                                         if (cow_start != (u64)-1)
1389                                                 cur_offset = cow_start;
1390                                         goto error;
1391                                 }
1392
1393                                 WARN_ON_ONCE(nolock);
1394                                 goto out_check;
1395                         }
1396                         disk_bytenr += extent_offset;
1397                         disk_bytenr += cur_offset - found_key.offset;
1398                         num_bytes = min(end + 1, extent_end) - cur_offset;
1399                         /*
1400                          * if there are pending snapshots for this root,
1401                          * we fall into common COW way.
1402                          */
1403                         if (!nolock && atomic_read(&root->snapshot_force_cow))
1404                                 goto out_check;
1405                         /*
1406                          * force cow if csum exists in the range.
1407                          * this ensure that csum for a given extent are
1408                          * either valid or do not exist.
1409                          */
1410                         ret = csum_exist_in_range(fs_info, disk_bytenr,
1411                                                   num_bytes);
1412                         if (ret) {
1413                                 /*
1414                                  * ret could be -EIO if the above fails to read
1415                                  * metadata.
1416                                  */
1417                                 if (ret < 0) {
1418                                         if (cow_start != (u64)-1)
1419                                                 cur_offset = cow_start;
1420                                         goto error;
1421                                 }
1422                                 WARN_ON_ONCE(nolock);
1423                                 goto out_check;
1424                         }
1425                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1426                                 goto out_check;
1427                         nocow = 1;
1428                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1429                         extent_end = found_key.offset +
1430                                 btrfs_file_extent_ram_bytes(leaf, fi);
1431                         extent_end = ALIGN(extent_end,
1432                                            fs_info->sectorsize);
1433                 } else {
1434                         BUG_ON(1);
1435                 }
1436 out_check:
1437                 if (extent_end <= start) {
1438                         path->slots[0]++;
1439                         if (nocow)
1440                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1441                         goto next_slot;
1442                 }
1443                 if (!nocow) {
1444                         if (cow_start == (u64)-1)
1445                                 cow_start = cur_offset;
1446                         cur_offset = extent_end;
1447                         if (cur_offset > end)
1448                                 break;
1449                         path->slots[0]++;
1450                         goto next_slot;
1451                 }
1452
1453                 btrfs_release_path(path);
1454                 if (cow_start != (u64)-1) {
1455                         ret = cow_file_range(inode, locked_page,
1456                                              cow_start, found_key.offset - 1,
1457                                              end, page_started, nr_written, 1,
1458                                              NULL);
1459                         if (ret) {
1460                                 if (nocow)
1461                                         btrfs_dec_nocow_writers(fs_info,
1462                                                                 disk_bytenr);
1463                                 goto error;
1464                         }
1465                         cow_start = (u64)-1;
1466                 }
1467
1468                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1469                         u64 orig_start = found_key.offset - extent_offset;
1470
1471                         em = create_io_em(inode, cur_offset, num_bytes,
1472                                           orig_start,
1473                                           disk_bytenr, /* block_start */
1474                                           num_bytes, /* block_len */
1475                                           disk_num_bytes, /* orig_block_len */
1476                                           ram_bytes, BTRFS_COMPRESS_NONE,
1477                                           BTRFS_ORDERED_PREALLOC);
1478                         if (IS_ERR(em)) {
1479                                 if (nocow)
1480                                         btrfs_dec_nocow_writers(fs_info,
1481                                                                 disk_bytenr);
1482                                 ret = PTR_ERR(em);
1483                                 goto error;
1484                         }
1485                         free_extent_map(em);
1486                 }
1487
1488                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1489                         type = BTRFS_ORDERED_PREALLOC;
1490                 } else {
1491                         type = BTRFS_ORDERED_NOCOW;
1492                 }
1493
1494                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1495                                                num_bytes, num_bytes, type);
1496                 if (nocow)
1497                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1498                 BUG_ON(ret); /* -ENOMEM */
1499
1500                 if (root->root_key.objectid ==
1501                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1502                         /*
1503                          * Error handled later, as we must prevent
1504                          * extent_clear_unlock_delalloc() in error handler
1505                          * from freeing metadata of created ordered extent.
1506                          */
1507                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1508                                                       num_bytes);
1509
1510                 extent_clear_unlock_delalloc(inode, cur_offset,
1511                                              cur_offset + num_bytes - 1, end,
1512                                              locked_page, EXTENT_LOCKED |
1513                                              EXTENT_DELALLOC |
1514                                              EXTENT_CLEAR_DATA_RESV,
1515                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1516
1517                 cur_offset = extent_end;
1518
1519                 /*
1520                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1521                  * handler, as metadata for created ordered extent will only
1522                  * be freed by btrfs_finish_ordered_io().
1523                  */
1524                 if (ret)
1525                         goto error;
1526                 if (cur_offset > end)
1527                         break;
1528         }
1529         btrfs_release_path(path);
1530
1531         if (cur_offset <= end && cow_start == (u64)-1)
1532                 cow_start = cur_offset;
1533
1534         if (cow_start != (u64)-1) {
1535                 cur_offset = end;
1536                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1537                                      page_started, nr_written, 1, NULL);
1538                 if (ret)
1539                         goto error;
1540         }
1541
1542 error:
1543         if (ret && cur_offset < end)
1544                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1545                                              locked_page, EXTENT_LOCKED |
1546                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1547                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1548                                              PAGE_CLEAR_DIRTY |
1549                                              PAGE_SET_WRITEBACK |
1550                                              PAGE_END_WRITEBACK);
1551         btrfs_free_path(path);
1552         return ret;
1553 }
1554
1555 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1556 {
1557
1558         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1559             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1560                 return 0;
1561
1562         /*
1563          * @defrag_bytes is a hint value, no spinlock held here,
1564          * if is not zero, it means the file is defragging.
1565          * Force cow if given extent needs to be defragged.
1566          */
1567         if (BTRFS_I(inode)->defrag_bytes &&
1568             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1569                            EXTENT_DEFRAG, 0, NULL))
1570                 return 1;
1571
1572         return 0;
1573 }
1574
1575 /*
1576  * Function to process delayed allocation (create CoW) for ranges which are
1577  * being touched for the first time.
1578  */
1579 int btrfs_run_delalloc_range(void *private_data, struct page *locked_page,
1580                 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1581                 struct writeback_control *wbc)
1582 {
1583         struct inode *inode = private_data;
1584         int ret;
1585         int force_cow = need_force_cow(inode, start, end);
1586         unsigned int write_flags = wbc_to_write_flags(wbc);
1587
1588         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1589                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1590                                          page_started, 1, nr_written);
1591         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1592                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1593                                          page_started, 0, nr_written);
1594         } else if (!inode_need_compress(inode, start, end)) {
1595                 ret = cow_file_range(inode, locked_page, start, end, end,
1596                                       page_started, nr_written, 1, NULL);
1597         } else {
1598                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1599                         &BTRFS_I(inode)->runtime_flags);
1600                 ret = cow_file_range_async(inode, locked_page, start, end,
1601                                            page_started, nr_written,
1602                                            write_flags);
1603         }
1604         if (ret)
1605                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1606         return ret;
1607 }
1608
1609 void btrfs_split_delalloc_extent(struct inode *inode,
1610                                  struct extent_state *orig, u64 split)
1611 {
1612         u64 size;
1613
1614         /* not delalloc, ignore it */
1615         if (!(orig->state & EXTENT_DELALLOC))
1616                 return;
1617
1618         size = orig->end - orig->start + 1;
1619         if (size > BTRFS_MAX_EXTENT_SIZE) {
1620                 u32 num_extents;
1621                 u64 new_size;
1622
1623                 /*
1624                  * See the explanation in btrfs_merge_delalloc_extent, the same
1625                  * applies here, just in reverse.
1626                  */
1627                 new_size = orig->end - split + 1;
1628                 num_extents = count_max_extents(new_size);
1629                 new_size = split - orig->start;
1630                 num_extents += count_max_extents(new_size);
1631                 if (count_max_extents(size) >= num_extents)
1632                         return;
1633         }
1634
1635         spin_lock(&BTRFS_I(inode)->lock);
1636         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1637         spin_unlock(&BTRFS_I(inode)->lock);
1638 }
1639
1640 /*
1641  * Handle merged delayed allocation extents so we can keep track of new extents
1642  * that are just merged onto old extents, such as when we are doing sequential
1643  * writes, so we can properly account for the metadata space we'll need.
1644  */
1645 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1646                                  struct extent_state *other)
1647 {
1648         u64 new_size, old_size;
1649         u32 num_extents;
1650
1651         /* not delalloc, ignore it */
1652         if (!(other->state & EXTENT_DELALLOC))
1653                 return;
1654
1655         if (new->start > other->start)
1656                 new_size = new->end - other->start + 1;
1657         else
1658                 new_size = other->end - new->start + 1;
1659
1660         /* we're not bigger than the max, unreserve the space and go */
1661         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1662                 spin_lock(&BTRFS_I(inode)->lock);
1663                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1664                 spin_unlock(&BTRFS_I(inode)->lock);
1665                 return;
1666         }
1667
1668         /*
1669          * We have to add up either side to figure out how many extents were
1670          * accounted for before we merged into one big extent.  If the number of
1671          * extents we accounted for is <= the amount we need for the new range
1672          * then we can return, otherwise drop.  Think of it like this
1673          *
1674          * [ 4k][MAX_SIZE]
1675          *
1676          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1677          * need 2 outstanding extents, on one side we have 1 and the other side
1678          * we have 1 so they are == and we can return.  But in this case
1679          *
1680          * [MAX_SIZE+4k][MAX_SIZE+4k]
1681          *
1682          * Each range on their own accounts for 2 extents, but merged together
1683          * they are only 3 extents worth of accounting, so we need to drop in
1684          * this case.
1685          */
1686         old_size = other->end - other->start + 1;
1687         num_extents = count_max_extents(old_size);
1688         old_size = new->end - new->start + 1;
1689         num_extents += count_max_extents(old_size);
1690         if (count_max_extents(new_size) >= num_extents)
1691                 return;
1692
1693         spin_lock(&BTRFS_I(inode)->lock);
1694         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1695         spin_unlock(&BTRFS_I(inode)->lock);
1696 }
1697
1698 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1699                                       struct inode *inode)
1700 {
1701         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1702
1703         spin_lock(&root->delalloc_lock);
1704         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1705                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1706                               &root->delalloc_inodes);
1707                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1708                         &BTRFS_I(inode)->runtime_flags);
1709                 root->nr_delalloc_inodes++;
1710                 if (root->nr_delalloc_inodes == 1) {
1711                         spin_lock(&fs_info->delalloc_root_lock);
1712                         BUG_ON(!list_empty(&root->delalloc_root));
1713                         list_add_tail(&root->delalloc_root,
1714                                       &fs_info->delalloc_roots);
1715                         spin_unlock(&fs_info->delalloc_root_lock);
1716                 }
1717         }
1718         spin_unlock(&root->delalloc_lock);
1719 }
1720
1721
1722 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1723                                 struct btrfs_inode *inode)
1724 {
1725         struct btrfs_fs_info *fs_info = root->fs_info;
1726
1727         if (!list_empty(&inode->delalloc_inodes)) {
1728                 list_del_init(&inode->delalloc_inodes);
1729                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1730                           &inode->runtime_flags);
1731                 root->nr_delalloc_inodes--;
1732                 if (!root->nr_delalloc_inodes) {
1733                         ASSERT(list_empty(&root->delalloc_inodes));
1734                         spin_lock(&fs_info->delalloc_root_lock);
1735                         BUG_ON(list_empty(&root->delalloc_root));
1736                         list_del_init(&root->delalloc_root);
1737                         spin_unlock(&fs_info->delalloc_root_lock);
1738                 }
1739         }
1740 }
1741
1742 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1743                                      struct btrfs_inode *inode)
1744 {
1745         spin_lock(&root->delalloc_lock);
1746         __btrfs_del_delalloc_inode(root, inode);
1747         spin_unlock(&root->delalloc_lock);
1748 }
1749
1750 /*
1751  * Properly track delayed allocation bytes in the inode and to maintain the
1752  * list of inodes that have pending delalloc work to be done.
1753  */
1754 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1755                                unsigned *bits)
1756 {
1757         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1758
1759         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1760                 WARN_ON(1);
1761         /*
1762          * set_bit and clear bit hooks normally require _irqsave/restore
1763          * but in this case, we are only testing for the DELALLOC
1764          * bit, which is only set or cleared with irqs on
1765          */
1766         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1767                 struct btrfs_root *root = BTRFS_I(inode)->root;
1768                 u64 len = state->end + 1 - state->start;
1769                 u32 num_extents = count_max_extents(len);
1770                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1771
1772                 spin_lock(&BTRFS_I(inode)->lock);
1773                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1774                 spin_unlock(&BTRFS_I(inode)->lock);
1775
1776                 /* For sanity tests */
1777                 if (btrfs_is_testing(fs_info))
1778                         return;
1779
1780                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1781                                          fs_info->delalloc_batch);
1782                 spin_lock(&BTRFS_I(inode)->lock);
1783                 BTRFS_I(inode)->delalloc_bytes += len;
1784                 if (*bits & EXTENT_DEFRAG)
1785                         BTRFS_I(inode)->defrag_bytes += len;
1786                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1787                                          &BTRFS_I(inode)->runtime_flags))
1788                         btrfs_add_delalloc_inodes(root, inode);
1789                 spin_unlock(&BTRFS_I(inode)->lock);
1790         }
1791
1792         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1793             (*bits & EXTENT_DELALLOC_NEW)) {
1794                 spin_lock(&BTRFS_I(inode)->lock);
1795                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1796                         state->start;
1797                 spin_unlock(&BTRFS_I(inode)->lock);
1798         }
1799 }
1800
1801 /*
1802  * Once a range is no longer delalloc this function ensures that proper
1803  * accounting happens.
1804  */
1805 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1806                                  struct extent_state *state, unsigned *bits)
1807 {
1808         struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1809         struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1810         u64 len = state->end + 1 - state->start;
1811         u32 num_extents = count_max_extents(len);
1812
1813         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1814                 spin_lock(&inode->lock);
1815                 inode->defrag_bytes -= len;
1816                 spin_unlock(&inode->lock);
1817         }
1818
1819         /*
1820          * set_bit and clear bit hooks normally require _irqsave/restore
1821          * but in this case, we are only testing for the DELALLOC
1822          * bit, which is only set or cleared with irqs on
1823          */
1824         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1825                 struct btrfs_root *root = inode->root;
1826                 bool do_list = !btrfs_is_free_space_inode(inode);
1827
1828                 spin_lock(&inode->lock);
1829                 btrfs_mod_outstanding_extents(inode, -num_extents);
1830                 spin_unlock(&inode->lock);
1831
1832                 /*
1833                  * We don't reserve metadata space for space cache inodes so we
1834                  * don't need to call dellalloc_release_metadata if there is an
1835                  * error.
1836                  */
1837                 if (*bits & EXTENT_CLEAR_META_RESV &&
1838                     root != fs_info->tree_root)
1839                         btrfs_delalloc_release_metadata(inode, len, false);
1840
1841                 /* For sanity tests. */
1842                 if (btrfs_is_testing(fs_info))
1843                         return;
1844
1845                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1846                     do_list && !(state->state & EXTENT_NORESERVE) &&
1847                     (*bits & EXTENT_CLEAR_DATA_RESV))
1848                         btrfs_free_reserved_data_space_noquota(
1849                                         &inode->vfs_inode,
1850                                         state->start, len);
1851
1852                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1853                                          fs_info->delalloc_batch);
1854                 spin_lock(&inode->lock);
1855                 inode->delalloc_bytes -= len;
1856                 if (do_list && inode->delalloc_bytes == 0 &&
1857                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1858                                         &inode->runtime_flags))
1859                         btrfs_del_delalloc_inode(root, inode);
1860                 spin_unlock(&inode->lock);
1861         }
1862
1863         if ((state->state & EXTENT_DELALLOC_NEW) &&
1864             (*bits & EXTENT_DELALLOC_NEW)) {
1865                 spin_lock(&inode->lock);
1866                 ASSERT(inode->new_delalloc_bytes >= len);
1867                 inode->new_delalloc_bytes -= len;
1868                 spin_unlock(&inode->lock);
1869         }
1870 }
1871
1872 /*
1873  * Merge bio hook, this must check the chunk tree to make sure we don't create
1874  * bios that span stripes or chunks
1875  *
1876  * return 1 if page cannot be merged to bio
1877  * return 0 if page can be merged to bio
1878  * return error otherwise
1879  */
1880 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1881                          size_t size, struct bio *bio,
1882                          unsigned long bio_flags)
1883 {
1884         struct inode *inode = page->mapping->host;
1885         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1886         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1887         u64 length = 0;
1888         u64 map_length;
1889         int ret;
1890
1891         if (bio_flags & EXTENT_BIO_COMPRESSED)
1892                 return 0;
1893
1894         length = bio->bi_iter.bi_size;
1895         map_length = length;
1896         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1897                               NULL, 0);
1898         if (ret < 0)
1899                 return ret;
1900         if (map_length < length + size)
1901                 return 1;
1902         return 0;
1903 }
1904
1905 /*
1906  * in order to insert checksums into the metadata in large chunks,
1907  * we wait until bio submission time.   All the pages in the bio are
1908  * checksummed and sums are attached onto the ordered extent record.
1909  *
1910  * At IO completion time the cums attached on the ordered extent record
1911  * are inserted into the btree
1912  */
1913 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1914                                     u64 bio_offset)
1915 {
1916         struct inode *inode = private_data;
1917         blk_status_t ret = 0;
1918
1919         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1920         BUG_ON(ret); /* -ENOMEM */
1921         return 0;
1922 }
1923
1924 /*
1925  * extent_io.c submission hook. This does the right thing for csum calculation
1926  * on write, or reading the csums from the tree before a read.
1927  *
1928  * Rules about async/sync submit,
1929  * a) read:                             sync submit
1930  *
1931  * b) write without checksum:           sync submit
1932  *
1933  * c) write with checksum:
1934  *    c-1) if bio is issued by fsync:   sync submit
1935  *         (sync_writers != 0)
1936  *
1937  *    c-2) if root is reloc root:       sync submit
1938  *         (only in case of buffered IO)
1939  *
1940  *    c-3) otherwise:                   async submit
1941  */
1942 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1943                                  int mirror_num, unsigned long bio_flags,
1944                                  u64 bio_offset)
1945 {
1946         struct inode *inode = private_data;
1947         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1948         struct btrfs_root *root = BTRFS_I(inode)->root;
1949         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1950         blk_status_t ret = 0;
1951         int skip_sum;
1952         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1953
1954         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1955
1956         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1957                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1958
1959         if (bio_op(bio) != REQ_OP_WRITE) {
1960                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1961                 if (ret)
1962                         goto out;
1963
1964                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1965                         ret = btrfs_submit_compressed_read(inode, bio,
1966                                                            mirror_num,
1967                                                            bio_flags);
1968                         goto out;
1969                 } else if (!skip_sum) {
1970                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1971                         if (ret)
1972                                 goto out;
1973                 }
1974                 goto mapit;
1975         } else if (async && !skip_sum) {
1976                 /* csum items have already been cloned */
1977                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1978                         goto mapit;
1979                 /* we're doing a write, do the async checksumming */
1980                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
1981                                           bio_offset, inode,
1982                                           btrfs_submit_bio_start);
1983                 goto out;
1984         } else if (!skip_sum) {
1985                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1986                 if (ret)
1987                         goto out;
1988         }
1989
1990 mapit:
1991         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
1992
1993 out:
1994         if (ret) {
1995                 bio->bi_status = ret;
1996                 bio_endio(bio);
1997         }
1998         return ret;
1999 }
2000
2001 /*
2002  * given a list of ordered sums record them in the inode.  This happens
2003  * at IO completion time based on sums calculated at bio submission time.
2004  */
2005 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2006                              struct inode *inode, struct list_head *list)
2007 {
2008         struct btrfs_ordered_sum *sum;
2009         int ret;
2010
2011         list_for_each_entry(sum, list, list) {
2012                 trans->adding_csums = true;
2013                 ret = btrfs_csum_file_blocks(trans,
2014                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2015                 trans->adding_csums = false;
2016                 if (ret)
2017                         return ret;
2018         }
2019         return 0;
2020 }
2021
2022 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2023                               unsigned int extra_bits,
2024                               struct extent_state **cached_state, int dedupe)
2025 {
2026         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2027         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2028                                    extra_bits, cached_state);
2029 }
2030
2031 /* see btrfs_writepage_start_hook for details on why this is required */
2032 struct btrfs_writepage_fixup {
2033         struct page *page;
2034         struct btrfs_work work;
2035 };
2036
2037 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2038 {
2039         struct btrfs_writepage_fixup *fixup;
2040         struct btrfs_ordered_extent *ordered;
2041         struct extent_state *cached_state = NULL;
2042         struct extent_changeset *data_reserved = NULL;
2043         struct page *page;
2044         struct inode *inode;
2045         u64 page_start;
2046         u64 page_end;
2047         int ret;
2048
2049         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2050         page = fixup->page;
2051 again:
2052         lock_page(page);
2053         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2054                 ClearPageChecked(page);
2055                 goto out_page;
2056         }
2057
2058         inode = page->mapping->host;
2059         page_start = page_offset(page);
2060         page_end = page_offset(page) + PAGE_SIZE - 1;
2061
2062         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2063                          &cached_state);
2064
2065         /* already ordered? We're done */
2066         if (PagePrivate2(page))
2067                 goto out;
2068
2069         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2070                                         PAGE_SIZE);
2071         if (ordered) {
2072                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2073                                      page_end, &cached_state);
2074                 unlock_page(page);
2075                 btrfs_start_ordered_extent(inode, ordered, 1);
2076                 btrfs_put_ordered_extent(ordered);
2077                 goto again;
2078         }
2079
2080         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2081                                            PAGE_SIZE);
2082         if (ret) {
2083                 mapping_set_error(page->mapping, ret);
2084                 end_extent_writepage(page, ret, page_start, page_end);
2085                 ClearPageChecked(page);
2086                 goto out;
2087          }
2088
2089         ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2090                                         &cached_state, 0);
2091         if (ret) {
2092                 mapping_set_error(page->mapping, ret);
2093                 end_extent_writepage(page, ret, page_start, page_end);
2094                 ClearPageChecked(page);
2095                 goto out;
2096         }
2097
2098         ClearPageChecked(page);
2099         set_page_dirty(page);
2100         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2101 out:
2102         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2103                              &cached_state);
2104 out_page:
2105         unlock_page(page);
2106         put_page(page);
2107         kfree(fixup);
2108         extent_changeset_free(data_reserved);
2109 }
2110
2111 /*
2112  * There are a few paths in the higher layers of the kernel that directly
2113  * set the page dirty bit without asking the filesystem if it is a
2114  * good idea.  This causes problems because we want to make sure COW
2115  * properly happens and the data=ordered rules are followed.
2116  *
2117  * In our case any range that doesn't have the ORDERED bit set
2118  * hasn't been properly setup for IO.  We kick off an async process
2119  * to fix it up.  The async helper will wait for ordered extents, set
2120  * the delalloc bit and make it safe to write the page.
2121  */
2122 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2123 {
2124         struct inode *inode = page->mapping->host;
2125         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2126         struct btrfs_writepage_fixup *fixup;
2127
2128         /* this page is properly in the ordered list */
2129         if (TestClearPagePrivate2(page))
2130                 return 0;
2131
2132         if (PageChecked(page))
2133                 return -EAGAIN;
2134
2135         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2136         if (!fixup)
2137                 return -EAGAIN;
2138
2139         SetPageChecked(page);
2140         get_page(page);
2141         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2142                         btrfs_writepage_fixup_worker, NULL, NULL);
2143         fixup->page = page;
2144         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2145         return -EBUSY;
2146 }
2147
2148 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2149                                        struct inode *inode, u64 file_pos,
2150                                        u64 disk_bytenr, u64 disk_num_bytes,
2151                                        u64 num_bytes, u64 ram_bytes,
2152                                        u8 compression, u8 encryption,
2153                                        u16 other_encoding, int extent_type)
2154 {
2155         struct btrfs_root *root = BTRFS_I(inode)->root;
2156         struct btrfs_file_extent_item *fi;
2157         struct btrfs_path *path;
2158         struct extent_buffer *leaf;
2159         struct btrfs_key ins;
2160         u64 qg_released;
2161         int extent_inserted = 0;
2162         int ret;
2163
2164         path = btrfs_alloc_path();
2165         if (!path)
2166                 return -ENOMEM;
2167
2168         /*
2169          * we may be replacing one extent in the tree with another.
2170          * The new extent is pinned in the extent map, and we don't want
2171          * to drop it from the cache until it is completely in the btree.
2172          *
2173          * So, tell btrfs_drop_extents to leave this extent in the cache.
2174          * the caller is expected to unpin it and allow it to be merged
2175          * with the others.
2176          */
2177         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2178                                    file_pos + num_bytes, NULL, 0,
2179                                    1, sizeof(*fi), &extent_inserted);
2180         if (ret)
2181                 goto out;
2182
2183         if (!extent_inserted) {
2184                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2185                 ins.offset = file_pos;
2186                 ins.type = BTRFS_EXTENT_DATA_KEY;
2187
2188                 path->leave_spinning = 1;
2189                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2190                                               sizeof(*fi));
2191                 if (ret)
2192                         goto out;
2193         }
2194         leaf = path->nodes[0];
2195         fi = btrfs_item_ptr(leaf, path->slots[0],
2196                             struct btrfs_file_extent_item);
2197         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2198         btrfs_set_file_extent_type(leaf, fi, extent_type);
2199         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2200         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2201         btrfs_set_file_extent_offset(leaf, fi, 0);
2202         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2203         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2204         btrfs_set_file_extent_compression(leaf, fi, compression);
2205         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2206         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2207
2208         btrfs_mark_buffer_dirty(leaf);
2209         btrfs_release_path(path);
2210
2211         inode_add_bytes(inode, num_bytes);
2212
2213         ins.objectid = disk_bytenr;
2214         ins.offset = disk_num_bytes;
2215         ins.type = BTRFS_EXTENT_ITEM_KEY;
2216
2217         /*
2218          * Release the reserved range from inode dirty range map, as it is
2219          * already moved into delayed_ref_head
2220          */
2221         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2222         if (ret < 0)
2223                 goto out;
2224         qg_released = ret;
2225         ret = btrfs_alloc_reserved_file_extent(trans, root,
2226                                                btrfs_ino(BTRFS_I(inode)),
2227                                                file_pos, qg_released, &ins);
2228 out:
2229         btrfs_free_path(path);
2230
2231         return ret;
2232 }
2233
2234 /* snapshot-aware defrag */
2235 struct sa_defrag_extent_backref {
2236         struct rb_node node;
2237         struct old_sa_defrag_extent *old;
2238         u64 root_id;
2239         u64 inum;
2240         u64 file_pos;
2241         u64 extent_offset;
2242         u64 num_bytes;
2243         u64 generation;
2244 };
2245
2246 struct old_sa_defrag_extent {
2247         struct list_head list;
2248         struct new_sa_defrag_extent *new;
2249
2250         u64 extent_offset;
2251         u64 bytenr;
2252         u64 offset;
2253         u64 len;
2254         int count;
2255 };
2256
2257 struct new_sa_defrag_extent {
2258         struct rb_root root;
2259         struct list_head head;
2260         struct btrfs_path *path;
2261         struct inode *inode;
2262         u64 file_pos;
2263         u64 len;
2264         u64 bytenr;
2265         u64 disk_len;
2266         u8 compress_type;
2267 };
2268
2269 static int backref_comp(struct sa_defrag_extent_backref *b1,
2270                         struct sa_defrag_extent_backref *b2)
2271 {
2272         if (b1->root_id < b2->root_id)
2273                 return -1;
2274         else if (b1->root_id > b2->root_id)
2275                 return 1;
2276
2277         if (b1->inum < b2->inum)
2278                 return -1;
2279         else if (b1->inum > b2->inum)
2280                 return 1;
2281
2282         if (b1->file_pos < b2->file_pos)
2283                 return -1;
2284         else if (b1->file_pos > b2->file_pos)
2285                 return 1;
2286
2287         /*
2288          * [------------------------------] ===> (a range of space)
2289          *     |<--->|   |<---->| =============> (fs/file tree A)
2290          * |<---------------------------->| ===> (fs/file tree B)
2291          *
2292          * A range of space can refer to two file extents in one tree while
2293          * refer to only one file extent in another tree.
2294          *
2295          * So we may process a disk offset more than one time(two extents in A)
2296          * and locate at the same extent(one extent in B), then insert two same
2297          * backrefs(both refer to the extent in B).
2298          */
2299         return 0;
2300 }
2301
2302 static void backref_insert(struct rb_root *root,
2303                            struct sa_defrag_extent_backref *backref)
2304 {
2305         struct rb_node **p = &root->rb_node;
2306         struct rb_node *parent = NULL;
2307         struct sa_defrag_extent_backref *entry;
2308         int ret;
2309
2310         while (*p) {
2311                 parent = *p;
2312                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2313
2314                 ret = backref_comp(backref, entry);
2315                 if (ret < 0)
2316                         p = &(*p)->rb_left;
2317                 else
2318                         p = &(*p)->rb_right;
2319         }
2320
2321         rb_link_node(&backref->node, parent, p);
2322         rb_insert_color(&backref->node, root);
2323 }
2324
2325 /*
2326  * Note the backref might has changed, and in this case we just return 0.
2327  */
2328 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2329                                        void *ctx)
2330 {
2331         struct btrfs_file_extent_item *extent;
2332         struct old_sa_defrag_extent *old = ctx;
2333         struct new_sa_defrag_extent *new = old->new;
2334         struct btrfs_path *path = new->path;
2335         struct btrfs_key key;
2336         struct btrfs_root *root;
2337         struct sa_defrag_extent_backref *backref;
2338         struct extent_buffer *leaf;
2339         struct inode *inode = new->inode;
2340         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2341         int slot;
2342         int ret;
2343         u64 extent_offset;
2344         u64 num_bytes;
2345
2346         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2347             inum == btrfs_ino(BTRFS_I(inode)))
2348                 return 0;
2349
2350         key.objectid = root_id;
2351         key.type = BTRFS_ROOT_ITEM_KEY;
2352         key.offset = (u64)-1;
2353
2354         root = btrfs_read_fs_root_no_name(fs_info, &key);
2355         if (IS_ERR(root)) {
2356                 if (PTR_ERR(root) == -ENOENT)
2357                         return 0;
2358                 WARN_ON(1);
2359                 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2360                          inum, offset, root_id);
2361                 return PTR_ERR(root);
2362         }
2363
2364         key.objectid = inum;
2365         key.type = BTRFS_EXTENT_DATA_KEY;
2366         if (offset > (u64)-1 << 32)
2367                 key.offset = 0;
2368         else
2369                 key.offset = offset;
2370
2371         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2372         if (WARN_ON(ret < 0))
2373                 return ret;
2374         ret = 0;
2375
2376         while (1) {
2377                 cond_resched();
2378
2379                 leaf = path->nodes[0];
2380                 slot = path->slots[0];
2381
2382                 if (slot >= btrfs_header_nritems(leaf)) {
2383                         ret = btrfs_next_leaf(root, path);
2384                         if (ret < 0) {
2385                                 goto out;
2386                         } else if (ret > 0) {
2387                                 ret = 0;
2388                                 goto out;
2389                         }
2390                         continue;
2391                 }
2392
2393                 path->slots[0]++;
2394
2395                 btrfs_item_key_to_cpu(leaf, &key, slot);
2396
2397                 if (key.objectid > inum)
2398                         goto out;
2399
2400                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2401                         continue;
2402
2403                 extent = btrfs_item_ptr(leaf, slot,
2404                                         struct btrfs_file_extent_item);
2405
2406                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2407                         continue;
2408
2409                 /*
2410                  * 'offset' refers to the exact key.offset,
2411                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2412                  * (key.offset - extent_offset).
2413                  */
2414                 if (key.offset != offset)
2415                         continue;
2416
2417                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2418                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2419
2420                 if (extent_offset >= old->extent_offset + old->offset +
2421                     old->len || extent_offset + num_bytes <=
2422                     old->extent_offset + old->offset)
2423                         continue;
2424                 break;
2425         }
2426
2427         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2428         if (!backref) {
2429                 ret = -ENOENT;
2430                 goto out;
2431         }
2432
2433         backref->root_id = root_id;
2434         backref->inum = inum;
2435         backref->file_pos = offset;
2436         backref->num_bytes = num_bytes;
2437         backref->extent_offset = extent_offset;
2438         backref->generation = btrfs_file_extent_generation(leaf, extent);
2439         backref->old = old;
2440         backref_insert(&new->root, backref);
2441         old->count++;
2442 out:
2443         btrfs_release_path(path);
2444         WARN_ON(ret);
2445         return ret;
2446 }
2447
2448 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2449                                    struct new_sa_defrag_extent *new)
2450 {
2451         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2452         struct old_sa_defrag_extent *old, *tmp;
2453         int ret;
2454
2455         new->path = path;
2456
2457         list_for_each_entry_safe(old, tmp, &new->head, list) {
2458                 ret = iterate_inodes_from_logical(old->bytenr +
2459                                                   old->extent_offset, fs_info,
2460                                                   path, record_one_backref,
2461                                                   old, false);
2462                 if (ret < 0 && ret != -ENOENT)
2463                         return false;
2464
2465                 /* no backref to be processed for this extent */
2466                 if (!old->count) {
2467                         list_del(&old->list);
2468                         kfree(old);
2469                 }
2470         }
2471
2472         if (list_empty(&new->head))
2473                 return false;
2474
2475         return true;
2476 }
2477
2478 static int relink_is_mergable(struct extent_buffer *leaf,
2479                               struct btrfs_file_extent_item *fi,
2480                               struct new_sa_defrag_extent *new)
2481 {
2482         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2483                 return 0;
2484
2485         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2486                 return 0;
2487
2488         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2489                 return 0;
2490
2491         if (btrfs_file_extent_encryption(leaf, fi) ||
2492             btrfs_file_extent_other_encoding(leaf, fi))
2493                 return 0;
2494
2495         return 1;
2496 }
2497
2498 /*
2499  * Note the backref might has changed, and in this case we just return 0.
2500  */
2501 static noinline int relink_extent_backref(struct btrfs_path *path,
2502                                  struct sa_defrag_extent_backref *prev,
2503                                  struct sa_defrag_extent_backref *backref)
2504 {
2505         struct btrfs_file_extent_item *extent;
2506         struct btrfs_file_extent_item *item;
2507         struct btrfs_ordered_extent *ordered;
2508         struct btrfs_trans_handle *trans;
2509         struct btrfs_root *root;
2510         struct btrfs_key key;
2511         struct extent_buffer *leaf;
2512         struct old_sa_defrag_extent *old = backref->old;
2513         struct new_sa_defrag_extent *new = old->new;
2514         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2515         struct inode *inode;
2516         struct extent_state *cached = NULL;
2517         int ret = 0;
2518         u64 start;
2519         u64 len;
2520         u64 lock_start;
2521         u64 lock_end;
2522         bool merge = false;
2523         int index;
2524
2525         if (prev && prev->root_id == backref->root_id &&
2526             prev->inum == backref->inum &&
2527             prev->file_pos + prev->num_bytes == backref->file_pos)
2528                 merge = true;
2529
2530         /* step 1: get root */
2531         key.objectid = backref->root_id;
2532         key.type = BTRFS_ROOT_ITEM_KEY;
2533         key.offset = (u64)-1;
2534
2535         index = srcu_read_lock(&fs_info->subvol_srcu);
2536
2537         root = btrfs_read_fs_root_no_name(fs_info, &key);
2538         if (IS_ERR(root)) {
2539                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2540                 if (PTR_ERR(root) == -ENOENT)
2541                         return 0;
2542                 return PTR_ERR(root);
2543         }
2544
2545         if (btrfs_root_readonly(root)) {
2546                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2547                 return 0;
2548         }
2549
2550         /* step 2: get inode */
2551         key.objectid = backref->inum;
2552         key.type = BTRFS_INODE_ITEM_KEY;
2553         key.offset = 0;
2554
2555         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2556         if (IS_ERR(inode)) {
2557                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2558                 return 0;
2559         }
2560
2561         srcu_read_unlock(&fs_info->subvol_srcu, index);
2562
2563         /* step 3: relink backref */
2564         lock_start = backref->file_pos;
2565         lock_end = backref->file_pos + backref->num_bytes - 1;
2566         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2567                          &cached);
2568
2569         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2570         if (ordered) {
2571                 btrfs_put_ordered_extent(ordered);
2572                 goto out_unlock;
2573         }
2574
2575         trans = btrfs_join_transaction(root);
2576         if (IS_ERR(trans)) {
2577                 ret = PTR_ERR(trans);
2578                 goto out_unlock;
2579         }
2580
2581         key.objectid = backref->inum;
2582         key.type = BTRFS_EXTENT_DATA_KEY;
2583         key.offset = backref->file_pos;
2584
2585         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2586         if (ret < 0) {
2587                 goto out_free_path;
2588         } else if (ret > 0) {
2589                 ret = 0;
2590                 goto out_free_path;
2591         }
2592
2593         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2594                                 struct btrfs_file_extent_item);
2595
2596         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2597             backref->generation)
2598                 goto out_free_path;
2599
2600         btrfs_release_path(path);
2601
2602         start = backref->file_pos;
2603         if (backref->extent_offset < old->extent_offset + old->offset)
2604                 start += old->extent_offset + old->offset -
2605                          backref->extent_offset;
2606
2607         len = min(backref->extent_offset + backref->num_bytes,
2608                   old->extent_offset + old->offset + old->len);
2609         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2610
2611         ret = btrfs_drop_extents(trans, root, inode, start,
2612                                  start + len, 1);
2613         if (ret)
2614                 goto out_free_path;
2615 again:
2616         key.objectid = btrfs_ino(BTRFS_I(inode));
2617         key.type = BTRFS_EXTENT_DATA_KEY;
2618         key.offset = start;
2619
2620         path->leave_spinning = 1;
2621         if (merge) {
2622                 struct btrfs_file_extent_item *fi;
2623                 u64 extent_len;
2624                 struct btrfs_key found_key;
2625
2626                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2627                 if (ret < 0)
2628                         goto out_free_path;
2629
2630                 path->slots[0]--;
2631                 leaf = path->nodes[0];
2632                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2633
2634                 fi = btrfs_item_ptr(leaf, path->slots[0],
2635                                     struct btrfs_file_extent_item);
2636                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2637
2638                 if (extent_len + found_key.offset == start &&
2639                     relink_is_mergable(leaf, fi, new)) {
2640                         btrfs_set_file_extent_num_bytes(leaf, fi,
2641                                                         extent_len + len);
2642                         btrfs_mark_buffer_dirty(leaf);
2643                         inode_add_bytes(inode, len);
2644
2645                         ret = 1;
2646                         goto out_free_path;
2647                 } else {
2648                         merge = false;
2649                         btrfs_release_path(path);
2650                         goto again;
2651                 }
2652         }
2653
2654         ret = btrfs_insert_empty_item(trans, root, path, &key,
2655                                         sizeof(*extent));
2656         if (ret) {
2657                 btrfs_abort_transaction(trans, ret);
2658                 goto out_free_path;
2659         }
2660
2661         leaf = path->nodes[0];
2662         item = btrfs_item_ptr(leaf, path->slots[0],
2663                                 struct btrfs_file_extent_item);
2664         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2665         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2666         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2667         btrfs_set_file_extent_num_bytes(leaf, item, len);
2668         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2669         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2670         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2671         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2672         btrfs_set_file_extent_encryption(leaf, item, 0);
2673         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2674
2675         btrfs_mark_buffer_dirty(leaf);
2676         inode_add_bytes(inode, len);
2677         btrfs_release_path(path);
2678
2679         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2680                         new->disk_len, 0,
2681                         backref->root_id, backref->inum,
2682                         new->file_pos); /* start - extent_offset */
2683         if (ret) {
2684                 btrfs_abort_transaction(trans, ret);
2685                 goto out_free_path;
2686         }
2687
2688         ret = 1;
2689 out_free_path:
2690         btrfs_release_path(path);
2691         path->leave_spinning = 0;
2692         btrfs_end_transaction(trans);
2693 out_unlock:
2694         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2695                              &cached);
2696         iput(inode);
2697         return ret;
2698 }
2699
2700 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2701 {
2702         struct old_sa_defrag_extent *old, *tmp;
2703
2704         if (!new)
2705                 return;
2706
2707         list_for_each_entry_safe(old, tmp, &new->head, list) {
2708                 kfree(old);
2709         }
2710         kfree(new);
2711 }
2712
2713 static void relink_file_extents(struct new_sa_defrag_extent *new)
2714 {
2715         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2716         struct btrfs_path *path;
2717         struct sa_defrag_extent_backref *backref;
2718         struct sa_defrag_extent_backref *prev = NULL;
2719         struct rb_node *node;
2720         int ret;
2721
2722         path = btrfs_alloc_path();
2723         if (!path)
2724                 return;
2725
2726         if (!record_extent_backrefs(path, new)) {
2727                 btrfs_free_path(path);
2728                 goto out;
2729         }
2730         btrfs_release_path(path);
2731
2732         while (1) {
2733                 node = rb_first(&new->root);
2734                 if (!node)
2735                         break;
2736                 rb_erase(node, &new->root);
2737
2738                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2739
2740                 ret = relink_extent_backref(path, prev, backref);
2741                 WARN_ON(ret < 0);
2742
2743                 kfree(prev);
2744
2745                 if (ret == 1)
2746                         prev = backref;
2747                 else
2748                         prev = NULL;
2749                 cond_resched();
2750         }
2751         kfree(prev);
2752
2753         btrfs_free_path(path);
2754 out:
2755         free_sa_defrag_extent(new);
2756
2757         atomic_dec(&fs_info->defrag_running);
2758         wake_up(&fs_info->transaction_wait);
2759 }
2760
2761 static struct new_sa_defrag_extent *
2762 record_old_file_extents(struct inode *inode,
2763                         struct btrfs_ordered_extent *ordered)
2764 {
2765         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2766         struct btrfs_root *root = BTRFS_I(inode)->root;
2767         struct btrfs_path *path;
2768         struct btrfs_key key;
2769         struct old_sa_defrag_extent *old;
2770         struct new_sa_defrag_extent *new;
2771         int ret;
2772
2773         new = kmalloc(sizeof(*new), GFP_NOFS);
2774         if (!new)
2775                 return NULL;
2776
2777         new->inode = inode;
2778         new->file_pos = ordered->file_offset;
2779         new->len = ordered->len;
2780         new->bytenr = ordered->start;
2781         new->disk_len = ordered->disk_len;
2782         new->compress_type = ordered->compress_type;
2783         new->root = RB_ROOT;
2784         INIT_LIST_HEAD(&new->head);
2785
2786         path = btrfs_alloc_path();
2787         if (!path)
2788                 goto out_kfree;
2789
2790         key.objectid = btrfs_ino(BTRFS_I(inode));
2791         key.type = BTRFS_EXTENT_DATA_KEY;
2792         key.offset = new->file_pos;
2793
2794         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2795         if (ret < 0)
2796                 goto out_free_path;
2797         if (ret > 0 && path->slots[0] > 0)
2798                 path->slots[0]--;
2799
2800         /* find out all the old extents for the file range */
2801         while (1) {
2802                 struct btrfs_file_extent_item *extent;
2803                 struct extent_buffer *l;
2804                 int slot;
2805                 u64 num_bytes;
2806                 u64 offset;
2807                 u64 end;
2808                 u64 disk_bytenr;
2809                 u64 extent_offset;
2810
2811                 l = path->nodes[0];
2812                 slot = path->slots[0];
2813
2814                 if (slot >= btrfs_header_nritems(l)) {
2815                         ret = btrfs_next_leaf(root, path);
2816                         if (ret < 0)
2817                                 goto out_free_path;
2818                         else if (ret > 0)
2819                                 break;
2820                         continue;
2821                 }
2822
2823                 btrfs_item_key_to_cpu(l, &key, slot);
2824
2825                 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2826                         break;
2827                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2828                         break;
2829                 if (key.offset >= new->file_pos + new->len)
2830                         break;
2831
2832                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2833
2834                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2835                 if (key.offset + num_bytes < new->file_pos)
2836                         goto next;
2837
2838                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2839                 if (!disk_bytenr)
2840                         goto next;
2841
2842                 extent_offset = btrfs_file_extent_offset(l, extent);
2843
2844                 old = kmalloc(sizeof(*old), GFP_NOFS);
2845                 if (!old)
2846                         goto out_free_path;
2847
2848                 offset = max(new->file_pos, key.offset);
2849                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2850
2851                 old->bytenr = disk_bytenr;
2852                 old->extent_offset = extent_offset;
2853                 old->offset = offset - key.offset;
2854                 old->len = end - offset;
2855                 old->new = new;
2856                 old->count = 0;
2857                 list_add_tail(&old->list, &new->head);
2858 next:
2859                 path->slots[0]++;
2860                 cond_resched();
2861         }
2862
2863         btrfs_free_path(path);
2864         atomic_inc(&fs_info->defrag_running);
2865
2866         return new;
2867
2868 out_free_path:
2869         btrfs_free_path(path);
2870 out_kfree:
2871         free_sa_defrag_extent(new);
2872         return NULL;
2873 }
2874
2875 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2876                                          u64 start, u64 len)
2877 {
2878         struct btrfs_block_group_cache *cache;
2879
2880         cache = btrfs_lookup_block_group(fs_info, start);
2881         ASSERT(cache);
2882
2883         spin_lock(&cache->lock);
2884         cache->delalloc_bytes -= len;
2885         spin_unlock(&cache->lock);
2886
2887         btrfs_put_block_group(cache);
2888 }
2889
2890 /* as ordered data IO finishes, this gets called so we can finish
2891  * an ordered extent if the range of bytes in the file it covers are
2892  * fully written.
2893  */
2894 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2895 {
2896         struct inode *inode = ordered_extent->inode;
2897         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2898         struct btrfs_root *root = BTRFS_I(inode)->root;
2899         struct btrfs_trans_handle *trans = NULL;
2900         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2901         struct extent_state *cached_state = NULL;
2902         struct new_sa_defrag_extent *new = NULL;
2903         int compress_type = 0;
2904         int ret = 0;
2905         u64 logical_len = ordered_extent->len;
2906         bool nolock;
2907         bool truncated = false;
2908         bool range_locked = false;
2909         bool clear_new_delalloc_bytes = false;
2910         bool clear_reserved_extent = true;
2911
2912         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2913             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2914             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2915                 clear_new_delalloc_bytes = true;
2916
2917         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2918
2919         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2920                 ret = -EIO;
2921                 goto out;
2922         }
2923
2924         btrfs_free_io_failure_record(BTRFS_I(inode),
2925                         ordered_extent->file_offset,
2926                         ordered_extent->file_offset +
2927                         ordered_extent->len - 1);
2928
2929         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2930                 truncated = true;
2931                 logical_len = ordered_extent->truncated_len;
2932                 /* Truncated the entire extent, don't bother adding */
2933                 if (!logical_len)
2934                         goto out;
2935         }
2936
2937         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2938                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2939
2940                 /*
2941                  * For mwrite(mmap + memset to write) case, we still reserve
2942                  * space for NOCOW range.
2943                  * As NOCOW won't cause a new delayed ref, just free the space
2944                  */
2945                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2946                                        ordered_extent->len);
2947                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2948                 if (nolock)
2949                         trans = btrfs_join_transaction_nolock(root);
2950                 else
2951                         trans = btrfs_join_transaction(root);
2952                 if (IS_ERR(trans)) {
2953                         ret = PTR_ERR(trans);
2954                         trans = NULL;
2955                         goto out;
2956                 }
2957                 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2958                 ret = btrfs_update_inode_fallback(trans, root, inode);
2959                 if (ret) /* -ENOMEM or corruption */
2960                         btrfs_abort_transaction(trans, ret);
2961                 goto out;
2962         }
2963
2964         range_locked = true;
2965         lock_extent_bits(io_tree, ordered_extent->file_offset,
2966                          ordered_extent->file_offset + ordered_extent->len - 1,
2967                          &cached_state);
2968
2969         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2970                         ordered_extent->file_offset + ordered_extent->len - 1,
2971                         EXTENT_DEFRAG, 0, cached_state);
2972         if (ret) {
2973                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2974                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2975                         /* the inode is shared */
2976                         new = record_old_file_extents(inode, ordered_extent);
2977
2978                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2979                         ordered_extent->file_offset + ordered_extent->len - 1,
2980                         EXTENT_DEFRAG, 0, 0, &cached_state);
2981         }
2982
2983         if (nolock)
2984                 trans = btrfs_join_transaction_nolock(root);
2985         else
2986                 trans = btrfs_join_transaction(root);
2987         if (IS_ERR(trans)) {
2988                 ret = PTR_ERR(trans);
2989                 trans = NULL;
2990                 goto out;
2991         }
2992
2993         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2994
2995         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2996                 compress_type = ordered_extent->compress_type;
2997         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2998                 BUG_ON(compress_type);
2999                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3000                                        ordered_extent->len);
3001                 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3002                                                 ordered_extent->file_offset,
3003                                                 ordered_extent->file_offset +
3004                                                 logical_len);
3005         } else {
3006                 BUG_ON(root == fs_info->tree_root);
3007                 ret = insert_reserved_file_extent(trans, inode,
3008                                                 ordered_extent->file_offset,
3009                                                 ordered_extent->start,
3010                                                 ordered_extent->disk_len,
3011                                                 logical_len, logical_len,
3012                                                 compress_type, 0, 0,
3013                                                 BTRFS_FILE_EXTENT_REG);
3014                 if (!ret) {
3015                         clear_reserved_extent = false;
3016                         btrfs_release_delalloc_bytes(fs_info,
3017                                                      ordered_extent->start,
3018                                                      ordered_extent->disk_len);
3019                 }
3020         }
3021         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3022                            ordered_extent->file_offset, ordered_extent->len,
3023                            trans->transid);
3024         if (ret < 0) {
3025                 btrfs_abort_transaction(trans, ret);
3026                 goto out;
3027         }
3028
3029         ret = add_pending_csums(trans, inode, &ordered_extent->list);
3030         if (ret) {
3031                 btrfs_abort_transaction(trans, ret);
3032                 goto out;
3033         }
3034
3035         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3036         ret = btrfs_update_inode_fallback(trans, root, inode);
3037         if (ret) { /* -ENOMEM or corruption */
3038                 btrfs_abort_transaction(trans, ret);
3039                 goto out;
3040         }
3041         ret = 0;
3042 out:
3043         if (range_locked || clear_new_delalloc_bytes) {
3044                 unsigned int clear_bits = 0;
3045
3046                 if (range_locked)
3047                         clear_bits |= EXTENT_LOCKED;
3048                 if (clear_new_delalloc_bytes)
3049                         clear_bits |= EXTENT_DELALLOC_NEW;
3050                 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3051                                  ordered_extent->file_offset,
3052                                  ordered_extent->file_offset +
3053                                  ordered_extent->len - 1,
3054                                  clear_bits,
3055                                  (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3056                                  0, &cached_state);
3057         }
3058
3059         if (trans)
3060                 btrfs_end_transaction(trans);
3061
3062         if (ret || truncated) {
3063                 u64 start, end;
3064
3065                 if (truncated)
3066                         start = ordered_extent->file_offset + logical_len;
3067                 else
3068             &