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