a88122b89f50d3198200eda3b5bde6235261f742
[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_root *root;
362         struct page *locked_page;
363         u64 start;
364         u64 end;
365         unsigned int write_flags;
366         struct list_head extents;
367         struct btrfs_work work;
368 };
369
370 static noinline int add_async_extent(struct async_cow *cow,
371                                      u64 start, u64 ram_size,
372                                      u64 compressed_size,
373                                      struct page **pages,
374                                      unsigned long nr_pages,
375                                      int compress_type)
376 {
377         struct async_extent *async_extent;
378
379         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
380         BUG_ON(!async_extent); /* -ENOMEM */
381         async_extent->start = start;
382         async_extent->ram_size = ram_size;
383         async_extent->compressed_size = compressed_size;
384         async_extent->pages = pages;
385         async_extent->nr_pages = nr_pages;
386         async_extent->compress_type = compress_type;
387         list_add_tail(&async_extent->list, &cow->extents);
388         return 0;
389 }
390
391 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
392 {
393         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
394
395         /* force compress */
396         if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
397                 return 1;
398         /* defrag ioctl */
399         if (BTRFS_I(inode)->defrag_compress)
400                 return 1;
401         /* bad compression ratios */
402         if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
403                 return 0;
404         if (btrfs_test_opt(fs_info, COMPRESS) ||
405             BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
406             BTRFS_I(inode)->prop_compress)
407                 return btrfs_compress_heuristic(inode, start, end);
408         return 0;
409 }
410
411 static inline void inode_should_defrag(struct btrfs_inode *inode,
412                 u64 start, u64 end, u64 num_bytes, u64 small_write)
413 {
414         /* If this is a small write inside eof, kick off a defrag */
415         if (num_bytes < small_write &&
416             (start > 0 || end + 1 < inode->disk_i_size))
417                 btrfs_add_inode_defrag(NULL, inode);
418 }
419
420 /*
421  * we create compressed extents in two phases.  The first
422  * phase compresses a range of pages that have already been
423  * locked (both pages and state bits are locked).
424  *
425  * This is done inside an ordered work queue, and the compression
426  * is spread across many cpus.  The actual IO submission is step
427  * two, and the ordered work queue takes care of making sure that
428  * happens in the same order things were put onto the queue by
429  * writepages and friends.
430  *
431  * If this code finds it can't get good compression, it puts an
432  * entry onto the work queue to write the uncompressed bytes.  This
433  * makes sure that both compressed inodes and uncompressed inodes
434  * are written in the same order that the flusher thread sent them
435  * down.
436  */
437 static noinline void compress_file_range(struct inode *inode,
438                                         struct page *locked_page,
439                                         u64 start, u64 end,
440                                         struct async_cow *async_cow,
441                                         int *num_added)
442 {
443         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
444         u64 blocksize = fs_info->sectorsize;
445         u64 actual_end;
446         u64 isize = i_size_read(inode);
447         int ret = 0;
448         struct page **pages = NULL;
449         unsigned long nr_pages;
450         unsigned long total_compressed = 0;
451         unsigned long total_in = 0;
452         int i;
453         int will_compress;
454         int compress_type = fs_info->compress_type;
455         int redirty = 0;
456
457         inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
458                         SZ_16K);
459
460         actual_end = min_t(u64, isize, end + 1);
461 again:
462         will_compress = 0;
463         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
464         BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
465         nr_pages = min_t(unsigned long, nr_pages,
466                         BTRFS_MAX_COMPRESSED / PAGE_SIZE);
467
468         /*
469          * we don't want to send crud past the end of i_size through
470          * compression, that's just a waste of CPU time.  So, if the
471          * end of the file is before the start of our current
472          * requested range of bytes, we bail out to the uncompressed
473          * cleanup code that can deal with all of this.
474          *
475          * It isn't really the fastest way to fix things, but this is a
476          * very uncommon corner.
477          */
478         if (actual_end <= start)
479                 goto cleanup_and_bail_uncompressed;
480
481         total_compressed = actual_end - start;
482
483         /*
484          * skip compression for a small file range(<=blocksize) that
485          * isn't an inline extent, since it doesn't save disk space at all.
486          */
487         if (total_compressed <= blocksize &&
488            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
489                 goto cleanup_and_bail_uncompressed;
490
491         total_compressed = min_t(unsigned long, total_compressed,
492                         BTRFS_MAX_UNCOMPRESSED);
493         total_in = 0;
494         ret = 0;
495
496         /*
497          * we do compression for mount -o compress and when the
498          * inode has not been flagged as nocompress.  This flag can
499          * change at any time if we discover bad compression ratios.
500          */
501         if (inode_need_compress(inode, start, end)) {
502                 WARN_ON(pages);
503                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
504                 if (!pages) {
505                         /* just bail out to the uncompressed code */
506                         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         struct btrfs_root *root;
1148         unsigned long nr_pages;
1149
1150         async_cow = container_of(work, struct async_cow, work);
1151
1152         root = async_cow->root;
1153         fs_info = root->fs_info;
1154         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1155                 PAGE_SHIFT;
1156
1157         /* atomic_sub_return implies a barrier */
1158         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1159             5 * SZ_1M)
1160                 cond_wake_up_nomb(&fs_info->async_submit_wait);
1161
1162         if (async_cow->inode)
1163                 submit_compressed_extents(async_cow->inode, async_cow);
1164 }
1165
1166 static noinline void async_cow_free(struct btrfs_work *work)
1167 {
1168         struct async_cow *async_cow;
1169         async_cow = container_of(work, struct async_cow, work);
1170         if (async_cow->inode)
1171                 btrfs_add_delayed_iput(async_cow->inode);
1172         kfree(async_cow);
1173 }
1174
1175 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1176                                 u64 start, u64 end, int *page_started,
1177                                 unsigned long *nr_written,
1178                                 unsigned int write_flags)
1179 {
1180         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1181         struct async_cow *async_cow;
1182         struct btrfs_root *root = BTRFS_I(inode)->root;
1183         unsigned long nr_pages;
1184         u64 cur_end;
1185
1186         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1187                          1, 0, NULL);
1188         while (start < end) {
1189                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1190                 BUG_ON(!async_cow); /* -ENOMEM */
1191                 async_cow->inode = igrab(inode);
1192                 async_cow->root = root;
1193                 async_cow->locked_page = locked_page;
1194                 async_cow->start = start;
1195                 async_cow->write_flags = write_flags;
1196
1197                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1198                     !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1199                         cur_end = end;
1200                 else
1201                         cur_end = min(end, start + SZ_512K - 1);
1202
1203                 async_cow->end = cur_end;
1204                 INIT_LIST_HEAD(&async_cow->extents);
1205
1206                 btrfs_init_work(&async_cow->work,
1207                                 btrfs_delalloc_helper,
1208                                 async_cow_start, async_cow_submit,
1209                                 async_cow_free);
1210
1211                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1212                         PAGE_SHIFT;
1213                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1214
1215                 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1216
1217                 *nr_written += nr_pages;
1218                 start = cur_end + 1;
1219         }
1220         *page_started = 1;
1221         return 0;
1222 }
1223
1224 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1225                                         u64 bytenr, u64 num_bytes)
1226 {
1227         int ret;
1228         struct btrfs_ordered_sum *sums;
1229         LIST_HEAD(list);
1230
1231         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1232                                        bytenr + num_bytes - 1, &list, 0);
1233         if (ret == 0 && list_empty(&list))
1234                 return 0;
1235
1236         while (!list_empty(&list)) {
1237                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1238                 list_del(&sums->list);
1239                 kfree(sums);
1240         }
1241         if (ret < 0)
1242                 return ret;
1243         return 1;
1244 }
1245
1246 /*
1247  * when nowcow writeback call back.  This checks for snapshots or COW copies
1248  * of the extents that exist in the file, and COWs the file as required.
1249  *
1250  * If no cow copies or snapshots exist, we write directly to the existing
1251  * blocks on disk
1252  */
1253 static noinline int run_delalloc_nocow(struct inode *inode,
1254                                        struct page *locked_page,
1255                               u64 start, u64 end, int *page_started, int force,
1256                               unsigned long *nr_written)
1257 {
1258         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1259         struct btrfs_root *root = BTRFS_I(inode)->root;
1260         struct extent_buffer *leaf;
1261         struct btrfs_path *path;
1262         struct btrfs_file_extent_item *fi;
1263         struct btrfs_key found_key;
1264         struct extent_map *em;
1265         u64 cow_start;
1266         u64 cur_offset;
1267         u64 extent_end;
1268         u64 extent_offset;
1269         u64 disk_bytenr;
1270         u64 num_bytes;
1271         u64 disk_num_bytes;
1272         u64 ram_bytes;
1273         int extent_type;
1274         int ret;
1275         int type;
1276         int nocow;
1277         int check_prev = 1;
1278         bool nolock;
1279         u64 ino = btrfs_ino(BTRFS_I(inode));
1280
1281         path = btrfs_alloc_path();
1282         if (!path) {
1283                 extent_clear_unlock_delalloc(inode, start, end, end,
1284                                              locked_page,
1285                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1286                                              EXTENT_DO_ACCOUNTING |
1287                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1288                                              PAGE_CLEAR_DIRTY |
1289                                              PAGE_SET_WRITEBACK |
1290                                              PAGE_END_WRITEBACK);
1291                 return -ENOMEM;
1292         }
1293
1294         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1295
1296         cow_start = (u64)-1;
1297         cur_offset = start;
1298         while (1) {
1299                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1300                                                cur_offset, 0);
1301                 if (ret < 0)
1302                         goto error;
1303                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1304                         leaf = path->nodes[0];
1305                         btrfs_item_key_to_cpu(leaf, &found_key,
1306                                               path->slots[0] - 1);
1307                         if (found_key.objectid == ino &&
1308                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1309                                 path->slots[0]--;
1310                 }
1311                 check_prev = 0;
1312 next_slot:
1313                 leaf = path->nodes[0];
1314                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1315                         ret = btrfs_next_leaf(root, path);
1316                         if (ret < 0) {
1317                                 if (cow_start != (u64)-1)
1318                                         cur_offset = cow_start;
1319                                 goto error;
1320                         }
1321                         if (ret > 0)
1322                                 break;
1323                         leaf = path->nodes[0];
1324                 }
1325
1326                 nocow = 0;
1327                 disk_bytenr = 0;
1328                 num_bytes = 0;
1329                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1330
1331                 if (found_key.objectid > ino)
1332                         break;
1333                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1334                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1335                         path->slots[0]++;
1336                         goto next_slot;
1337                 }
1338                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1339                     found_key.offset > end)
1340                         break;
1341
1342                 if (found_key.offset > cur_offset) {
1343                         extent_end = found_key.offset;
1344                         extent_type = 0;
1345                         goto out_check;
1346                 }
1347
1348                 fi = btrfs_item_ptr(leaf, path->slots[0],
1349                                     struct btrfs_file_extent_item);
1350                 extent_type = btrfs_file_extent_type(leaf, fi);
1351
1352                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1353                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1354                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1355                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1356                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1357                         extent_end = found_key.offset +
1358                                 btrfs_file_extent_num_bytes(leaf, fi);
1359                         disk_num_bytes =
1360                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1361                         if (extent_end <= start) {
1362                                 path->slots[0]++;
1363                                 goto next_slot;
1364                         }
1365                         if (disk_bytenr == 0)
1366                                 goto out_check;
1367                         if (btrfs_file_extent_compression(leaf, fi) ||
1368                             btrfs_file_extent_encryption(leaf, fi) ||
1369                             btrfs_file_extent_other_encoding(leaf, fi))
1370                                 goto out_check;
1371                         /*
1372                          * Do the same check as in btrfs_cross_ref_exist but
1373                          * without the unnecessary search.
1374                          */
1375                         if (btrfs_file_extent_generation(leaf, fi) <=
1376                             btrfs_root_last_snapshot(&root->root_item))
1377                                 goto out_check;
1378                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1379                                 goto out_check;
1380                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1381                                 goto out_check;
1382                         ret = btrfs_cross_ref_exist(root, ino,
1383                                                     found_key.offset -
1384                                                     extent_offset, disk_bytenr);
1385                         if (ret) {
1386                                 /*
1387                                  * ret could be -EIO if the above fails to read
1388                                  * metadata.
1389                                  */
1390                                 if (ret < 0) {
1391                                         if (cow_start != (u64)-1)
1392                                                 cur_offset = cow_start;
1393                                         goto error;
1394                                 }
1395
1396                                 WARN_ON_ONCE(nolock);
1397                                 goto out_check;
1398                         }
1399                         disk_bytenr += extent_offset;
1400                         disk_bytenr += cur_offset - found_key.offset;
1401                         num_bytes = min(end + 1, extent_end) - cur_offset;
1402                         /*
1403                          * if there are pending snapshots for this root,
1404                          * we fall into common COW way.
1405                          */
1406                         if (!nolock && atomic_read(&root->snapshot_force_cow))
1407                                 goto out_check;
1408                         /*
1409                          * force cow if csum exists in the range.
1410                          * this ensure that csum for a given extent are
1411                          * either valid or do not exist.
1412                          */
1413                         ret = csum_exist_in_range(fs_info, disk_bytenr,
1414                                                   num_bytes);
1415                         if (ret) {
1416                                 /*
1417                                  * ret could be -EIO if the above fails to read
1418                                  * metadata.
1419                                  */
1420                                 if (ret < 0) {
1421                                         if (cow_start != (u64)-1)
1422                                                 cur_offset = cow_start;
1423                                         goto error;
1424                                 }
1425                                 WARN_ON_ONCE(nolock);
1426                                 goto out_check;
1427                         }
1428                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1429                                 goto out_check;
1430                         nocow = 1;
1431                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1432                         extent_end = found_key.offset +
1433                                 btrfs_file_extent_ram_bytes(leaf, fi);
1434                         extent_end = ALIGN(extent_end,
1435                                            fs_info->sectorsize);
1436                 } else {
1437                         BUG_ON(1);
1438                 }
1439 out_check:
1440                 if (extent_end <= start) {
1441                         path->slots[0]++;
1442                         if (nocow)
1443                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1444                         goto next_slot;
1445                 }
1446                 if (!nocow) {
1447                         if (cow_start == (u64)-1)
1448                                 cow_start = cur_offset;
1449                         cur_offset = extent_end;
1450                         if (cur_offset > end)
1451                                 break;
1452                         path->slots[0]++;
1453                         goto next_slot;
1454                 }
1455
1456                 btrfs_release_path(path);
1457                 if (cow_start != (u64)-1) {
1458                         ret = cow_file_range(inode, locked_page,
1459                                              cow_start, found_key.offset - 1,
1460                                              end, page_started, nr_written, 1,
1461                                              NULL);
1462                         if (ret) {
1463                                 if (nocow)
1464                                         btrfs_dec_nocow_writers(fs_info,
1465                                                                 disk_bytenr);
1466                                 goto error;
1467                         }
1468                         cow_start = (u64)-1;
1469                 }
1470
1471                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1472                         u64 orig_start = found_key.offset - extent_offset;
1473
1474                         em = create_io_em(inode, cur_offset, num_bytes,
1475                                           orig_start,
1476                                           disk_bytenr, /* block_start */
1477                                           num_bytes, /* block_len */
1478                                           disk_num_bytes, /* orig_block_len */
1479                                           ram_bytes, BTRFS_COMPRESS_NONE,
1480                                           BTRFS_ORDERED_PREALLOC);
1481                         if (IS_ERR(em)) {
1482                                 if (nocow)
1483                                         btrfs_dec_nocow_writers(fs_info,
1484                                                                 disk_bytenr);
1485                                 ret = PTR_ERR(em);
1486                                 goto error;
1487                         }
1488                         free_extent_map(em);
1489                 }
1490
1491                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1492                         type = BTRFS_ORDERED_PREALLOC;
1493                 } else {
1494                         type = BTRFS_ORDERED_NOCOW;
1495                 }
1496
1497                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1498                                                num_bytes, num_bytes, type);
1499                 if (nocow)
1500                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1501                 BUG_ON(ret); /* -ENOMEM */
1502
1503                 if (root->root_key.objectid ==
1504                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1505                         /*
1506                          * Error handled later, as we must prevent
1507                          * extent_clear_unlock_delalloc() in error handler
1508                          * from freeing metadata of created ordered extent.
1509                          */
1510                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1511                                                       num_bytes);
1512
1513                 extent_clear_unlock_delalloc(inode, cur_offset,
1514                                              cur_offset + num_bytes - 1, end,
1515                                              locked_page, EXTENT_LOCKED |
1516                                              EXTENT_DELALLOC |
1517                                              EXTENT_CLEAR_DATA_RESV,
1518                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1519
1520                 cur_offset = extent_end;
1521
1522                 /*
1523                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1524                  * handler, as metadata for created ordered extent will only
1525                  * be freed by btrfs_finish_ordered_io().
1526                  */
1527                 if (ret)
1528                         goto error;
1529                 if (cur_offset > end)
1530                         break;
1531         }
1532         btrfs_release_path(path);
1533
1534         if (cur_offset <= end && cow_start == (u64)-1)
1535                 cow_start = cur_offset;
1536
1537         if (cow_start != (u64)-1) {
1538                 cur_offset = end;
1539                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1540                                      page_started, nr_written, 1, NULL);
1541                 if (ret)
1542                         goto error;
1543         }
1544
1545 error:
1546         if (ret && cur_offset < end)
1547                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1548                                              locked_page, EXTENT_LOCKED |
1549                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1550                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1551                                              PAGE_CLEAR_DIRTY |
1552                                              PAGE_SET_WRITEBACK |
1553                                              PAGE_END_WRITEBACK);
1554         btrfs_free_path(path);
1555         return ret;
1556 }
1557
1558 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1559 {
1560
1561         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1562             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1563                 return 0;
1564
1565         /*
1566          * @defrag_bytes is a hint value, no spinlock held here,
1567          * if is not zero, it means the file is defragging.
1568          * Force cow if given extent needs to be defragged.
1569          */
1570         if (BTRFS_I(inode)->defrag_bytes &&
1571             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1572                            EXTENT_DEFRAG, 0, NULL))
1573                 return 1;
1574
1575         return 0;
1576 }
1577
1578 /*
1579  * Function to process delayed allocation (create CoW) for ranges which are
1580  * being touched for the first time.
1581  */
1582 int btrfs_run_delalloc_range(void *private_data, struct page *locked_page,
1583                 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1584                 struct writeback_control *wbc)
1585 {
1586         struct inode *inode = private_data;
1587         int ret;
1588         int force_cow = need_force_cow(inode, start, end);
1589         unsigned int write_flags = wbc_to_write_flags(wbc);
1590
1591         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1592                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1593                                          page_started, 1, nr_written);
1594         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1595                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1596                                          page_started, 0, nr_written);
1597         } else if (!inode_need_compress(inode, start, end)) {
1598                 ret = cow_file_range(inode, locked_page, start, end, end,
1599                                       page_started, nr_written, 1, NULL);
1600         } else {
1601                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1602                         &BTRFS_I(inode)->runtime_flags);
1603                 ret = cow_file_range_async(inode, locked_page, start, end,
1604                                            page_started, nr_written,
1605                                            write_flags);
1606         }
1607         if (ret)
1608                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1609         return ret;
1610 }
1611
1612 void btrfs_split_delalloc_extent(struct inode *inode,
1613                                  struct extent_state *orig, u64 split)
1614 {
1615         u64 size;
1616
1617         /* not delalloc, ignore it */
1618         if (!(orig->state & EXTENT_DELALLOC))
1619                 return;
1620
1621         size = orig->end - orig->start + 1;
1622         if (size > BTRFS_MAX_EXTENT_SIZE) {
1623                 u32 num_extents;
1624                 u64 new_size;
1625
1626                 /*
1627                  * See the explanation in btrfs_merge_delalloc_extent, the same
1628                  * applies here, just in reverse.
1629                  */
1630                 new_size = orig->end - split + 1;
1631                 num_extents = count_max_extents(new_size);
1632                 new_size = split - orig->start;
1633                 num_extents += count_max_extents(new_size);
1634                 if (count_max_extents(size) >= num_extents)
1635                         return;
1636         }
1637
1638         spin_lock(&BTRFS_I(inode)->lock);
1639         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1640         spin_unlock(&BTRFS_I(inode)->lock);
1641 }
1642
1643 /*
1644  * Handle merged delayed allocation extents so we can keep track of new extents
1645  * that are just merged onto old extents, such as when we are doing sequential
1646  * writes, so we can properly account for the metadata space we'll need.
1647  */
1648 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1649                                  struct extent_state *other)
1650 {
1651         u64 new_size, old_size;
1652         u32 num_extents;
1653
1654         /* not delalloc, ignore it */
1655         if (!(other->state & EXTENT_DELALLOC))
1656                 return;
1657
1658         if (new->start > other->start)
1659                 new_size = new->end - other->start + 1;
1660         else
1661                 new_size = other->end - new->start + 1;
1662
1663         /* we're not bigger than the max, unreserve the space and go */
1664         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1665                 spin_lock(&BTRFS_I(inode)->lock);
1666                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1667                 spin_unlock(&BTRFS_I(inode)->lock);
1668                 return;
1669         }
1670
1671         /*
1672          * We have to add up either side to figure out how many extents were
1673          * accounted for before we merged into one big extent.  If the number of
1674          * extents we accounted for is <= the amount we need for the new range
1675          * then we can return, otherwise drop.  Think of it like this
1676          *
1677          * [ 4k][MAX_SIZE]
1678          *
1679          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1680          * need 2 outstanding extents, on one side we have 1 and the other side
1681          * we have 1 so they are == and we can return.  But in this case
1682          *
1683          * [MAX_SIZE+4k][MAX_SIZE+4k]
1684          *
1685          * Each range on their own accounts for 2 extents, but merged together
1686          * they are only 3 extents worth of accounting, so we need to drop in
1687          * this case.
1688          */
1689         old_size = other->end - other->start + 1;
1690         num_extents = count_max_extents(old_size);
1691         old_size = new->end - new->start + 1;
1692         num_extents += count_max_extents(old_size);
1693         if (count_max_extents(new_size) >= num_extents)
1694                 return;
1695
1696         spin_lock(&BTRFS_I(inode)->lock);
1697         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1698         spin_unlock(&BTRFS_I(inode)->lock);
1699 }
1700
1701 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1702                                       struct inode *inode)
1703 {
1704         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1705
1706         spin_lock(&root->delalloc_lock);
1707         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1708                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1709                               &root->delalloc_inodes);
1710                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1711                         &BTRFS_I(inode)->runtime_flags);
1712                 root->nr_delalloc_inodes++;
1713                 if (root->nr_delalloc_inodes == 1) {
1714                         spin_lock(&fs_info->delalloc_root_lock);
1715                         BUG_ON(!list_empty(&root->delalloc_root));
1716                         list_add_tail(&root->delalloc_root,
1717                                       &fs_info->delalloc_roots);
1718                         spin_unlock(&fs_info->delalloc_root_lock);
1719                 }
1720         }
1721         spin_unlock(&root->delalloc_lock);
1722 }
1723
1724
1725 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1726                                 struct btrfs_inode *inode)
1727 {
1728         struct btrfs_fs_info *fs_info = root->fs_info;
1729
1730         if (!list_empty(&inode->delalloc_inodes)) {
1731                 list_del_init(&inode->delalloc_inodes);
1732                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1733                           &inode->runtime_flags);
1734                 root->nr_delalloc_inodes--;
1735                 if (!root->nr_delalloc_inodes) {
1736                         ASSERT(list_empty(&root->delalloc_inodes));
1737                         spin_lock(&fs_info->delalloc_root_lock);
1738                         BUG_ON(list_empty(&root->delalloc_root));
1739                         list_del_init(&root->delalloc_root);
1740                         spin_unlock(&fs_info->delalloc_root_lock);
1741                 }
1742         }
1743 }
1744
1745 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1746                                      struct btrfs_inode *inode)
1747 {
1748         spin_lock(&root->delalloc_lock);
1749         __btrfs_del_delalloc_inode(root, inode);
1750         spin_unlock(&root->delalloc_lock);
1751 }
1752
1753 /*
1754  * Properly track delayed allocation bytes in the inode and to maintain the
1755  * list of inodes that have pending delalloc work to be done.
1756  */
1757 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1758                                unsigned *bits)
1759 {
1760         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1761
1762         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1763                 WARN_ON(1);
1764         /*
1765          * set_bit and clear bit hooks normally require _irqsave/restore
1766          * but in this case, we are only testing for the DELALLOC
1767          * bit, which is only set or cleared with irqs on
1768          */
1769         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1770                 struct btrfs_root *root = BTRFS_I(inode)->root;
1771                 u64 len = state->end + 1 - state->start;
1772                 u32 num_extents = count_max_extents(len);
1773                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1774
1775                 spin_lock(&BTRFS_I(inode)->lock);
1776                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1777                 spin_unlock(&BTRFS_I(inode)->lock);
1778
1779                 /* For sanity tests */
1780                 if (btrfs_is_testing(fs_info))
1781                         return;
1782
1783                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1784                                          fs_info->delalloc_batch);
1785                 spin_lock(&BTRFS_I(inode)->lock);
1786                 BTRFS_I(inode)->delalloc_bytes += len;
1787                 if (*bits & EXTENT_DEFRAG)
1788                         BTRFS_I(inode)->defrag_bytes += len;
1789                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1790                                          &BTRFS_I(inode)->runtime_flags))
1791                         btrfs_add_delalloc_inodes(root, inode);
1792                 spin_unlock(&BTRFS_I(inode)->lock);
1793         }
1794
1795         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1796             (*bits & EXTENT_DELALLOC_NEW)) {
1797                 spin_lock(&BTRFS_I(inode)->lock);
1798                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1799                         state->start;
1800                 spin_unlock(&BTRFS_I(inode)->lock);
1801         }
1802 }
1803
1804 /*
1805  * Once a range is no longer delalloc this function ensures that proper
1806  * accounting happens.
1807  */
1808 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1809                                  struct extent_state *state, unsigned *bits)
1810 {
1811         struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1812         struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1813         u64 len = state->end + 1 - state->start;
1814         u32 num_extents = count_max_extents(len);
1815
1816         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1817                 spin_lock(&inode->lock);
1818                 inode->defrag_bytes -= len;
1819                 spin_unlock(&inode->lock);
1820         }
1821
1822         /*
1823          * set_bit and clear bit hooks normally require _irqsave/restore
1824          * but in this case, we are only testing for the DELALLOC
1825          * bit, which is only set or cleared with irqs on
1826          */
1827         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1828                 struct btrfs_root *root = inode->root;
1829                 bool do_list = !btrfs_is_free_space_inode(inode);
1830
1831                 spin_lock(&inode->lock);
1832                 btrfs_mod_outstanding_extents(inode, -num_extents);
1833                 spin_unlock(&inode->lock);
1834
1835                 /*
1836                  * We don't reserve metadata space for space cache inodes so we
1837                  * don't need to call dellalloc_release_metadata if there is an
1838                  * error.
1839                  */
1840                 if (*bits & EXTENT_CLEAR_META_RESV &&
1841                     root != fs_info->tree_root)
1842                         btrfs_delalloc_release_metadata(inode, len, false);
1843
1844                 /* For sanity tests. */
1845                 if (btrfs_is_testing(fs_info))
1846                         return;
1847
1848                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1849                     do_list && !(state->state & EXTENT_NORESERVE) &&
1850                     (*bits & EXTENT_CLEAR_DATA_RESV))
1851                         btrfs_free_reserved_data_space_noquota(
1852                                         &inode->vfs_inode,
1853                                         state->start, len);
1854
1855                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1856                                          fs_info->delalloc_batch);
1857                 spin_lock(&inode->lock);
1858                 inode->delalloc_bytes -= len;
1859                 if (do_list && inode->delalloc_bytes == 0 &&
1860                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1861                                         &inode->runtime_flags))
1862                         btrfs_del_delalloc_inode(root, inode);
1863                 spin_unlock(&inode->lock);
1864         }
1865
1866         if ((state->state & EXTENT_DELALLOC_NEW) &&
1867             (*bits & EXTENT_DELALLOC_NEW)) {
1868                 spin_lock(&inode->lock);
1869                 ASSERT(inode->new_delalloc_bytes >= len);
1870                 inode->new_delalloc_bytes -= len;
1871                 spin_unlock(&inode->lock);
1872         }
1873 }
1874
1875 /*
1876  * Merge bio hook, this must check the chunk tree to make sure we don't create
1877  * bios that span stripes or chunks
1878  *
1879  * return 1 if page cannot be merged to bio
1880  * return 0 if page can be merged to bio
1881  * return error otherwise
1882  */
1883 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1884                          size_t size, struct bio *bio,
1885                          unsigned long bio_flags)
1886 {
1887         struct inode *inode = page->mapping->host;
1888         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1889         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1890         u64 length = 0;
1891         u64 map_length;
1892         int ret;
1893
1894         if (bio_flags & EXTENT_BIO_COMPRESSED)
1895                 return 0;
1896
1897         length = bio->bi_iter.bi_size;
1898         map_length = length;
1899         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1900                               NULL, 0);
1901         if (ret < 0)
1902                 return ret;
1903         if (map_length < length + size)
1904                 return 1;
1905         return 0;
1906 }
1907
1908 /*
1909  * in order to insert checksums into the metadata in large chunks,
1910  * we wait until bio submission time.   All the pages in the bio are
1911  * checksummed and sums are attached onto the ordered extent record.
1912  *
1913  * At IO completion time the cums attached on the ordered extent record
1914  * are inserted into the btree
1915  */
1916 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1917                                     u64 bio_offset)
1918 {
1919         struct inode *inode = private_data;
1920         blk_status_t ret = 0;
1921
1922         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1923         BUG_ON(ret); /* -ENOMEM */
1924         return 0;
1925 }
1926
1927 /*
1928  * extent_io.c submission hook. This does the right thing for csum calculation
1929  * on write, or reading the csums from the tree before a read.
1930  *
1931  * Rules about async/sync submit,
1932  * a) read:                             sync submit
1933  *
1934  * b) write without checksum:           sync submit
1935  *
1936  * c) write with checksum:
1937  *    c-1) if bio is issued by fsync:   sync submit
1938  *         (sync_writers != 0)
1939  *
1940  *    c-2) if root is reloc root:       sync submit
1941  *         (only in case of buffered IO)
1942  *
1943  *    c-3) otherwise:                   async submit
1944  */
1945 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1946                                  int mirror_num, unsigned long bio_flags,
1947                                  u64 bio_offset)
1948 {
1949         struct inode *inode = private_data;
1950         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1951         struct btrfs_root *root = BTRFS_I(inode)->root;
1952         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1953         blk_status_t ret = 0;
1954         int skip_sum;
1955         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1956
1957         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1958
1959         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1960                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1961
1962         if (bio_op(bio) != REQ_OP_WRITE) {
1963                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1964                 if (ret)
1965                         goto out;
1966
1967                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1968                         ret = btrfs_submit_compressed_read(inode, bio,
1969                                                            mirror_num,
1970                                                            bio_flags);
1971                         goto out;
1972                 } else if (!skip_sum) {
1973                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1974                         if (ret)
1975                                 goto out;
1976                 }
1977                 goto mapit;
1978         } else if (async && !skip_sum) {
1979                 /* csum items have already been cloned */
1980                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1981                         goto mapit;
1982                 /* we're doing a write, do the async checksumming */
1983                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
1984                                           bio_offset, inode,
1985                                           btrfs_submit_bio_start);
1986                 goto out;
1987         } else if (!skip_sum) {
1988                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1989                 if (ret)
1990                         goto out;
1991         }
1992
1993 mapit:
1994         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
1995
1996 out:
1997         if (ret) {
1998                 bio->bi_status = ret;
1999                 bio_endio(bio);
2000         }
2001         return ret;
2002 }
2003
2004 /*
2005  * given a list of ordered sums record them in the inode.  This happens
2006  * at IO completion time based on sums calculated at bio submission time.
2007  */
2008 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2009                              struct inode *inode, struct list_head *list)
2010 {
2011         struct btrfs_ordered_sum *sum;
2012         int ret;
2013
2014         list_for_each_entry(sum, list, list) {
2015                 trans->adding_csums = true;
2016                 ret = btrfs_csum_file_blocks(trans,
2017                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2018                 trans->adding_csums = false;
2019                 if (ret)
2020                         return ret;
2021         }
2022         return 0;
2023 }
2024
2025 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2026                               unsigned int extra_bits,
2027                               struct extent_state **cached_state, int dedupe)
2028 {
2029         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2030         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2031                                    extra_bits, cached_state);
2032 }
2033
2034 /* see btrfs_writepage_start_hook for details on why this is required */
2035 struct btrfs_writepage_fixup {
2036         struct page *page;
2037         struct btrfs_work work;
2038 };
2039
2040 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2041 {
2042         struct btrfs_writepage_fixup *fixup;
2043         struct btrfs_ordered_extent *ordered;
2044         struct extent_state *cached_state = NULL;
2045         struct extent_changeset *data_reserved = NULL;
2046         struct page *page;
2047         struct inode *inode;
2048         u64 page_start;
2049         u64 page_end;
2050         int ret;
2051
2052         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2053         page = fixup->page;
2054 again:
2055         lock_page(page);
2056         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2057                 ClearPageChecked(page);
2058                 goto out_page;
2059         }
2060
2061         inode = page->mapping->host;
2062         page_start = page_offset(page);
2063         page_end = page_offset(page) + PAGE_SIZE - 1;
2064
2065         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2066                          &cached_state);
2067
2068         /* already ordered? We're done */
2069         if (PagePrivate2(page))
2070                 goto out;
2071
2072         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2073                                         PAGE_SIZE);
2074         if (ordered) {
2075                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2076                                      page_end, &cached_state);
2077                 unlock_page(page);
2078                 btrfs_start_ordered_extent(inode, ordered, 1);
2079                 btrfs_put_ordered_extent(ordered);
2080                 goto again;
2081         }
2082
2083         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2084                                            PAGE_SIZE);
2085         if (ret) {
2086                 mapping_set_error(page->mapping, ret);
2087                 end_extent_writepage(page, ret, page_start, page_end);
2088                 ClearPageChecked(page);
2089                 goto out;
2090          }
2091
2092         ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2093                                         &cached_state, 0);
2094         if (ret) {
2095                 mapping_set_error(page->mapping, ret);
2096                 end_extent_writepage(page, ret, page_start, page_end);
2097                 ClearPageChecked(page);
2098                 goto out;
2099         }
2100
2101         ClearPageChecked(page);
2102         set_page_dirty(page);
2103         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2104 out:
2105         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2106                              &cached_state);
2107 out_page:
2108         unlock_page(page);
2109         put_page(page);
2110         kfree(fixup);
2111         extent_changeset_free(data_reserved);
2112 }
2113
2114 /*
2115  * There are a few paths in the higher layers of the kernel that directly
2116  * set the page dirty bit without asking the filesystem if it is a
2117  * good idea.  This causes problems because we want to make sure COW
2118  * properly happens and the data=ordered rules are followed.
2119  *
2120  * In our case any range that doesn't have the ORDERED bit set
2121  * hasn't been properly setup for IO.  We kick off an async process
2122  * to fix it up.  The async helper will wait for ordered extents, set
2123  * the delalloc bit and make it safe to write the page.
2124  */
2125 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2126 {
2127         struct inode *inode = page->mapping->host;
2128         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2129         struct btrfs_writepage_fixup *fixup;
2130
2131         /* this page is properly in the ordered list */
2132         if (TestClearPagePrivate2(page))
2133                 return 0;
2134
2135         if (PageChecked(page))
2136                 return -EAGAIN;
2137
2138         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2139         if (!fixup)
2140                 return -EAGAIN;
2141
2142         SetPageChecked(page);
2143         get_page(page);
2144         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2145                         btrfs_writepage_fixup_worker, NULL, NULL);
2146         fixup->page = page;
2147         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2148         return -EBUSY;
2149 }
2150
2151 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2152                                        struct inode *inode, u64 file_pos,
2153                                        u64 disk_bytenr, u64 disk_num_bytes,
2154                                        u64 num_bytes, u64 ram_bytes,
2155                                        u8 compression, u8 encryption,
2156                                        u16 other_encoding, int extent_type)
2157 {
2158         struct btrfs_root *root = BTRFS_I(inode)->root;
2159         struct btrfs_file_extent_item *fi;
2160         struct btrfs_path *path;
2161         struct extent_buffer *leaf;
2162         struct btrfs_key ins;
2163         u64 qg_released;
2164         int extent_inserted = 0;
2165         int ret;
2166
2167         path = btrfs_alloc_path();
2168         if (!path)
2169                 return -ENOMEM;
2170
2171         /*
2172          * we may be replacing one extent in the tree with another.
2173          * The new extent is pinned in the extent map, and we don't want
2174          * to drop it from the cache until it is completely in the btree.
2175          *
2176          * So, tell btrfs_drop_extents to leave this extent in the cache.
2177          * the caller is expected to unpin it and allow it to be merged
2178          * with the others.
2179          */
2180         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2181                                    file_pos + num_bytes, NULL, 0,
2182                                    1, sizeof(*fi), &extent_inserted);
2183         if (ret)
2184                 goto out;
2185
2186         if (!extent_inserted) {
2187                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2188                 ins.offset = file_pos;
2189                 ins.type = BTRFS_EXTENT_DATA_KEY;
2190
2191                 path->leave_spinning = 1;
2192                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2193                                               sizeof(*fi));
2194                 if (ret)
2195                         goto out;
2196         }
2197         leaf = path->nodes[0];
2198         fi = btrfs_item_ptr(leaf, path->slots[0],
2199                             struct btrfs_file_extent_item);
2200         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2201         btrfs_set_file_extent_type(leaf, fi, extent_type);
2202         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2203         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2204         btrfs_set_file_extent_offset(leaf, fi, 0);
2205         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2206         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2207         btrfs_set_file_extent_compression(leaf, fi, compression);
2208         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2209         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2210
2211         btrfs_mark_buffer_dirty(leaf);
2212         btrfs_release_path(path);
2213
2214         inode_add_bytes(inode, num_bytes);
2215
2216         ins.objectid = disk_bytenr;
2217         ins.offset = disk_num_bytes;
2218         ins.type = BTRFS_EXTENT_ITEM_KEY;
2219
2220         /*
2221          * Release the reserved range from inode dirty range map, as it is
2222          * already moved into delayed_ref_head
2223          */
2224         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2225         if (ret < 0)
2226                 goto out;
2227         qg_released = ret;
2228         ret = btrfs_alloc_reserved_file_extent(trans, root,
2229                                                btrfs_ino(BTRFS_I(inode)),
2230                                                file_pos, qg_released, &ins);
2231 out:
2232         btrfs_free_path(path);
2233
2234         return ret;
2235 }
2236
2237 /* snapshot-aware defrag */
2238 struct sa_defrag_extent_backref {
2239         struct rb_node node;
2240         struct old_sa_defrag_extent *old;
2241         u64 root_id;
2242         u64 inum;
2243         u64 file_pos;
2244         u64 extent_offset;
2245         u64 num_bytes;
2246         u64 generation;
2247 };
2248
2249 struct old_sa_defrag_extent {
2250         struct list_head list;
2251         struct new_sa_defrag_extent *new;
2252
2253         u64 extent_offset;
2254         u64 bytenr;
2255         u64 offset;
2256         u64 len;
2257         int count;
2258 };
2259
2260 struct new_sa_defrag_extent {
2261         struct rb_root root;
2262         struct list_head head;
2263         struct btrfs_path *path;
2264         struct inode *inode;
2265         u64 file_pos;
2266         u64 len;
2267         u64 bytenr;
2268         u64 disk_len;
2269         u8 compress_type;
2270 };
2271
2272 static int backref_comp(struct sa_defrag_extent_backref *b1,
2273                         struct sa_defrag_extent_backref *b2)
2274 {
2275         if (b1->root_id < b2->root_id)
2276                 return -1;
2277         else if (b1->root_id > b2->root_id)
2278                 return 1;
2279
2280         if (b1->inum < b2->inum)
2281                 return -1;
2282         else if (b1->inum > b2->inum)
2283                 return 1;
2284
2285         if (b1->file_pos < b2->file_pos)
2286                 return -1;
2287         else if (b1->file_pos > b2->file_pos)
2288                 return 1;
2289
2290         /*
2291          * [------------------------------] ===> (a range of space)
2292          *     |<--->|   |<---->| =============> (fs/file tree A)
2293          * |<---------------------------->| ===> (fs/file tree B)
2294          *
2295          * A range of space can refer to two file extents in one tree while
2296          * refer to only one file extent in another tree.
2297          *
2298          * So we may process a disk offset more than one time(two extents in A)
2299          * and locate at the same extent(one extent in B), then insert two same
2300          * backrefs(both refer to the extent in B).
2301          */
2302         return 0;
2303 }
2304
2305 static void backref_insert(struct rb_root *root,
2306                            struct sa_defrag_extent_backref *backref)
2307 {
2308         struct rb_node **p = &root->rb_node;
2309         struct rb_node *parent = NULL;
2310         struct sa_defrag_extent_backref *entry;
2311         int ret;
2312
2313         while (*p) {
2314                 parent = *p;
2315                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2316
2317                 ret = backref_comp(backref, entry);
2318                 if (ret < 0)
2319                         p = &(*p)->rb_left;
2320                 else
2321                         p = &(*p)->rb_right;
2322         }
2323
2324         rb_link_node(&backref->node, parent, p);
2325         rb_insert_color(&backref->node, root);
2326 }
2327
2328 /*
2329  * Note the backref might has changed, and in this case we just return 0.
2330  */
2331 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2332                                        void *ctx)
2333 {
2334         struct btrfs_file_extent_item *extent;
2335         struct old_sa_defrag_extent *old = ctx;
2336         struct new_sa_defrag_extent *new = old->new;
2337         struct btrfs_path *path = new->path;
2338         struct btrfs_key key;
2339         struct btrfs_root *root;
2340         struct sa_defrag_extent_backref *backref;
2341         struct extent_buffer *leaf;
2342         struct inode *inode = new->inode;
2343         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2344         int slot;
2345         int ret;
2346         u64 extent_offset;
2347         u64 num_bytes;
2348
2349         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2350             inum == btrfs_ino(BTRFS_I(inode)))
2351                 return 0;
2352
2353         key.objectid = root_id;
2354         key.type = BTRFS_ROOT_ITEM_KEY;
2355         key.offset = (u64)-1;
2356
2357         root = btrfs_read_fs_root_no_name(fs_info, &key);
2358         if (IS_ERR(root)) {
2359                 if (PTR_ERR(root) == -ENOENT)
2360                         return 0;
2361                 WARN_ON(1);
2362                 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2363                          inum, offset, root_id);
2364                 return PTR_ERR(root);
2365         }
2366
2367         key.objectid = inum;
2368         key.type = BTRFS_EXTENT_DATA_KEY;
2369         if (offset > (u64)-1 << 32)
2370                 key.offset = 0;
2371         else
2372                 key.offset = offset;
2373
2374         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2375         if (WARN_ON(ret < 0))
2376                 return ret;
2377         ret = 0;
2378
2379         while (1) {
2380                 cond_resched();
2381
2382                 leaf = path->nodes[0];
2383                 slot = path->slots[0];
2384
2385                 if (slot >= btrfs_header_nritems(leaf)) {
2386                         ret = btrfs_next_leaf(root, path);
2387                         if (ret < 0) {
2388                                 goto out;
2389                         } else if (ret > 0) {
2390                                 ret = 0;
2391                                 goto out;
2392                         }
2393                         continue;
2394                 }
2395
2396                 path->slots[0]++;
2397
2398                 btrfs_item_key_to_cpu(leaf, &key, slot);
2399
2400                 if (key.objectid > inum)
2401                         goto out;
2402
2403                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2404                         continue;
2405
2406                 extent = btrfs_item_ptr(leaf, slot,
2407                                         struct btrfs_file_extent_item);
2408
2409                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2410                         continue;
2411
2412                 /*
2413                  * 'offset' refers to the exact key.offset,
2414                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2415                  * (key.offset - extent_offset).
2416                  */
2417                 if (key.offset != offset)
2418                         continue;
2419
2420                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2421                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2422
2423                 if (extent_offset >= old->extent_offset + old->offset +
2424                     old->len || extent_offset + num_bytes <=
2425                     old->extent_offset + old->offset)
2426                         continue;
2427                 break;
2428         }
2429
2430         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2431         if (!backref) {
2432                 ret = -ENOENT;
2433                 goto out;
2434         }
2435
2436         backref->root_id = root_id;
2437         backref->inum = inum;
2438         backref->file_pos = offset;
2439         backref->num_bytes = num_bytes;
2440         backref->extent_offset = extent_offset;
2441         backref->generation = btrfs_file_extent_generation(leaf, extent);
2442         backref->old = old;
2443         backref_insert(&new->root, backref);
2444         old->count++;
2445 out:
2446         btrfs_release_path(path);
2447         WARN_ON(ret);
2448         return ret;
2449 }
2450
2451 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2452                                    struct new_sa_defrag_extent *new)
2453 {
2454         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2455         struct old_sa_defrag_extent *old, *tmp;
2456         int ret;
2457
2458         new->path = path;
2459
2460         list_for_each_entry_safe(old, tmp, &new->head, list) {
2461                 ret = iterate_inodes_from_logical(old->bytenr +
2462                                                   old->extent_offset, fs_info,
2463                                                   path, record_one_backref,
2464                                                   old, false);
2465                 if (ret < 0 && ret != -ENOENT)
2466                         return false;
2467
2468                 /* no backref to be processed for this extent */
2469                 if (!old->count) {
2470                         list_del(&old->list);
2471                         kfree(old);
2472                 }
2473         }
2474
2475         if (list_empty(&new->head))
2476                 return false;
2477
2478         return true;
2479 }
2480
2481 static int relink_is_mergable(struct extent_buffer *leaf,
2482                               struct btrfs_file_extent_item *fi,
2483                               struct new_sa_defrag_extent *new)
2484 {
2485         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2486                 return 0;
2487
2488         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2489                 return 0;
2490
2491         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2492                 return 0;
2493
2494         if (btrfs_file_extent_encryption(leaf, fi) ||
2495             btrfs_file_extent_other_encoding(leaf, fi))
2496                 return 0;
2497
2498         return 1;
2499 }
2500
2501 /*
2502  * Note the backref might has changed, and in this case we just return 0.
2503  */
2504 static noinline int relink_extent_backref(struct btrfs_path *path,
2505                                  struct sa_defrag_extent_backref *prev,
2506                                  struct sa_defrag_extent_backref *backref)
2507 {
2508         struct btrfs_file_extent_item *extent;
2509         struct btrfs_file_extent_item *item;
2510         struct btrfs_ordered_extent *ordered;
2511         struct btrfs_trans_handle *trans;
2512         struct btrfs_root *root;
2513         struct btrfs_key key;
2514         struct extent_buffer *leaf;
2515         struct old_sa_defrag_extent *old = backref->old;
2516         struct new_sa_defrag_extent *new = old->new;
2517         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2518         struct inode *inode;
2519         struct extent_state *cached = NULL;
2520         int ret = 0;
2521         u64 start;
2522         u64 len;
2523         u64 lock_start;
2524         u64 lock_end;
2525         bool merge = false;
2526         int index;
2527
2528         if (prev && prev->root_id == backref->root_id &&
2529             prev->inum == backref->inum &&
2530             prev->file_pos + prev->num_bytes == backref->file_pos)
2531                 merge = true;
2532
2533         /* step 1: get root */
2534         key.objectid = backref->root_id;
2535         key.type = BTRFS_ROOT_ITEM_KEY;
2536         key.offset = (u64)-1;
2537
2538         index = srcu_read_lock(&fs_info->subvol_srcu);
2539
2540         root = btrfs_read_fs_root_no_name(fs_info, &key);
2541         if (IS_ERR(root)) {
2542                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2543                 if (PTR_ERR(root) == -ENOENT)
2544                         return 0;
2545                 return PTR_ERR(root);
2546         }
2547
2548         if (btrfs_root_readonly(root)) {
2549                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2550                 return 0;
2551         }
2552
2553         /* step 2: get inode */
2554         key.objectid = backref->inum;
2555         key.type = BTRFS_INODE_ITEM_KEY;
2556         key.offset = 0;
2557
2558         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2559         if (IS_ERR(inode)) {
2560                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2561                 return 0;
2562         }
2563
2564         srcu_read_unlock(&fs_info->subvol_srcu, index);
2565
2566         /* step 3: relink backref */
2567         lock_start = backref->file_pos;
2568         lock_end = backref->file_pos + backref->num_bytes - 1;
2569         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2570                          &cached);
2571
2572         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2573         if (ordered) {
2574                 btrfs_put_ordered_extent(ordered);
2575                 goto out_unlock;
2576         }
2577
2578         trans = btrfs_join_transaction(root);
2579         if (IS_ERR(trans)) {
2580                 ret = PTR_ERR(trans);
2581                 goto out_unlock;
2582         }
2583
2584         key.objectid = backref->inum;
2585         key.type = BTRFS_EXTENT_DATA_KEY;
2586         key.offset = backref->file_pos;
2587
2588         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2589         if (ret < 0) {
2590                 goto out_free_path;
2591         } else if (ret > 0) {
2592                 ret = 0;
2593                 goto out_free_path;
2594         }
2595
2596         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2597                                 struct btrfs_file_extent_item);
2598
2599         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2600             backref->generation)
2601                 goto out_free_path;
2602
2603         btrfs_release_path(path);
2604
2605         start = backref->file_pos;
2606         if (backref->extent_offset < old->extent_offset + old->offset)
2607                 start += old->extent_offset + old->offset -
2608                          backref->extent_offset;
2609
2610         len = min(backref->extent_offset + backref->num_bytes,
2611                   old->extent_offset + old->offset + old->len);
2612         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2613
2614         ret = btrfs_drop_extents(trans, root, inode, start,
2615                                  start + len, 1);
2616         if (ret)
2617                 goto out_free_path;
2618 again:
2619         key.objectid = btrfs_ino(BTRFS_I(inode));
2620         key.type = BTRFS_EXTENT_DATA_KEY;
2621         key.offset = start;
2622
2623         path->leave_spinning = 1;
2624         if (merge) {
2625                 struct btrfs_file_extent_item *fi;
2626                 u64 extent_len;
2627                 struct btrfs_key found_key;
2628
2629                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2630                 if (ret < 0)
2631                         goto out_free_path;
2632
2633                 path->slots[0]--;
2634                 leaf = path->nodes[0];
2635                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2636
2637                 fi = btrfs_item_ptr(leaf, path->slots[0],
2638                                     struct btrfs_file_extent_item);
2639                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2640
2641                 if (extent_len + found_key.offset == start &&
2642                     relink_is_mergable(leaf, fi, new)) {
2643                         btrfs_set_file_extent_num_bytes(leaf, fi,
2644                                                         extent_len + len);
2645                         btrfs_mark_buffer_dirty(leaf);
2646                         inode_add_bytes(inode, len);
2647
2648                         ret = 1;
2649                         goto out_free_path;
2650                 } else {
2651                         merge = false;
2652                         btrfs_release_path(path);
2653                         goto again;
2654                 }
2655         }
2656
2657         ret = btrfs_insert_empty_item(trans, root, path, &key,
2658                                         sizeof(*extent));
2659         if (ret) {
2660                 btrfs_abort_transaction(trans, ret);
2661                 goto out_free_path;
2662         }
2663
2664         leaf = path->nodes[0];
2665         item = btrfs_item_ptr(leaf, path->slots[0],
2666                                 struct btrfs_file_extent_item);
2667         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2668         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2669         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2670         btrfs_set_file_extent_num_bytes(leaf, item, len);
2671         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2672         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2673         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2674         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2675         btrfs_set_file_extent_encryption(leaf, item, 0);
2676         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2677
2678         btrfs_mark_buffer_dirty(leaf);
2679         inode_add_bytes(inode, len);
2680         btrfs_release_path(path);
2681
2682         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2683                         new->disk_len, 0,
2684                         backref->root_id, backref->inum,
2685                         new->file_pos); /* start - extent_offset */
2686         if (ret) {
2687                 btrfs_abort_transaction(trans, ret);
2688                 goto out_free_path;
2689         }
2690
2691         ret = 1;
2692 out_free_path:
2693         btrfs_release_path(path);
2694         path->leave_spinning = 0;
2695         btrfs_end_transaction(trans);
2696 out_unlock:
2697         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2698                              &cached);
2699         iput(inode);
2700         return ret;
2701 }
2702
2703 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2704 {
2705         struct old_sa_defrag_extent *old, *tmp;
2706
2707         if (!new)
2708                 return;
2709
2710         list_for_each_entry_safe(old, tmp, &new->head, list) {
2711                 kfree(old);
2712         }
2713         kfree(new);
2714 }
2715
2716 static void relink_file_extents(struct new_sa_defrag_extent *new)
2717 {
2718         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2719         struct btrfs_path *path;
2720         struct sa_defrag_extent_backref *backref;
2721         struct sa_defrag_extent_backref *prev = NULL;
2722         struct rb_node *node;
2723         int ret;
2724
2725         path = btrfs_alloc_path();
2726         if (!path)
2727                 return;
2728
2729         if (!record_extent_backrefs(path, new)) {
2730                 btrfs_free_path(path);
2731                 goto out;
2732         }
2733         btrfs_release_path(path);
2734
2735         while (1) {
2736                 node = rb_first(&new->root);
2737                 if (!node)
2738                         break;
2739                 rb_erase(node, &new->root);
2740
2741                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2742
2743                 ret = relink_extent_backref(path, prev, backref);
2744                 WARN_ON(ret < 0);
2745
2746                 kfree(prev);
2747
2748                 if (ret == 1)
2749                         prev = backref;
2750                 else
2751                         prev = NULL;
2752                 cond_resched();
2753         }
2754         kfree(prev);
2755
2756         btrfs_free_path(path);
2757 out:
2758         free_sa_defrag_extent(new);
2759
2760         atomic_dec(&fs_info->defrag_running);
2761         wake_up(&fs_info->transaction_wait);
2762 }
2763
2764 static struct new_sa_defrag_extent *
2765 record_old_file_extents(struct inode *inode,
2766                         struct btrfs_ordered_extent *ordered)
2767 {
2768         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2769         struct btrfs_root *root = BTRFS_I(inode)->root;
2770         struct btrfs_path *path;
2771         struct btrfs_key key;
2772         struct old_sa_defrag_extent *old;
2773         struct new_sa_defrag_extent *new;
2774         int ret;
2775
2776         new = kmalloc(sizeof(*new), GFP_NOFS);
2777         if (!new)
2778                 return NULL;
2779
2780         new->inode = inode;
2781         new->file_pos = ordered->file_offset;
2782         new->len = ordered->len;
2783         new->bytenr = ordered->start;
2784         new->disk_len = ordered->disk_len;
2785         new->compress_type = ordered->compress_type;
2786         new->root = RB_ROOT;
2787         INIT_LIST_HEAD(&new->head);
2788
2789         path = btrfs_alloc_path();
2790         if (!path)
2791                 goto out_kfree;
2792
2793         key.objectid = btrfs_ino(BTRFS_I(inode));
2794         key.type = BTRFS_EXTENT_DATA_KEY;
2795         key.offset = new->file_pos;
2796
2797         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2798         if (ret < 0)
2799                 goto out_free_path;
2800         if (ret > 0 && path->slots[0] > 0)
2801                 path->slots[0]--;
2802
2803         /* find out all the old extents for the file range */
2804         while (1) {
2805                 struct btrfs_file_extent_item *extent;
2806                 struct extent_buffer *l;
2807                 int slot;
2808                 u64 num_bytes;
2809                 u64 offset;
2810                 u64 end;
2811                 u64 disk_bytenr;
2812                 u64 extent_offset;
2813
2814                 l = path->nodes[0];
2815                 slot = path->slots[0];
2816
2817                 if (slot >= btrfs_header_nritems(l)) {
2818                         ret = btrfs_next_leaf(root, path);
2819                         if (ret < 0)
2820                                 goto out_free_path;
2821                         else if (ret > 0)
2822                                 break;
2823                         continue;
2824                 }
2825
2826                 btrfs_item_key_to_cpu(l, &key, slot);
2827
2828                 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2829                         break;
2830                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2831                         break;
2832                 if (key.offset >= new->file_pos + new->len)
2833                         break;
2834
2835                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2836
2837                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2838                 if (key.offset + num_bytes < new->file_pos)
2839                         goto next;
2840
2841                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2842                 if (!disk_bytenr)
2843                         goto next;
2844
2845                 extent_offset = btrfs_file_extent_offset(l, extent);
2846
2847                 old = kmalloc(sizeof(*old), GFP_NOFS);
2848                 if (!old)
2849                         goto out_free_path;
2850
2851                 offset = max(new->file_pos, key.offset);
2852                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2853
2854                 old->bytenr = disk_bytenr;
2855                 old->extent_offset = extent_offset;
2856                 old->offset = offset - key.offset;
2857                 old->len = end - offset;
2858                 old->new = new;
2859                 old->count = 0;
2860                 list_add_tail(&old->list, &new->head);
2861 next:
2862                 path->slots[0]++;
2863                 cond_resched();
2864         }
2865
2866         btrfs_free_path(path);
2867         atomic_inc(&fs_info->defrag_running);
2868
2869         return new;
2870
2871 out_free_path:
2872         btrfs_free_path(path);
2873 out_kfree:
2874         free_sa_defrag_extent(new);
2875         return NULL;
2876 }
2877
2878 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2879                                          u64 start, u64 len)
2880 {
2881         struct btrfs_block_group_cache *cache;
2882
2883         cache = btrfs_lookup_block_group(fs_info, start);
2884         ASSERT(cache);
2885
2886         spin_lock(&cache->lock);
2887         cache->delalloc_bytes -= len;
2888         spin_unlock(&cache->lock);
2889
2890         btrfs_put_block_group(cache);
2891 }
2892
2893 /* as ordered data IO finishes, this gets called so we can finish
2894  * an ordered extent if the range of bytes in the file it covers are
2895  * fully written.
2896  */
2897 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2898 {
2899         struct inode *inode = ordered_extent->inode;
2900         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2901         struct btrfs_root *root = BTRFS_I(inode)->root;
2902         struct btrfs_trans_handle *trans = NULL;
2903         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2904         struct extent_state *cached_state = NULL;
2905         struct new_sa_defrag_extent *new = NULL;
2906         int compress_type = 0;
2907         int ret = 0;
2908         u64 logical_len = ordered_extent->len;
2909         bool nolock;
2910         bool truncated = false;
2911         bool range_locked = false;
2912         bool clear_new_delalloc_bytes = false;
2913         bool clear_reserved_extent = true;
2914
2915         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2916             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2917             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2918                 clear_new_delalloc_bytes = true;
2919
2920         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2921
2922         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2923                 ret = -EIO;
2924                 goto out;
2925         }
2926
2927         btrfs_free_io_failure_record(BTRFS_I(inode),
2928                         ordered_extent->file_offset,
2929                         ordered_extent->file_offset +
2930                         ordered_extent->len - 1);
2931
2932         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2933                 truncated = true;
2934                 logical_len = ordered_extent->truncated_len;
2935                 /* Truncated the entire extent, don't bother adding */
2936                 if (!logical_len)
2937                         goto out;
2938         }
2939
2940         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2941                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2942
2943                 /*
2944                  * For mwrite(mmap + memset to write) case, we still reserve
2945                  * space for NOCOW range.
2946                  * As NOCOW won't cause a new delayed ref, just free the space
2947                  */
2948                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2949                                        ordered_extent->len);
2950                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2951                 if (nolock)
2952                         trans = btrfs_join_transaction_nolock(root);
2953                 else
2954                         trans = btrfs_join_transaction(root);
2955                 if (IS_ERR(trans)) {
2956                         ret = PTR_ERR(trans);
2957                         trans = NULL;
2958                         goto out;
2959                 }
2960                 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2961                 ret = btrfs_update_inode_fallback(trans, root, inode);
2962                 if (ret) /* -ENOMEM or corruption */
2963                         btrfs_abort_transaction(trans, ret);
2964                 goto out;
2965         }
2966
2967         range_locked = true;
2968         lock_extent_bits(io_tree, ordered_extent->file_offset,
2969                          ordered_extent->file_offset + ordered_extent->len - 1,
2970                          &cached_state);
2971
2972         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2973                         ordered_extent->file_offset + ordered_extent->len - 1,
2974                         EXTENT_DEFRAG, 0, cached_state);
2975         if (ret) {
2976                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2977                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2978                         /* the inode is shared */
2979                         new = record_old_file_extents(inode, ordered_extent);
2980
2981                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2982                         ordered_extent->file_offset + ordered_extent->len - 1,
2983                         EXTENT_DEFRAG, 0, 0, &cached_state);
2984         }
2985
2986         if (nolock)
2987                 trans = btrfs_join_transaction_nolock(root);
2988         else
2989                 trans = btrfs_join_transaction(root);
2990         if (IS_ERR(trans)) {
2991                 ret = PTR_ERR(trans);
2992                 trans = NULL;
2993                 goto out;
2994         }
2995
2996         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2997
2998         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2999                 compress_type = ordered_extent->compress_type;
3000         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3001                 BUG_ON(compress_type);
3002                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3003                                        ordered_extent->len);
3004                 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3005                                                 ordered_extent->file_offset,
3006                                                 ordered_extent->file_offset +
3007                                                 logical_len);
3008         } else {
3009                 BUG_ON(root == fs_info->tree_root);
3010                 ret = insert_reserved_file_extent(trans, inode,
3011                                                 ordered_extent->file_offset,
3012                                                 ordered_extent->start,
3013                                                 ordered_extent->disk_len,
3014                                                 logical_len, logical_len,
3015                                                 compress_type, 0, 0,
3016                                                 BTRFS_FILE_EXTENT_REG);
3017                 if (!ret) {
3018                         clear_reserved_extent = false;
3019                         btrfs_release_delalloc_bytes(fs_info,
3020                                                      ordered_extent->start,
3021                                                      ordered_extent->disk_len);
3022                 }
3023         }
3024         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3025                            ordered_extent->file_offset, ordered_extent->len,
3026                            trans->transid);
3027         if (ret < 0) {
3028                 btrfs_abort_transaction(trans, ret);
3029                 goto out;
3030         }
3031
3032         ret = add_pending_csums(trans, inode, &ordered_extent->list);
3033         if (ret) {
3034                 btrfs_abort_transaction(trans, ret);
3035                 goto out;
3036         }
3037
3038         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3039         ret = btrfs_update_inode_fallback(trans, root, inode);
3040         if (ret) { /* -ENOMEM or corruption */
3041                 btrfs_abort_transaction(trans, ret);
3042                 goto out;
3043         }
3044         ret = 0;
3045 out:
3046         if (range_locked || clear_new_delalloc_bytes) {
3047                 unsigned int clear_bits = 0;
3048
3049                 if (range_locked)
3050                         clear_bits |= EXTENT_LOCKED;
3051                 if (clear_new_delalloc_bytes)
3052                         clear_bits |= EXTENT_DELALLOC_NEW;
3053                 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3054                                  ordered_extent->file_offset,
3055                                  ordered_extent->file_offset +
3056                                  ordered_extent->len - 1,
3057                                  clear_bits,
3058                                  (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3059                                  0, &cached_state);
3060         }
3061
3062         if (trans)
3063                 btrfs_end_transaction(trans);
3064
3065         if (ret || truncated) {
3066                 u64 start, end;
3067
3068                 if (truncated)
3069                         start = ordered_extent->file_offset + logical_len;
3070                 else
3071                         start = ordered_extent->file_offset;
3072                 end = ordered_extent->file_offset + ordered_extent->len - 1;
3073                 clear_extent_uptodate(io_tree, start, end, NULL);
3074
3075                 /* Drop the cache for the part of the extent we didn't write. */
3076                 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3077
3078                 /*
3079                  * If the ordered extent had an IOERR or something else went
3080                  * wrong we need to return the space for this ordered extent
3081                  * back to the allocator.  We only free the extent in the
3082                  * truncated case if we didn't write out the extent at all.
3083                  *
3084                  * If we made it past insert_reserved_file_extent before we
3085                  * errored out then we don't need to do this as the accounting
3086                  * has already been done.
3087                  */
3088                 if ((ret || !logical_len) &&
3089                     clear_reserved_extent &&
3090                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3091                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3092                         btrfs_free_reserved_extent(fs_info,
3093                                                    ordered_extent->start,
3094                                                    ordered_extent->disk_len, 1);
3095         }
3096
3097
3098         /*
3099          * This needs to be done to make sure anybody waiting knows we are done
3100          * updating everything for this ordered extent.
3101          */
3102         btrfs_remove_ordered_extent(inode, ordered_extent);
3103
3104         /* for snapshot-aware defrag */
3105         if (new) {
3106                 if (ret) {
3107                         free_sa_defrag_extent(new);
3108                         atomic_dec(&fs_info->defrag_running);
3109                 } else {
3110                         relink_file_extents(new);
3111                 }
3112         }
3113
3114         /* once for us */
3115         btrfs_put_ordered_extent(ordered_extent);
3116         /* once for the tree */
3117         btrfs_put_ordered_extent(ordered_extent);
3118
3119         /* Try to release some metadata so we don't get an OOM but don't wait */
3120         btrfs_btree_balance_dirty_nodelay(fs_info);
3121
3122         return ret;
3123 }
3124
3125 static void finish_ordered_fn(struct btrfs_work *work)
3126 {
3127         struct btrfs_ordered_extent *ordered_extent;
3128         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3129         btrfs_finish_ordered_io(ordered_extent);
3130 }
3131
3132 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3133                                           u64 end, int uptodate)
3134 {
3135         struct inode *inode = page->mapping->host;
3136         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3137         struct btrfs_ordered_extent *ordered_extent = NULL;
3138         struct btrfs_workqueue *wq;
3139         btrfs_work_func_t func;
3140
3141         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3142
3143         ClearPagePrivate2(page);
3144         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3145                                             end - start + 1, uptodate))
3146                 return;
3147
3148         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3149                 wq = fs_info->endio_freespace_worker;
3150                 func = btrfs_freespace_write_helper;
3151         } else {
3152                 wq = fs_info->endio_write_workers;
3153                 func = btrfs_endio_write_helper;
3154         }
3155
3156         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3157                         NULL);
3158         btrfs_queue_work(wq, &ordered_extent->work);
3159 }
3160
3161 static int __readpage_endio_check(struct inode *inode,
3162                                   struct btrfs_io_bio *io_bio,
3163                                   int icsum, struct page *page,
3164                                   int pgoff, u64 start, size_t len)
3165 {
3166         char *kaddr;
3167         u32 csum_expected;
3168         u32 csum = ~(u32)0;
3169
3170         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3171
3172         kaddr = kmap_atomic(page);
3173         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3174         btrfs_csum_final(csum, (u8 *)&csum);
3175         if (csum != csum_expected)
3176                 goto zeroit;
3177
3178         kunmap_atomic(kaddr);
3179         return 0;
3180 zeroit:
3181         btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3182                                     io_bio->mirror_num);
3183         memset(kaddr + pgoff, 1, len);
3184         flush_dcache_page(page);
3185         kunmap_atomic(kaddr);
3186         return -EIO;
3187 }
3188
3189 /*
3190  * when reads are done, we need to check csums to verify the data is correct
3191  * if there's a match, we allow the bio to finish.  If not, the code in
3192  * extent_io.c will try to find good copies for us.
3193  */
3194 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3195                                       u64 phy_offset, struct page *page,
3196                                       u64 start, u64 end, int mirror)
3197 {
3198         size_t offset = start - page_offset(page);
3199         struct inode *inode = page->mapping->host;
3200         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3201         struct btrfs_root *root = BTRFS_I(inode)->root;
3202
3203         if (PageChecked(page)) {
3204                 ClearPageChecked(page);
3205                 return 0;
3206         }
3207
3208         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3209                 return 0;
3210
3211         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3212             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3213                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3214                 return 0;
3215         }
3216
3217         phy_offset >>= inode->i_sb->s_blocksize_bits;
3218         return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3219                                       start, (size_t)(end - start + 1));
3220 }
3221
3222 /*
3223  * btrfs_add_delayed_iput - perform a delayed iput on @inode
3224  *
3225  * @inode: The inode we want to perform iput on
3226  *
3227  * This function uses the generic vfs_inode::i_count to track whether we should
3228  * just decrement it (in case it's > 1) or if this is the last iput then link
3229  * the inode to the delayed iput machinery. Delayed iputs are processed at
3230  * transaction commit time/superblock commit/cleaner kthread.
3231  */
3232 void btrfs_add_delayed_iput(struct inode *inode)
3233 {
3234         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3235         struct btrfs_inode *binode = BTRFS_I(inode);
3236
3237         if (atomic_add_unless(&inode->i_count, -1, 1))
3238                 return;
3239
3240         spin_lock(&fs_info->delayed_iput_lock);
3241         ASSERT(list_empty(&binode->delayed_iput));
3242         list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3243         spin_unlock(&fs_info->delayed_iput_lock);
3244 }
3245
3246 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3247 {
3248
3249         spin_lock(&fs_info->delayed_iput_lock);
3250         while (!list_empty(&fs_info->delayed_iputs)) {
3251                 struct btrfs_inode *inode;
3252
3253                 inode = list_first_entry(&fs_info->delayed_iputs,
3254                                 struct btrfs_inode, delayed_iput);
3255                 list_del_init(&inode->delayed_iput);
3256                 spin_unlock(&fs_info->delayed_iput_lock);
3257                 iput(&inode->vfs_inode);
3258                 spin_lock(&fs_info->delayed_iput_lock);
3259         }
3260         spin_unlock(&fs_info->delayed_iput_lock);
3261 }
3262
3263 /*
3264  * This creates an orphan entry for the given inode in case something goes wrong
3265  * in the middle of an unlink.
3266  */
3267 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3268                      struct btrfs_inode *inode)
3269 {
3270         int ret;
3271
3272         ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3273         if (ret && ret != -EEXIST) {
3274                 btrfs_abort_transaction(trans, ret);
3275                 return ret;
3276         }
3277
3278         return 0;
3279 }
3280
3281 /*
3282  * We have done the delete so we can go ahead and remove the orphan item for
3283  * this particular inode.
3284  */
3285 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3286                             struct btrfs_inode *inode)
3287 {
3288         return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3289 }
3290
3291 /*
3292  * this cleans up any orphans that may be left on the list from the last use
3293  * of this root.
3294  */
3295 int btrfs_orphan_cleanup(struct btrfs_root *root)
3296 {
3297         struct btrfs_fs_info *fs_info = root->fs_info;
3298         struct btrfs_path *path;
3299         struct extent_buffer *leaf;
3300         struct btrfs_key key, found_key;
3301         struct btrfs_trans_handle *trans;
3302         struct inode *inode;
3303         u64 last_objectid = 0;
3304         int ret = 0, nr_unlink = 0;
3305
3306         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3307                 return 0;
3308
3309         path = btrfs_alloc_path();
3310         if (!path) {
3311                 ret = -ENOMEM;
3312                 goto out;
3313         }
3314         path->reada = READA_BACK;
3315
3316         key.objectid = BTRFS_ORPHAN_OBJECTID;
3317         key.type = BTRFS_ORPHAN_ITEM_KEY;
3318         key.offset = (u64)-1;
3319
3320         while (1) {
3321                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3322                 if (ret < 0)
3323                         goto out;
3324
3325                 /*
3326                  * if ret == 0 means we found what we were searching for, which
3327                  * is weird, but possible, so only screw with path if we didn't
3328                  * find the key and see if we have stuff that matches
3329                  */
3330                 if (ret > 0) {
3331                         ret = 0;
3332                         if (path->slots[0] == 0)
3333                                 break;
3334                         path->slots[0]--;
3335                 }
3336
3337                 /* pull out the item */
3338                 leaf = path->nodes[0];
3339                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3340
3341                 /* make sure the item matches what we want */
3342                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3343                         break;
3344                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3345                         break;
3346
3347                 /* release the path since we're done with it */
3348                 btrfs_release_path(path);
3349
3350                 /*
3351                  * this is where we are basically btrfs_lookup, without the
3352                  * crossing root thing.  we store the inode number in the
3353                  * offset of the orphan item.
3354                  */
3355
3356                 if (found_key.offset == last_objectid) {
3357                         btrfs_err(fs_info,
3358                                   "Error removing orphan entry, stopping orphan cleanup");
3359                         ret = -EINVAL;
3360                         goto out;
3361                 }
3362
3363                 last_objectid = found_key.offset;
3364
3365                 found_key.objectid = found_key.offset;
3366                 found_key.type = BTRFS_INODE_ITEM_KEY;
3367                 found_key.offset = 0;
3368                 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3369                 ret = PTR_ERR_OR_ZERO(inode);
3370                 if (ret && ret != -ENOENT)
3371                         goto out;
3372
3373                 if (ret == -ENOENT && root == fs_info->tree_root) {
3374                         struct btrfs_root *dead_root;
3375                         struct btrfs_fs_info *fs_info = root->fs_info;
3376                         int is_dead_root = 0;
3377
3378                         /*
3379                          * this is an orphan in the tree root. Currently these
3380                          * could come from 2 sources:
3381                          *  a) a snapshot deletion in progress
3382                          *  b) a free space cache inode
3383                          * We need to distinguish those two, as the snapshot
3384                          * orphan must not get deleted.
3385                          * find_dead_roots already ran before us, so if this
3386                          * is a snapshot deletion, we should find the root
3387                          * in the dead_roots list
3388                          */
3389                         spin_lock(&fs_info->trans_lock);
3390                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3391                                             root_list) {
3392                                 if (dead_root->root_key.objectid ==
3393                                     found_key.objectid) {
3394                                         is_dead_root = 1;
3395                                         break;
3396                                 }
3397                         }
3398                         spin_unlock(&fs_info->trans_lock);
3399                         if (is_dead_root) {
3400                                 /* prevent this orphan from being found again */
3401                                 key.offset = found_key.objectid - 1;
3402                                 continue;
3403                         }
3404
3405                 }
3406
3407                 /*
3408                  * If we have an inode with links, there are a couple of
3409                  * possibilities. Old kernels (before v3.12) used to create an
3410                  * orphan item for truncate indicating that there were possibly
3411                  * extent items past i_size that needed to be deleted. In v3.12,
3412                  * truncate was changed to update i_size in sync with the extent
3413                  * items, but the (useless) orphan item was still created. Since
3414                  * v4.18, we don't create the orphan item for truncate at all.
3415                  *
3416                  * So, this item could mean that we need to do a truncate, but
3417                  * only if this filesystem was last used on a pre-v3.12 kernel
3418                  * and was not cleanly unmounted. The odds of that are quite
3419                  * slim, and it's a pain to do the truncate now, so just delete
3420                  * the orphan item.
3421                  *
3422                  * It's also possible that this orphan item was supposed to be
3423                  * deleted but wasn't. The inode number may have been reused,
3424                  * but either way, we can delete the orphan item.
3425                  */
3426                 if (ret == -ENOENT || inode->i_nlink) {
3427                         if (!ret)
3428                                 iput(inode);
3429                         trans = btrfs_start_transaction(root, 1);
3430                         if (IS_ERR(trans)) {
3431                                 ret = PTR_ERR(trans);
3432                                 goto out;
3433                         }
3434                         btrfs_debug(fs_info, "auto deleting %Lu",
3435                                     found_key.objectid);
3436                         ret = btrfs_del_orphan_item(trans, root,
3437                                                     found_key.objectid);
3438                         btrfs_end_transaction(trans);
3439                         if (ret)
3440                                 goto out;
3441                         continue;
3442                 }
3443
3444                 nr_unlink++;
3445
3446                 /* this will do delete_inode and everything for us */
3447                 iput(inode);
3448         }
3449         /* release the path since we're done with it */
3450         btrfs_release_path(path);
3451
3452         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3453
3454         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3455                 trans = btrfs_join_transaction(root);
3456                 if (!IS_ERR(trans))
3457                         btrfs_end_transaction(trans);
3458         }
3459
3460         if (nr_unlink)
3461                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3462
3463 out:
3464         if (ret)
3465                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3466         btrfs_free_path(path);
3467         return ret;
3468 }
3469
3470 /*
3471  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3472  * don't find any xattrs, we know there can't be any acls.
3473  *
3474  * slot is the slot the inode is in, objectid is the objectid of the inode
3475  */
3476 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3477                                           int slot, u64 objectid,
3478                                           int *first_xattr_slot)
3479 {
3480         u32 nritems = btrfs_header_nritems(leaf);
3481         struct btrfs_key found_key;
3482         static u64 xattr_access = 0;
3483         static u64 xattr_default = 0;
3484         int scanned = 0;
3485
3486         if (!xattr_access) {
3487                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3488                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3489                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3490                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3491         }
3492
3493         slot++;
3494         *first_xattr_slot = -1;
3495         while (slot < nritems) {
3496                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3497
3498                 /* we found a different objectid, there must not be acls */
3499                 if (found_key.objectid != objectid)
3500                         return 0;
3501
3502                 /* we found an xattr, assume we've got an acl */
3503                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3504                         if (*first_xattr_slot == -1)
3505                                 *first_xattr_slot = slot;
3506                         if (found_key.offset == xattr_access ||
3507                             found_key.offset == xattr_default)
3508                                 return 1;
3509                 }
3510
3511                 /*
3512                  * we found a key greater than an xattr key, there can't
3513                  * be any acls later on
3514                  */
3515                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3516                         return 0;
3517
3518                 slot++;
3519                 scanned++;
3520
3521                 /*
3522                  * it goes inode, inode backrefs, xattrs, extents,
3523                  * so if there are a ton of hard links to an inode there can
3524                  * be a lot of backrefs.  Don't waste time searching too hard,
3525                  * this is just an optimization
3526                  */
3527                 if (scanned >= 8)
3528                         break;
3529         }
3530         /* we hit the end of the leaf before we found an xattr or
3531          * something larger than an xattr.  We have to assume the inode
3532          * has acls
3533          */