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