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