btrfs: open-code bio_set_op_attrs
[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 address_space_operations btrfs_symlink_aops;
68 static const struct file_operations btrfs_dir_file_operations;
69 static const struct extent_io_ops btrfs_extent_io_ops;
70
71 static struct kmem_cache *btrfs_inode_cachep;
72 struct kmem_cache *btrfs_trans_handle_cachep;
73 struct kmem_cache *btrfs_path_cachep;
74 struct kmem_cache *btrfs_free_space_cachep;
75
76 #define S_SHIFT 12
77 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
78         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
79         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
80         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
81         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
82         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
83         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
84         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
85 };
86
87 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
88 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
89 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
90 static noinline int cow_file_range(struct inode *inode,
91                                    struct page *locked_page,
92                                    u64 start, u64 end, u64 delalloc_end,
93                                    int *page_started, unsigned long *nr_written,
94                                    int unlock, struct btrfs_dedupe_hash *hash);
95 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
96                                        u64 orig_start, u64 block_start,
97                                        u64 block_len, u64 orig_block_len,
98                                        u64 ram_bytes, int compress_type,
99                                        int type);
100
101 static void __endio_write_update_ordered(struct inode *inode,
102                                          const u64 offset, const u64 bytes,
103                                          const bool uptodate);
104
105 /*
106  * Cleanup all submitted ordered extents in specified range to handle errors
107  * from the fill_dellaloc() callback.
108  *
109  * NOTE: caller must ensure that when an error happens, it can not call
110  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
111  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
112  * to be released, which we want to happen only when finishing the ordered
113  * extent (btrfs_finish_ordered_io()). Also note that the caller of the
114  * fill_delalloc() callback already does proper cleanup for the first page of
115  * the range, that is, it invokes the callback writepage_end_io_hook() for the
116  * range of the first page.
117  */
118 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
119                                                  const u64 offset,
120                                                  const u64 bytes)
121 {
122         unsigned long index = offset >> PAGE_SHIFT;
123         unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
124         struct page *page;
125
126         while (index <= end_index) {
127                 page = find_get_page(inode->i_mapping, index);
128                 index++;
129                 if (!page)
130                         continue;
131                 ClearPagePrivate2(page);
132                 put_page(page);
133         }
134         return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
135                                             bytes - PAGE_SIZE, false);
136 }
137
138 static int btrfs_dirty_inode(struct inode *inode);
139
140 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
141 void btrfs_test_inode_set_ops(struct inode *inode)
142 {
143         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
144 }
145 #endif
146
147 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
148                                      struct inode *inode,  struct inode *dir,
149                                      const struct qstr *qstr)
150 {
151         int err;
152
153         err = btrfs_init_acl(trans, inode, dir);
154         if (!err)
155                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
156         return err;
157 }
158
159 /*
160  * this does all the hard work for inserting an inline extent into
161  * the btree.  The caller should have done a btrfs_drop_extents so that
162  * no overlapping inline items exist in the btree
163  */
164 static int insert_inline_extent(struct btrfs_trans_handle *trans,
165                                 struct btrfs_path *path, int extent_inserted,
166                                 struct btrfs_root *root, struct inode *inode,
167                                 u64 start, size_t size, size_t compressed_size,
168                                 int compress_type,
169                                 struct page **compressed_pages)
170 {
171         struct extent_buffer *leaf;
172         struct page *page = NULL;
173         char *kaddr;
174         unsigned long ptr;
175         struct btrfs_file_extent_item *ei;
176         int ret;
177         size_t cur_size = size;
178         unsigned long offset;
179
180         if (compressed_size && compressed_pages)
181                 cur_size = compressed_size;
182
183         inode_add_bytes(inode, size);
184
185         if (!extent_inserted) {
186                 struct btrfs_key key;
187                 size_t datasize;
188
189                 key.objectid = btrfs_ino(BTRFS_I(inode));
190                 key.offset = start;
191                 key.type = BTRFS_EXTENT_DATA_KEY;
192
193                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
194                 path->leave_spinning = 1;
195                 ret = btrfs_insert_empty_item(trans, root, path, &key,
196                                               datasize);
197                 if (ret)
198                         goto fail;
199         }
200         leaf = path->nodes[0];
201         ei = btrfs_item_ptr(leaf, path->slots[0],
202                             struct btrfs_file_extent_item);
203         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
204         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
205         btrfs_set_file_extent_encryption(leaf, ei, 0);
206         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
207         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
208         ptr = btrfs_file_extent_inline_start(ei);
209
210         if (compress_type != BTRFS_COMPRESS_NONE) {
211                 struct page *cpage;
212                 int i = 0;
213                 while (compressed_size > 0) {
214                         cpage = compressed_pages[i];
215                         cur_size = min_t(unsigned long, compressed_size,
216                                        PAGE_SIZE);
217
218                         kaddr = kmap_atomic(cpage);
219                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
220                         kunmap_atomic(kaddr);
221
222                         i++;
223                         ptr += cur_size;
224                         compressed_size -= cur_size;
225                 }
226                 btrfs_set_file_extent_compression(leaf, ei,
227                                                   compress_type);
228         } else {
229                 page = find_get_page(inode->i_mapping,
230                                      start >> PAGE_SHIFT);
231                 btrfs_set_file_extent_compression(leaf, ei, 0);
232                 kaddr = kmap_atomic(page);
233                 offset = start & (PAGE_SIZE - 1);
234                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
235                 kunmap_atomic(kaddr);
236                 put_page(page);
237         }
238         btrfs_mark_buffer_dirty(leaf);
239         btrfs_release_path(path);
240
241         /*
242          * we're an inline extent, so nobody can
243          * extend the file past i_size without locking
244          * a page we already have locked.
245          *
246          * We must do any isize and inode updates
247          * before we unlock the pages.  Otherwise we
248          * could end up racing with unlink.
249          */
250         BTRFS_I(inode)->disk_i_size = inode->i_size;
251         ret = btrfs_update_inode(trans, root, inode);
252
253 fail:
254         return ret;
255 }
256
257
258 /*
259  * conditionally insert an inline extent into the file.  This
260  * does the checks required to make sure the data is small enough
261  * to fit as an inline extent.
262  */
263 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
264                                           u64 end, size_t compressed_size,
265                                           int compress_type,
266                                           struct page **compressed_pages)
267 {
268         struct btrfs_root *root = BTRFS_I(inode)->root;
269         struct btrfs_fs_info *fs_info = root->fs_info;
270         struct btrfs_trans_handle *trans;
271         u64 isize = i_size_read(inode);
272         u64 actual_end = min(end + 1, isize);
273         u64 inline_len = actual_end - start;
274         u64 aligned_end = ALIGN(end, fs_info->sectorsize);
275         u64 data_len = inline_len;
276         int ret;
277         struct btrfs_path *path;
278         int extent_inserted = 0;
279         u32 extent_item_size;
280
281         if (compressed_size)
282                 data_len = compressed_size;
283
284         if (start > 0 ||
285             actual_end > fs_info->sectorsize ||
286             data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
287             (!compressed_size &&
288             (actual_end & (fs_info->sectorsize - 1)) == 0) ||
289             end + 1 < isize ||
290             data_len > fs_info->max_inline) {
291                 return 1;
292         }
293
294         path = btrfs_alloc_path();
295         if (!path)
296                 return -ENOMEM;
297
298         trans = btrfs_join_transaction(root);
299         if (IS_ERR(trans)) {
300                 btrfs_free_path(path);
301                 return PTR_ERR(trans);
302         }
303         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
304
305         if (compressed_size && compressed_pages)
306                 extent_item_size = btrfs_file_extent_calc_inline_size(
307                    compressed_size);
308         else
309                 extent_item_size = btrfs_file_extent_calc_inline_size(
310                     inline_len);
311
312         ret = __btrfs_drop_extents(trans, root, inode, path,
313                                    start, aligned_end, NULL,
314                                    1, 1, extent_item_size, &extent_inserted);
315         if (ret) {
316                 btrfs_abort_transaction(trans, ret);
317                 goto out;
318         }
319
320         if (isize > actual_end)
321                 inline_len = min_t(u64, isize, actual_end);
322         ret = insert_inline_extent(trans, path, extent_inserted,
323                                    root, inode, start,
324                                    inline_len, compressed_size,
325                                    compress_type, compressed_pages);
326         if (ret && ret != -ENOSPC) {
327                 btrfs_abort_transaction(trans, ret);
328                 goto out;
329         } else if (ret == -ENOSPC) {
330                 ret = 1;
331                 goto out;
332         }
333
334         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
335         btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
336 out:
337         /*
338          * Don't forget to free the reserved space, as for inlined extent
339          * it won't count as data extent, free them directly here.
340          * And at reserve time, it's always aligned to page size, so
341          * just free one page here.
342          */
343         btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
344         btrfs_free_path(path);
345         btrfs_end_transaction(trans);
346         return ret;
347 }
348
349 struct async_extent {
350         u64 start;
351         u64 ram_size;
352         u64 compressed_size;
353         struct page **pages;
354         unsigned long nr_pages;
355         int compress_type;
356         struct list_head list;
357 };
358
359 struct async_cow {
360         struct inode *inode;
361         struct btrfs_root *root;
362         struct page *locked_page;
363         u64 start;
364         u64 end;
365         unsigned int write_flags;
366         struct list_head extents;
367         struct btrfs_work work;
368 };
369
370 static noinline int add_async_extent(struct async_cow *cow,
371                                      u64 start, u64 ram_size,
372                                      u64 compressed_size,
373                                      struct page **pages,
374                                      unsigned long nr_pages,
375                                      int compress_type)
376 {
377         struct async_extent *async_extent;
378
379         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
380         BUG_ON(!async_extent); /* -ENOMEM */
381         async_extent->start = start;
382         async_extent->ram_size = ram_size;
383         async_extent->compressed_size = compressed_size;
384         async_extent->pages = pages;
385         async_extent->nr_pages = nr_pages;
386         async_extent->compress_type = compress_type;
387         list_add_tail(&async_extent->list, &cow->extents);
388         return 0;
389 }
390
391 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
392 {
393         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
394
395         /* force compress */
396         if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
397                 return 1;
398         /* defrag ioctl */
399         if (BTRFS_I(inode)->defrag_compress)
400                 return 1;
401         /* bad compression ratios */
402         if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
403                 return 0;
404         if (btrfs_test_opt(fs_info, COMPRESS) ||
405             BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
406             BTRFS_I(inode)->prop_compress)
407                 return btrfs_compress_heuristic(inode, start, end);
408         return 0;
409 }
410
411 static inline void inode_should_defrag(struct btrfs_inode *inode,
412                 u64 start, u64 end, u64 num_bytes, u64 small_write)
413 {
414         /* If this is a small write inside eof, kick off a defrag */
415         if (num_bytes < small_write &&
416             (start > 0 || end + 1 < inode->disk_i_size))
417                 btrfs_add_inode_defrag(NULL, inode);
418 }
419
420 /*
421  * we create compressed extents in two phases.  The first
422  * phase compresses a range of pages that have already been
423  * locked (both pages and state bits are locked).
424  *
425  * This is done inside an ordered work queue, and the compression
426  * is spread across many cpus.  The actual IO submission is step
427  * two, and the ordered work queue takes care of making sure that
428  * happens in the same order things were put onto the queue by
429  * writepages and friends.
430  *
431  * If this code finds it can't get good compression, it puts an
432  * entry onto the work queue to write the uncompressed bytes.  This
433  * makes sure that both compressed inodes and uncompressed inodes
434  * are written in the same order that the flusher thread sent them
435  * down.
436  */
437 static noinline void compress_file_range(struct inode *inode,
438                                         struct page *locked_page,
439                                         u64 start, u64 end,
440                                         struct async_cow *async_cow,
441                                         int *num_added)
442 {
443         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
444         u64 blocksize = fs_info->sectorsize;
445         u64 actual_end;
446         u64 isize = i_size_read(inode);
447         int ret = 0;
448         struct page **pages = NULL;
449         unsigned long nr_pages;
450         unsigned long total_compressed = 0;
451         unsigned long total_in = 0;
452         int i;
453         int will_compress;
454         int compress_type = fs_info->compress_type;
455         int redirty = 0;
456
457         inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
458                         SZ_16K);
459
460         actual_end = min_t(u64, isize, end + 1);
461 again:
462         will_compress = 0;
463         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
464         BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
465         nr_pages = min_t(unsigned long, nr_pages,
466                         BTRFS_MAX_COMPRESSED / PAGE_SIZE);
467
468         /*
469          * we don't want to send crud past the end of i_size through
470          * compression, that's just a waste of CPU time.  So, if the
471          * end of the file is before the start of our current
472          * requested range of bytes, we bail out to the uncompressed
473          * cleanup code that can deal with all of this.
474          *
475          * It isn't really the fastest way to fix things, but this is a
476          * very uncommon corner.
477          */
478         if (actual_end <= start)
479                 goto cleanup_and_bail_uncompressed;
480
481         total_compressed = actual_end - start;
482
483         /*
484          * skip compression for a small file range(<=blocksize) that
485          * isn't an inline extent, since it doesn't save disk space at all.
486          */
487         if (total_compressed <= blocksize &&
488            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
489                 goto cleanup_and_bail_uncompressed;
490
491         total_compressed = min_t(unsigned long, total_compressed,
492                         BTRFS_MAX_UNCOMPRESSED);
493         total_in = 0;
494         ret = 0;
495
496         /*
497          * we do compression for mount -o compress and when the
498          * inode has not been flagged as nocompress.  This flag can
499          * change at any time if we discover bad compression ratios.
500          */
501         if (inode_need_compress(inode, start, end)) {
502                 WARN_ON(pages);
503                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
504                 if (!pages) {
505                         /* just bail out to the uncompressed code */
506                         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 extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
851                         struct page *p = async_extent->pages[0];
852                         const u64 start = async_extent->start;
853                         const u64 end = start + async_extent->ram_size - 1;
854
855                         p->mapping = inode->i_mapping;
856                         tree->ops->writepage_end_io_hook(p, start, end,
857                                                          NULL, 0);
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, err;
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) {
1407                                 err = btrfs_start_write_no_snapshotting(root);
1408                                 if (!err)
1409                                         goto out_check;
1410                         }
1411                         /*
1412                          * force cow if csum exists in the range.
1413                          * this ensure that csum for a given extent are
1414                          * either valid or do not exist.
1415                          */
1416                         ret = csum_exist_in_range(fs_info, disk_bytenr,
1417                                                   num_bytes);
1418                         if (ret) {
1419                                 if (!nolock)
1420                                         btrfs_end_write_no_snapshotting(root);
1421
1422                                 /*
1423                                  * ret could be -EIO if the above fails to read
1424                                  * metadata.
1425                                  */
1426                                 if (ret < 0) {
1427                                         if (cow_start != (u64)-1)
1428                                                 cur_offset = cow_start;
1429                                         goto error;
1430                                 }
1431                                 WARN_ON_ONCE(nolock);
1432                                 goto out_check;
1433                         }
1434                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1435                                 if (!nolock)
1436                                         btrfs_end_write_no_snapshotting(root);
1437                                 goto out_check;
1438                         }
1439                         nocow = 1;
1440                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1441                         extent_end = found_key.offset +
1442                                 btrfs_file_extent_ram_bytes(leaf, fi);
1443                         extent_end = ALIGN(extent_end,
1444                                            fs_info->sectorsize);
1445                 } else {
1446                         BUG_ON(1);
1447                 }
1448 out_check:
1449                 if (extent_end <= start) {
1450                         path->slots[0]++;
1451                         if (!nolock && nocow)
1452                                 btrfs_end_write_no_snapshotting(root);
1453                         if (nocow)
1454                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1455                         goto next_slot;
1456                 }
1457                 if (!nocow) {
1458                         if (cow_start == (u64)-1)
1459                                 cow_start = cur_offset;
1460                         cur_offset = extent_end;
1461                         if (cur_offset > end)
1462                                 break;
1463                         path->slots[0]++;
1464                         goto next_slot;
1465                 }
1466
1467                 btrfs_release_path(path);
1468                 if (cow_start != (u64)-1) {
1469                         ret = cow_file_range(inode, locked_page,
1470                                              cow_start, found_key.offset - 1,
1471                                              end, page_started, nr_written, 1,
1472                                              NULL);
1473                         if (ret) {
1474                                 if (!nolock && nocow)
1475                                         btrfs_end_write_no_snapshotting(root);
1476                                 if (nocow)
1477                                         btrfs_dec_nocow_writers(fs_info,
1478                                                                 disk_bytenr);
1479                                 goto error;
1480                         }
1481                         cow_start = (u64)-1;
1482                 }
1483
1484                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1485                         u64 orig_start = found_key.offset - extent_offset;
1486
1487                         em = create_io_em(inode, cur_offset, num_bytes,
1488                                           orig_start,
1489                                           disk_bytenr, /* block_start */
1490                                           num_bytes, /* block_len */
1491                                           disk_num_bytes, /* orig_block_len */
1492                                           ram_bytes, BTRFS_COMPRESS_NONE,
1493                                           BTRFS_ORDERED_PREALLOC);
1494                         if (IS_ERR(em)) {
1495                                 if (!nolock && nocow)
1496                                         btrfs_end_write_no_snapshotting(root);
1497                                 if (nocow)
1498                                         btrfs_dec_nocow_writers(fs_info,
1499                                                                 disk_bytenr);
1500                                 ret = PTR_ERR(em);
1501                                 goto error;
1502                         }
1503                         free_extent_map(em);
1504                 }
1505
1506                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1507                         type = BTRFS_ORDERED_PREALLOC;
1508                 } else {
1509                         type = BTRFS_ORDERED_NOCOW;
1510                 }
1511
1512                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1513                                                num_bytes, num_bytes, type);
1514                 if (nocow)
1515                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1516                 BUG_ON(ret); /* -ENOMEM */
1517
1518                 if (root->root_key.objectid ==
1519                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1520                         /*
1521                          * Error handled later, as we must prevent
1522                          * extent_clear_unlock_delalloc() in error handler
1523                          * from freeing metadata of created ordered extent.
1524                          */
1525                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1526                                                       num_bytes);
1527
1528                 extent_clear_unlock_delalloc(inode, cur_offset,
1529                                              cur_offset + num_bytes - 1, end,
1530                                              locked_page, EXTENT_LOCKED |
1531                                              EXTENT_DELALLOC |
1532                                              EXTENT_CLEAR_DATA_RESV,
1533                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1534
1535                 if (!nolock && nocow)
1536                         btrfs_end_write_no_snapshotting(root);
1537                 cur_offset = extent_end;
1538
1539                 /*
1540                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1541                  * handler, as metadata for created ordered extent will only
1542                  * be freed by btrfs_finish_ordered_io().
1543                  */
1544                 if (ret)
1545                         goto error;
1546                 if (cur_offset > end)
1547                         break;
1548         }
1549         btrfs_release_path(path);
1550
1551         if (cur_offset <= end && cow_start == (u64)-1) {
1552                 cow_start = cur_offset;
1553                 cur_offset = end;
1554         }
1555
1556         if (cow_start != (u64)-1) {
1557                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1558                                      page_started, nr_written, 1, NULL);
1559                 if (ret)
1560                         goto error;
1561         }
1562
1563 error:
1564         if (ret && cur_offset < end)
1565                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1566                                              locked_page, EXTENT_LOCKED |
1567                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1568                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1569                                              PAGE_CLEAR_DIRTY |
1570                                              PAGE_SET_WRITEBACK |
1571                                              PAGE_END_WRITEBACK);
1572         btrfs_free_path(path);
1573         return ret;
1574 }
1575
1576 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1577 {
1578
1579         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1580             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1581                 return 0;
1582
1583         /*
1584          * @defrag_bytes is a hint value, no spinlock held here,
1585          * if is not zero, it means the file is defragging.
1586          * Force cow if given extent needs to be defragged.
1587          */
1588         if (BTRFS_I(inode)->defrag_bytes &&
1589             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1590                            EXTENT_DEFRAG, 0, NULL))
1591                 return 1;
1592
1593         return 0;
1594 }
1595
1596 /*
1597  * extent_io.c call back to do delayed allocation processing
1598  */
1599 static int run_delalloc_range(void *private_data, struct page *locked_page,
1600                               u64 start, u64 end, int *page_started,
1601                               unsigned long *nr_written,
1602                               struct writeback_control *wbc)
1603 {
1604         struct inode *inode = private_data;
1605         int ret;
1606         int force_cow = need_force_cow(inode, start, end);
1607         unsigned int write_flags = wbc_to_write_flags(wbc);
1608
1609         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1610                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1611                                          page_started, 1, nr_written);
1612         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1613                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1614                                          page_started, 0, nr_written);
1615         } else if (!inode_need_compress(inode, start, end)) {
1616                 ret = cow_file_range(inode, locked_page, start, end, end,
1617                                       page_started, nr_written, 1, NULL);
1618         } else {
1619                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1620                         &BTRFS_I(inode)->runtime_flags);
1621                 ret = cow_file_range_async(inode, locked_page, start, end,
1622                                            page_started, nr_written,
1623                                            write_flags);
1624         }
1625         if (ret)
1626                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1627         return ret;
1628 }
1629
1630 static void btrfs_split_extent_hook(void *private_data,
1631                                     struct extent_state *orig, u64 split)
1632 {
1633         struct inode *inode = private_data;
1634         u64 size;
1635
1636         /* not delalloc, ignore it */
1637         if (!(orig->state & EXTENT_DELALLOC))
1638                 return;
1639
1640         size = orig->end - orig->start + 1;
1641         if (size > BTRFS_MAX_EXTENT_SIZE) {
1642                 u32 num_extents;
1643                 u64 new_size;
1644
1645                 /*
1646                  * See the explanation in btrfs_merge_extent_hook, the same
1647                  * applies here, just in reverse.
1648                  */
1649                 new_size = orig->end - split + 1;
1650                 num_extents = count_max_extents(new_size);
1651                 new_size = split - orig->start;
1652                 num_extents += count_max_extents(new_size);
1653                 if (count_max_extents(size) >= num_extents)
1654                         return;
1655         }
1656
1657         spin_lock(&BTRFS_I(inode)->lock);
1658         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1659         spin_unlock(&BTRFS_I(inode)->lock);
1660 }
1661
1662 /*
1663  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1664  * extents so we can keep track of new extents that are just merged onto old
1665  * extents, such as when we are doing sequential writes, so we can properly
1666  * account for the metadata space we'll need.
1667  */
1668 static void btrfs_merge_extent_hook(void *private_data,
1669                                     struct extent_state *new,
1670                                     struct extent_state *other)
1671 {
1672         struct inode *inode = private_data;
1673         u64 new_size, old_size;
1674         u32 num_extents;
1675
1676         /* not delalloc, ignore it */
1677         if (!(other->state & EXTENT_DELALLOC))
1678                 return;
1679
1680         if (new->start > other->start)
1681                 new_size = new->end - other->start + 1;
1682         else
1683                 new_size = other->end - new->start + 1;
1684
1685         /* we're not bigger than the max, unreserve the space and go */
1686         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1687                 spin_lock(&BTRFS_I(inode)->lock);
1688                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1689                 spin_unlock(&BTRFS_I(inode)->lock);
1690                 return;
1691         }
1692
1693         /*
1694          * We have to add up either side to figure out how many extents were
1695          * accounted for before we merged into one big extent.  If the number of
1696          * extents we accounted for is <= the amount we need for the new range
1697          * then we can return, otherwise drop.  Think of it like this
1698          *
1699          * [ 4k][MAX_SIZE]
1700          *
1701          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1702          * need 2 outstanding extents, on one side we have 1 and the other side
1703          * we have 1 so they are == and we can return.  But in this case
1704          *
1705          * [MAX_SIZE+4k][MAX_SIZE+4k]
1706          *
1707          * Each range on their own accounts for 2 extents, but merged together
1708          * they are only 3 extents worth of accounting, so we need to drop in
1709          * this case.
1710          */
1711         old_size = other->end - other->start + 1;
1712         num_extents = count_max_extents(old_size);
1713         old_size = new->end - new->start + 1;
1714         num_extents += count_max_extents(old_size);
1715         if (count_max_extents(new_size) >= num_extents)
1716                 return;
1717
1718         spin_lock(&BTRFS_I(inode)->lock);
1719         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1720         spin_unlock(&BTRFS_I(inode)->lock);
1721 }
1722
1723 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1724                                       struct inode *inode)
1725 {
1726         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1727
1728         spin_lock(&root->delalloc_lock);
1729         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1730                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1731                               &root->delalloc_inodes);
1732                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1733                         &BTRFS_I(inode)->runtime_flags);
1734                 root->nr_delalloc_inodes++;
1735                 if (root->nr_delalloc_inodes == 1) {
1736                         spin_lock(&fs_info->delalloc_root_lock);
1737                         BUG_ON(!list_empty(&root->delalloc_root));
1738                         list_add_tail(&root->delalloc_root,
1739                                       &fs_info->delalloc_roots);
1740                         spin_unlock(&fs_info->delalloc_root_lock);
1741                 }
1742         }
1743         spin_unlock(&root->delalloc_lock);
1744 }
1745
1746
1747 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1748                                 struct btrfs_inode *inode)
1749 {
1750         struct btrfs_fs_info *fs_info = root->fs_info;
1751
1752         if (!list_empty(&inode->delalloc_inodes)) {
1753                 list_del_init(&inode->delalloc_inodes);
1754                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1755                           &inode->runtime_flags);
1756                 root->nr_delalloc_inodes--;
1757                 if (!root->nr_delalloc_inodes) {
1758                         ASSERT(list_empty(&root->delalloc_inodes));
1759                         spin_lock(&fs_info->delalloc_root_lock);
1760                         BUG_ON(list_empty(&root->delalloc_root));
1761                         list_del_init(&root->delalloc_root);
1762                         spin_unlock(&fs_info->delalloc_root_lock);
1763                 }
1764         }
1765 }
1766
1767 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1768                                      struct btrfs_inode *inode)
1769 {
1770         spin_lock(&root->delalloc_lock);
1771         __btrfs_del_delalloc_inode(root, inode);
1772         spin_unlock(&root->delalloc_lock);
1773 }
1774
1775 /*
1776  * extent_io.c set_bit_hook, used to track delayed allocation
1777  * bytes in this file, and to maintain the list of inodes that
1778  * have pending delalloc work to be done.
1779  */
1780 static void btrfs_set_bit_hook(void *private_data,
1781                                struct extent_state *state, unsigned *bits)
1782 {
1783         struct inode *inode = private_data;
1784
1785         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1786
1787         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1788                 WARN_ON(1);
1789         /*
1790          * set_bit and clear bit hooks normally require _irqsave/restore
1791          * but in this case, we are only testing for the DELALLOC
1792          * bit, which is only set or cleared with irqs on
1793          */
1794         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1795                 struct btrfs_root *root = BTRFS_I(inode)->root;
1796                 u64 len = state->end + 1 - state->start;
1797                 u32 num_extents = count_max_extents(len);
1798                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1799
1800                 spin_lock(&BTRFS_I(inode)->lock);
1801                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1802                 spin_unlock(&BTRFS_I(inode)->lock);
1803
1804                 /* For sanity tests */
1805                 if (btrfs_is_testing(fs_info))
1806                         return;
1807
1808                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1809                                          fs_info->delalloc_batch);
1810                 spin_lock(&BTRFS_I(inode)->lock);
1811                 BTRFS_I(inode)->delalloc_bytes += len;
1812                 if (*bits & EXTENT_DEFRAG)
1813                         BTRFS_I(inode)->defrag_bytes += len;
1814                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1815                                          &BTRFS_I(inode)->runtime_flags))
1816                         btrfs_add_delalloc_inodes(root, inode);
1817                 spin_unlock(&BTRFS_I(inode)->lock);
1818         }
1819
1820         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1821             (*bits & EXTENT_DELALLOC_NEW)) {
1822                 spin_lock(&BTRFS_I(inode)->lock);
1823                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1824                         state->start;
1825                 spin_unlock(&BTRFS_I(inode)->lock);
1826         }
1827 }
1828
1829 /*
1830  * extent_io.c clear_bit_hook, see set_bit_hook for why
1831  */
1832 static void btrfs_clear_bit_hook(void *private_data,
1833                                  struct extent_state *state,
1834                                  unsigned *bits)
1835 {
1836         struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1837         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1838         u64 len = state->end + 1 - state->start;
1839         u32 num_extents = count_max_extents(len);
1840
1841         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1842                 spin_lock(&inode->lock);
1843                 inode->defrag_bytes -= len;
1844                 spin_unlock(&inode->lock);
1845         }
1846
1847         /*
1848          * set_bit and clear bit hooks normally require _irqsave/restore
1849          * but in this case, we are only testing for the DELALLOC
1850          * bit, which is only set or cleared with irqs on
1851          */
1852         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1853                 struct btrfs_root *root = inode->root;
1854                 bool do_list = !btrfs_is_free_space_inode(inode);
1855
1856                 spin_lock(&inode->lock);
1857                 btrfs_mod_outstanding_extents(inode, -num_extents);
1858                 spin_unlock(&inode->lock);
1859
1860                 /*
1861                  * We don't reserve metadata space for space cache inodes so we
1862                  * don't need to call dellalloc_release_metadata if there is an
1863                  * error.
1864                  */
1865                 if (*bits & EXTENT_CLEAR_META_RESV &&
1866                     root != fs_info->tree_root)
1867                         btrfs_delalloc_release_metadata(inode, len, false);
1868
1869                 /* For sanity tests. */
1870                 if (btrfs_is_testing(fs_info))
1871                         return;
1872
1873                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1874                     do_list && !(state->state & EXTENT_NORESERVE) &&
1875                     (*bits & EXTENT_CLEAR_DATA_RESV))
1876                         btrfs_free_reserved_data_space_noquota(
1877                                         &inode->vfs_inode,
1878                                         state->start, len);
1879
1880                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1881                                          fs_info->delalloc_batch);
1882                 spin_lock(&inode->lock);
1883                 inode->delalloc_bytes -= len;
1884                 if (do_list && inode->delalloc_bytes == 0 &&
1885                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1886                                         &inode->runtime_flags))
1887                         btrfs_del_delalloc_inode(root, inode);
1888                 spin_unlock(&inode->lock);
1889         }
1890
1891         if ((state->state & EXTENT_DELALLOC_NEW) &&
1892             (*bits & EXTENT_DELALLOC_NEW)) {
1893                 spin_lock(&inode->lock);
1894                 ASSERT(inode->new_delalloc_bytes >= len);
1895                 inode->new_delalloc_bytes -= len;
1896                 spin_unlock(&inode->lock);
1897         }
1898 }
1899
1900 /*
1901  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1902  * we don't create bios that span stripes or chunks
1903  *
1904  * return 1 if page cannot be merged to bio
1905  * return 0 if page can be merged to bio
1906  * return error otherwise
1907  */
1908 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1909                          size_t size, struct bio *bio,
1910                          unsigned long bio_flags)
1911 {
1912         struct inode *inode = page->mapping->host;
1913         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1914         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1915         u64 length = 0;
1916         u64 map_length;
1917         int ret;
1918
1919         if (bio_flags & EXTENT_BIO_COMPRESSED)
1920                 return 0;
1921
1922         length = bio->bi_iter.bi_size;
1923         map_length = length;
1924         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1925                               NULL, 0);
1926         if (ret < 0)
1927                 return ret;
1928         if (map_length < length + size)
1929                 return 1;
1930         return 0;
1931 }
1932
1933 /*
1934  * in order to insert checksums into the metadata in large chunks,
1935  * we wait until bio submission time.   All the pages in the bio are
1936  * checksummed and sums are attached onto the ordered extent record.
1937  *
1938  * At IO completion time the cums attached on the ordered extent record
1939  * are inserted into the btree
1940  */
1941 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1942                                     u64 bio_offset)
1943 {
1944         struct inode *inode = private_data;
1945         blk_status_t ret = 0;
1946
1947         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1948         BUG_ON(ret); /* -ENOMEM */
1949         return 0;
1950 }
1951
1952 /*
1953  * in order to insert checksums into the metadata in large chunks,
1954  * we wait until bio submission time.   All the pages in the bio are
1955  * checksummed and sums are attached onto the ordered extent record.
1956  *
1957  * At IO completion time the cums attached on the ordered extent record
1958  * are inserted into the btree
1959  */
1960 static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1961                           int mirror_num)
1962 {
1963         struct inode *inode = private_data;
1964         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1965         blk_status_t ret;
1966
1967         ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1968         if (ret) {
1969                 bio->bi_status = ret;
1970                 bio_endio(bio);
1971         }
1972         return ret;
1973 }
1974
1975 /*
1976  * extent_io.c submission hook. This does the right thing for csum calculation
1977  * on write, or reading the csums from the tree before a read.
1978  *
1979  * Rules about async/sync submit,
1980  * a) read:                             sync submit
1981  *
1982  * b) write without checksum:           sync submit
1983  *
1984  * c) write with checksum:
1985  *    c-1) if bio is issued by fsync:   sync submit
1986  *         (sync_writers != 0)
1987  *
1988  *    c-2) if root is reloc root:       sync submit
1989  *         (only in case of buffered IO)
1990  *
1991  *    c-3) otherwise:                   async submit
1992  */
1993 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1994                                  int mirror_num, unsigned long bio_flags,
1995                                  u64 bio_offset)
1996 {
1997         struct inode *inode = private_data;
1998         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1999         struct btrfs_root *root = BTRFS_I(inode)->root;
2000         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2001         blk_status_t ret = 0;
2002         int skip_sum;
2003         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2004
2005         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2006
2007         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2008                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2009
2010         if (bio_op(bio) != REQ_OP_WRITE) {
2011                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2012                 if (ret)
2013                         goto out;
2014
2015                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2016                         ret = btrfs_submit_compressed_read(inode, bio,
2017                                                            mirror_num,
2018                                                            bio_flags);
2019                         goto out;
2020                 } else if (!skip_sum) {
2021                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2022                         if (ret)
2023                                 goto out;
2024                 }
2025                 goto mapit;
2026         } else if (async && !skip_sum) {
2027                 /* csum items have already been cloned */
2028                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2029                         goto mapit;
2030                 /* we're doing a write, do the async checksumming */
2031                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2032                                           bio_offset, inode,
2033                                           btrfs_submit_bio_start,
2034                                           btrfs_submit_bio_done);
2035                 goto out;
2036         } else if (!skip_sum) {
2037                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2038                 if (ret)
2039                         goto out;
2040         }
2041
2042 mapit:
2043         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2044
2045 out:
2046         if (ret) {
2047                 bio->bi_status = ret;
2048                 bio_endio(bio);
2049         }
2050         return ret;
2051 }
2052
2053 /*
2054  * given a list of ordered sums record them in the inode.  This happens
2055  * at IO completion time based on sums calculated at bio submission time.
2056  */
2057 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2058                              struct inode *inode, struct list_head *list)
2059 {
2060         struct btrfs_ordered_sum *sum;
2061         int ret;
2062
2063         list_for_each_entry(sum, list, list) {
2064                 trans->adding_csums = true;
2065                 ret = btrfs_csum_file_blocks(trans,
2066                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2067                 trans->adding_csums = false;
2068                 if (ret)
2069                         return ret;
2070         }
2071         return 0;
2072 }
2073
2074 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2075                               unsigned int extra_bits,
2076                               struct extent_state **cached_state, int dedupe)
2077 {
2078         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2079         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2080                                    extra_bits, cached_state);
2081 }
2082
2083 /* see btrfs_writepage_start_hook for details on why this is required */
2084 struct btrfs_writepage_fixup {
2085         struct page *page;
2086         struct btrfs_work work;
2087 };
2088
2089 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2090 {
2091         struct btrfs_writepage_fixup *fixup;
2092         struct btrfs_ordered_extent *ordered;
2093         struct extent_state *cached_state = NULL;
2094         struct extent_changeset *data_reserved = NULL;
2095         struct page *page;
2096         struct inode *inode;
2097         u64 page_start;
2098         u64 page_end;
2099         int ret;
2100
2101         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2102         page = fixup->page;
2103 again:
2104         lock_page(page);
2105         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2106                 ClearPageChecked(page);
2107                 goto out_page;
2108         }
2109
2110         inode = page->mapping->host;
2111         page_start = page_offset(page);
2112         page_end = page_offset(page) + PAGE_SIZE - 1;
2113
2114         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2115                          &cached_state);
2116
2117         /* already ordered? We're done */
2118         if (PagePrivate2(page))
2119                 goto out;
2120
2121         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2122                                         PAGE_SIZE);
2123         if (ordered) {
2124                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2125                                      page_end, &cached_state);
2126                 unlock_page(page);
2127                 btrfs_start_ordered_extent(inode, ordered, 1);
2128                 btrfs_put_ordered_extent(ordered);
2129                 goto again;
2130         }
2131
2132         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2133                                            PAGE_SIZE);
2134         if (ret) {
2135                 mapping_set_error(page->mapping, ret);
2136                 end_extent_writepage(page, ret, page_start, page_end);
2137                 ClearPageChecked(page);
2138                 goto out;
2139          }
2140
2141         ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2142                                         &cached_state, 0);
2143         if (ret) {
2144                 mapping_set_error(page->mapping, ret);
2145                 end_extent_writepage(page, ret, page_start, page_end);
2146                 ClearPageChecked(page);
2147                 goto out;
2148         }
2149
2150         ClearPageChecked(page);
2151         set_page_dirty(page);
2152         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2153 out:
2154         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2155                              &cached_state);
2156 out_page:
2157         unlock_page(page);
2158         put_page(page);
2159         kfree(fixup);
2160         extent_changeset_free(data_reserved);
2161 }
2162
2163 /*
2164  * There are a few paths in the higher layers of the kernel that directly
2165  * set the page dirty bit without asking the filesystem if it is a
2166  * good idea.  This causes problems because we want to make sure COW
2167  * properly happens and the data=ordered rules are followed.
2168  *
2169  * In our case any range that doesn't have the ORDERED bit set
2170  * hasn't been properly setup for IO.  We kick off an async process
2171  * to fix it up.  The async helper will wait for ordered extents, set
2172  * the delalloc bit and make it safe to write the page.
2173  */
2174 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2175 {
2176         struct inode *inode = page->mapping->host;
2177         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2178         struct btrfs_writepage_fixup *fixup;
2179
2180         /* this page is properly in the ordered list */
2181         if (TestClearPagePrivate2(page))
2182                 return 0;
2183
2184         if (PageChecked(page))
2185                 return -EAGAIN;
2186
2187         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2188         if (!fixup)
2189                 return -EAGAIN;
2190
2191         SetPageChecked(page);
2192         get_page(page);
2193         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2194                         btrfs_writepage_fixup_worker, NULL, NULL);
2195         fixup->page = page;
2196         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2197         return -EBUSY;
2198 }
2199
2200 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2201                                        struct inode *inode, u64 file_pos,
2202                                        u64 disk_bytenr, u64 disk_num_bytes,
2203                                        u64 num_bytes, u64 ram_bytes,
2204                                        u8 compression, u8 encryption,
2205                                        u16 other_encoding, int extent_type)
2206 {
2207         struct btrfs_root *root = BTRFS_I(inode)->root;
2208         struct btrfs_file_extent_item *fi;
2209         struct btrfs_path *path;
2210         struct extent_buffer *leaf;
2211         struct btrfs_key ins;
2212         u64 qg_released;
2213         int extent_inserted = 0;
2214         int ret;
2215
2216         path = btrfs_alloc_path();
2217         if (!path)
2218                 return -ENOMEM;
2219
2220         /*
2221          * we may be replacing one extent in the tree with another.
2222          * The new extent is pinned in the extent map, and we don't want
2223          * to drop it from the cache until it is completely in the btree.
2224          *
2225          * So, tell btrfs_drop_extents to leave this extent in the cache.
2226          * the caller is expected to unpin it and allow it to be merged
2227          * with the others.
2228          */
2229         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2230                                    file_pos + num_bytes, NULL, 0,
2231                                    1, sizeof(*fi), &extent_inserted);
2232         if (ret)
2233                 goto out;
2234
2235         if (!extent_inserted) {
2236                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2237                 ins.offset = file_pos;
2238                 ins.type = BTRFS_EXTENT_DATA_KEY;
2239
2240                 path->leave_spinning = 1;
2241                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2242                                               sizeof(*fi));
2243                 if (ret)
2244                         goto out;
2245         }
2246         leaf = path->nodes[0];
2247         fi = btrfs_item_ptr(leaf, path->slots[0],
2248                             struct btrfs_file_extent_item);
2249         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2250         btrfs_set_file_extent_type(leaf, fi, extent_type);
2251         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2252         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2253         btrfs_set_file_extent_offset(leaf, fi, 0);
2254         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2255         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2256         btrfs_set_file_extent_compression(leaf, fi, compression);
2257         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2258         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2259
2260         btrfs_mark_buffer_dirty(leaf);
2261         btrfs_release_path(path);
2262
2263         inode_add_bytes(inode, num_bytes);
2264
2265         ins.objectid = disk_bytenr;
2266         ins.offset = disk_num_bytes;
2267         ins.type = BTRFS_EXTENT_ITEM_KEY;
2268
2269         /*
2270          * Release the reserved range from inode dirty range map, as it is
2271          * already moved into delayed_ref_head
2272          */
2273         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2274         if (ret < 0)
2275                 goto out;
2276         qg_released = ret;
2277         ret = btrfs_alloc_reserved_file_extent(trans, root,
2278                                                btrfs_ino(BTRFS_I(inode)),
2279                                                file_pos, qg_released, &ins);
2280 out:
2281         btrfs_free_path(path);
2282
2283         return ret;
2284 }
2285
2286 /* snapshot-aware defrag */
2287 struct sa_defrag_extent_backref {
2288         struct rb_node node;
2289         struct old_sa_defrag_extent *old;
2290         u64 root_id;
2291         u64 inum;
2292         u64 file_pos;
2293         u64 extent_offset;
2294         u64 num_bytes;
2295         u64 generation;
2296 };
2297
2298 struct old_sa_defrag_extent {
2299         struct list_head list;
2300         struct new_sa_defrag_extent *new;
2301
2302         u64 extent_offset;
2303         u64 bytenr;
2304         u64 offset;
2305         u64 len;
2306         int count;
2307 };
2308
2309 struct new_sa_defrag_extent {
2310         struct rb_root root;
2311         struct list_head head;
2312         struct btrfs_path *path;
2313         struct inode *inode;
2314         u64 file_pos;
2315         u64 len;
2316         u64 bytenr;
2317         u64 disk_len;
2318         u8 compress_type;
2319 };
2320
2321 static int backref_comp(struct sa_defrag_extent_backref *b1,
2322                         struct sa_defrag_extent_backref *b2)
2323 {
2324         if (b1->root_id < b2->root_id)
2325                 return -1;
2326         else if (b1->root_id > b2->root_id)
2327                 return 1;
2328
2329         if (b1->inum < b2->inum)
2330                 return -1;
2331         else if (b1->inum > b2->inum)
2332                 return 1;
2333
2334         if (b1->file_pos < b2->file_pos)
2335                 return -1;
2336         else if (b1->file_pos > b2->file_pos)
2337                 return 1;
2338
2339         /*
2340          * [------------------------------] ===> (a range of space)
2341          *     |<--->|   |<---->| =============> (fs/file tree A)
2342          * |<---------------------------->| ===> (fs/file tree B)
2343          *
2344          * A range of space can refer to two file extents in one tree while
2345          * refer to only one file extent in another tree.
2346          *
2347          * So we may process a disk offset more than one time(two extents in A)
2348          * and locate at the same extent(one extent in B), then insert two same
2349          * backrefs(both refer to the extent in B).
2350          */
2351         return 0;
2352 }
2353
2354 static void backref_insert(struct rb_root *root,
2355                            struct sa_defrag_extent_backref *backref)
2356 {
2357         struct rb_node **p = &root->rb_node;
2358         struct rb_node *parent = NULL;
2359         struct sa_defrag_extent_backref *entry;
2360         int ret;
2361
2362         while (*p) {
2363                 parent = *p;
2364                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2365
2366                 ret = backref_comp(backref, entry);
2367                 if (ret < 0)
2368                         p = &(*p)->rb_left;
2369                 else
2370                         p = &(*p)->rb_right;
2371         }
2372
2373         rb_link_node(&backref->node, parent, p);
2374         rb_insert_color(&backref->node, root);
2375 }
2376
2377 /*
2378  * Note the backref might has changed, and in this case we just return 0.
2379  */
2380 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2381                                        void *ctx)
2382 {
2383         struct btrfs_file_extent_item *extent;
2384         struct old_sa_defrag_extent *old = ctx;
2385         struct new_sa_defrag_extent *new = old->new;
2386         struct btrfs_path *path = new->path;
2387         struct btrfs_key key;
2388         struct btrfs_root *root;
2389         struct sa_defrag_extent_backref *backref;
2390         struct extent_buffer *leaf;
2391         struct inode *inode = new->inode;
2392         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2393         int slot;
2394         int ret;
2395         u64 extent_offset;
2396         u64 num_bytes;
2397
2398         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2399             inum == btrfs_ino(BTRFS_I(inode)))
2400                 return 0;
2401
2402         key.objectid = root_id;
2403         key.type = BTRFS_ROOT_ITEM_KEY;
2404         key.offset = (u64)-1;
2405
2406         root = btrfs_read_fs_root_no_name(fs_info, &key);
2407         if (IS_ERR(root)) {
2408                 if (PTR_ERR(root) == -ENOENT)
2409                         return 0;
2410                 WARN_ON(1);
2411                 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2412                          inum, offset, root_id);
2413                 return PTR_ERR(root);
2414         }
2415
2416         key.objectid = inum;
2417         key.type = BTRFS_EXTENT_DATA_KEY;
2418         if (offset > (u64)-1 << 32)
2419                 key.offset = 0;
2420         else
2421                 key.offset = offset;
2422
2423         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2424         if (WARN_ON(ret < 0))
2425                 return ret;
2426         ret = 0;
2427
2428         while (1) {
2429                 cond_resched();
2430
2431                 leaf = path->nodes[0];
2432                 slot = path->slots[0];
2433
2434                 if (slot >= btrfs_header_nritems(leaf)) {
2435                         ret = btrfs_next_leaf(root, path);
2436                         if (ret < 0) {
2437                                 goto out;
2438                         } else if (ret > 0) {
2439                                 ret = 0;
2440                                 goto out;
2441                         }
2442                         continue;
2443                 }
2444
2445                 path->slots[0]++;
2446
2447                 btrfs_item_key_to_cpu(leaf, &key, slot);
2448
2449                 if (key.objectid > inum)
2450                         goto out;
2451
2452                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2453                         continue;
2454
2455                 extent = btrfs_item_ptr(leaf, slot,
2456                                         struct btrfs_file_extent_item);
2457
2458                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2459                         continue;
2460
2461                 /*
2462                  * 'offset' refers to the exact key.offset,
2463                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2464                  * (key.offset - extent_offset).
2465                  */
2466                 if (key.offset != offset)
2467                         continue;
2468
2469                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2470                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2471
2472                 if (extent_offset >= old->extent_offset + old->offset +
2473                     old->len || extent_offset + num_bytes <=
2474                     old->extent_offset + old->offset)
2475                         continue;
2476                 break;
2477         }
2478
2479         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2480         if (!backref) {
2481                 ret = -ENOENT;
2482                 goto out;
2483         }
2484
2485         backref->root_id = root_id;
2486         backref->inum = inum;
2487         backref->file_pos = offset;
2488         backref->num_bytes = num_bytes;
2489         backref->extent_offset = extent_offset;
2490         backref->generation = btrfs_file_extent_generation(leaf, extent);
2491         backref->old = old;
2492         backref_insert(&new->root, backref);
2493         old->count++;
2494 out:
2495         btrfs_release_path(path);
2496         WARN_ON(ret);
2497         return ret;
2498 }
2499
2500 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2501                                    struct new_sa_defrag_extent *new)
2502 {
2503         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2504         struct old_sa_defrag_extent *old, *tmp;
2505         int ret;
2506
2507         new->path = path;
2508
2509         list_for_each_entry_safe(old, tmp, &new->head, list) {
2510                 ret = iterate_inodes_from_logical(old->bytenr +
2511                                                   old->extent_offset, fs_info,
2512                                                   path, record_one_backref,
2513                                                   old, false);
2514                 if (ret < 0 && ret != -ENOENT)
2515                         return false;
2516
2517                 /* no backref to be processed for this extent */
2518                 if (!old->count) {
2519                         list_del(&old->list);
2520                         kfree(old);
2521                 }
2522         }
2523
2524         if (list_empty(&new->head))
2525                 return false;
2526
2527         return true;
2528 }
2529
2530 static int relink_is_mergable(struct extent_buffer *leaf,
2531                               struct btrfs_file_extent_item *fi,
2532                               struct new_sa_defrag_extent *new)
2533 {
2534         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2535                 return 0;
2536
2537         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2538                 return 0;
2539
2540         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2541                 return 0;
2542
2543         if (btrfs_file_extent_encryption(leaf, fi) ||
2544             btrfs_file_extent_other_encoding(leaf, fi))
2545                 return 0;
2546
2547         return 1;
2548 }
2549
2550 /*
2551  * Note the backref might has changed, and in this case we just return 0.
2552  */
2553 static noinline int relink_extent_backref(struct btrfs_path *path,
2554                                  struct sa_defrag_extent_backref *prev,
2555                                  struct sa_defrag_extent_backref *backref)
2556 {
2557         struct btrfs_file_extent_item *extent;
2558         struct btrfs_file_extent_item *item;
2559         struct btrfs_ordered_extent *ordered;
2560         struct btrfs_trans_handle *trans;
2561         struct btrfs_root *root;
2562         struct btrfs_key key;
2563         struct extent_buffer *leaf;
2564         struct old_sa_defrag_extent *old = backref->old;
2565         struct new_sa_defrag_extent *new = old->new;
2566         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2567         struct inode *inode;
2568         struct extent_state *cached = NULL;
2569         int ret = 0;
2570         u64 start;
2571         u64 len;
2572         u64 lock_start;
2573         u64 lock_end;
2574         bool merge = false;
2575         int index;
2576
2577         if (prev && prev->root_id == backref->root_id &&
2578             prev->inum == backref->inum &&
2579             prev->file_pos + prev->num_bytes == backref->file_pos)
2580                 merge = true;
2581
2582         /* step 1: get root */
2583         key.objectid = backref->root_id;
2584         key.type = BTRFS_ROOT_ITEM_KEY;
2585         key.offset = (u64)-1;
2586
2587         index = srcu_read_lock(&fs_info->subvol_srcu);
2588
2589         root = btrfs_read_fs_root_no_name(fs_info, &key);
2590         if (IS_ERR(root)) {
2591                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2592                 if (PTR_ERR(root) == -ENOENT)
2593                         return 0;
2594                 return PTR_ERR(root);
2595         }
2596
2597         if (btrfs_root_readonly(root)) {
2598                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2599                 return 0;
2600         }
2601
2602         /* step 2: get inode */
2603         key.objectid = backref->inum;
2604         key.type = BTRFS_INODE_ITEM_KEY;
2605         key.offset = 0;
2606
2607         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2608         if (IS_ERR(inode)) {
2609                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2610                 return 0;
2611         }
2612
2613         srcu_read_unlock(&fs_info->subvol_srcu, index);
2614
2615         /* step 3: relink backref */
2616         lock_start = backref->file_pos;
2617         lock_end = backref->file_pos + backref->num_bytes - 1;
2618         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2619                          &cached);
2620
2621         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2622         if (ordered) {
2623                 btrfs_put_ordered_extent(ordered);
2624                 goto out_unlock;
2625         }
2626
2627         trans = btrfs_join_transaction(root);
2628         if (IS_ERR(trans)) {
2629                 ret = PTR_ERR(trans);
2630                 goto out_unlock;
2631         }
2632
2633         key.objectid = backref->inum;
2634         key.type = BTRFS_EXTENT_DATA_KEY;
2635         key.offset = backref->file_pos;
2636
2637         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2638         if (ret < 0) {
2639                 goto out_free_path;
2640         } else if (ret > 0) {
2641                 ret = 0;
2642                 goto out_free_path;
2643         }
2644
2645         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2646                                 struct btrfs_file_extent_item);
2647
2648         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2649             backref->generation)
2650                 goto out_free_path;
2651
2652         btrfs_release_path(path);
2653
2654         start = backref->file_pos;
2655         if (backref->extent_offset < old->extent_offset + old->offset)
2656                 start += old->extent_offset + old->offset -
2657                          backref->extent_offset;
2658
2659         len = min(backref->extent_offset + backref->num_bytes,
2660                   old->extent_offset + old->offset + old->len);
2661         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2662
2663         ret = btrfs_drop_extents(trans, root, inode, start,
2664                                  start + len, 1);
2665         if (ret)
2666                 goto out_free_path;
2667 again:
2668         key.objectid = btrfs_ino(BTRFS_I(inode));
2669         key.type = BTRFS_EXTENT_DATA_KEY;
2670         key.offset = start;
2671
2672         path->leave_spinning = 1;
2673         if (merge) {
2674                 struct btrfs_file_extent_item *fi;
2675                 u64 extent_len;
2676                 struct btrfs_key found_key;
2677
2678                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2679                 if (ret < 0)
2680                         goto out_free_path;
2681
2682                 path->slots[0]--;
2683                 leaf = path->nodes[0];
2684                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2685
2686                 fi = btrfs_item_ptr(leaf, path->slots[0],
2687                                     struct btrfs_file_extent_item);
2688                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2689
2690                 if (extent_len + found_key.offset == start &&
2691                     relink_is_mergable(leaf, fi, new)) {
2692                         btrfs_set_file_extent_num_bytes(leaf, fi,
2693                                                         extent_len + len);
2694                         btrfs_mark_buffer_dirty(leaf);
2695                         inode_add_bytes(inode, len);
2696
2697                         ret = 1;
2698                         goto out_free_path;
2699                 } else {
2700                         merge = false;
2701                         btrfs_release_path(path);
2702                         goto again;
2703                 }
2704         }
2705
2706         ret = btrfs_insert_empty_item(trans, root, path, &key,
2707                                         sizeof(*extent));
2708         if (ret) {
2709                 btrfs_abort_transaction(trans, ret);
2710                 goto out_free_path;
2711         }
2712
2713         leaf = path->nodes[0];
2714         item = btrfs_item_ptr(leaf, path->slots[0],
2715                                 struct btrfs_file_extent_item);
2716         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2717         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2718         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2719         btrfs_set_file_extent_num_bytes(leaf, item, len);
2720         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2721         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2722         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2723         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2724         btrfs_set_file_extent_encryption(leaf, item, 0);
2725         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2726
2727         btrfs_mark_buffer_dirty(leaf);
2728         inode_add_bytes(inode, len);
2729         btrfs_release_path(path);
2730
2731         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2732                         new->disk_len, 0,
2733                         backref->root_id, backref->inum,
2734                         new->file_pos); /* start - extent_offset */
2735         if (ret) {
2736                 btrfs_abort_transaction(trans, ret);
2737                 goto out_free_path;
2738         }
2739
2740         ret = 1;
2741 out_free_path:
2742         btrfs_release_path(path);
2743         path->leave_spinning = 0;
2744         btrfs_end_transaction(trans);
2745 out_unlock:
2746         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2747                              &cached);
2748         iput(inode);
2749         return ret;
2750 }
2751
2752 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2753 {
2754         struct old_sa_defrag_extent *old, *tmp;
2755
2756         if (!new)
2757                 return;
2758
2759         list_for_each_entry_safe(old, tmp, &new->head, list) {
2760                 kfree(old);
2761         }
2762         kfree(new);
2763 }
2764
2765 static void relink_file_extents(struct new_sa_defrag_extent *new)
2766 {
2767         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2768         struct btrfs_path *path;
2769         struct sa_defrag_extent_backref *backref;
2770         struct sa_defrag_extent_backref *prev = NULL;
2771         struct inode *inode;
2772         struct rb_node *node;
2773         int ret;
2774
2775         inode = new->inode;
2776
2777         path = btrfs_alloc_path();
2778         if (!path)
2779                 return;
2780
2781         if (!record_extent_backrefs(path, new)) {
2782                 btrfs_free_path(path);
2783                 goto out;
2784         }
2785         btrfs_release_path(path);
2786
2787         while (1) {
2788                 node = rb_first(&new->root);
2789                 if (!node)
2790                         break;
2791                 rb_erase(node, &new->root);
2792
2793                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2794
2795                 ret = relink_extent_backref(path, prev, backref);
2796                 WARN_ON(ret < 0);
2797
2798                 kfree(prev);
2799
2800                 if (ret == 1)
2801                         prev = backref;
2802                 else
2803                         prev = NULL;
2804                 cond_resched();
2805         }
2806         kfree(prev);
2807
2808         btrfs_free_path(path);
2809 out:
2810         free_sa_defrag_extent(new);
2811
2812         atomic_dec(&fs_info->defrag_running);
2813         wake_up(&fs_info->transaction_wait);
2814 }
2815
2816 static struct new_sa_defrag_extent *
2817 record_old_file_extents(struct inode *inode,
2818                         struct btrfs_ordered_extent *ordered)
2819 {
2820         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2821         struct btrfs_root *root = BTRFS_I(inode)->root;
2822         struct btrfs_path *path;
2823         struct btrfs_key key;
2824         struct old_sa_defrag_extent *old;
2825         struct new_sa_defrag_extent *new;
2826         int ret;
2827
2828         new = kmalloc(sizeof(*new), GFP_NOFS);
2829         if (!new)
2830                 return NULL;
2831
2832         new->inode = inode;
2833         new->file_pos = ordered->file_offset;
2834         new->len = ordered->len;
2835         new->bytenr = ordered->start;
2836         new->disk_len = ordered->disk_len;
2837         new->compress_type = ordered->compress_type;
2838         new->root = RB_ROOT;
2839         INIT_LIST_HEAD(&new->head);
2840
2841         path = btrfs_alloc_path();
2842         if (!path)
2843                 goto out_kfree;
2844
2845         key.objectid = btrfs_ino(BTRFS_I(inode));
2846         key.type = BTRFS_EXTENT_DATA_KEY;
2847         key.offset = new->file_pos;
2848
2849         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2850         if (ret < 0)
2851                 goto out_free_path;
2852         if (ret > 0 && path->slots[0] > 0)
2853                 path->slots[0]--;
2854
2855         /* find out all the old extents for the file range */
2856         while (1) {
2857                 struct btrfs_file_extent_item *extent;
2858                 struct extent_buffer *l;
2859                 int slot;
2860                 u64 num_bytes;
2861                 u64 offset;
2862                 u64 end;
2863                 u64 disk_bytenr;
2864                 u64 extent_offset;
2865
2866                 l = path->nodes[0];
2867                 slot = path->slots[0];
2868
2869                 if (slot >= btrfs_header_nritems(l)) {
2870                         ret = btrfs_next_leaf(root, path);
2871                         if (ret < 0)
2872                                 goto out_free_path;
2873                         else if (ret > 0)
2874                                 break;
2875                         continue;
2876                 }
2877
2878                 btrfs_item_key_to_cpu(l, &key, slot);
2879
2880                 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2881                         break;
2882                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2883                         break;
2884                 if (key.offset >= new->file_pos + new->len)
2885                         break;
2886
2887                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2888
2889                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2890                 if (key.offset + num_bytes < new->file_pos)
2891                         goto next;
2892
2893                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2894                 if (!disk_bytenr)
2895                         goto next;
2896
2897                 extent_offset = btrfs_file_extent_offset(l, extent);
2898
2899                 old = kmalloc(sizeof(*old), GFP_NOFS);
2900                 if (!old)
2901                         goto out_free_path;
2902
2903                 offset = max(new->file_pos, key.offset);
2904                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2905
2906                 old->bytenr = disk_bytenr;
2907                 old->extent_offset = extent_offset;
2908                 old->offset = offset - key.offset;
2909                 old->len = end - offset;
2910                 old->new = new;
2911                 old->count = 0;
2912                 list_add_tail(&old->list, &new->head);
2913 next:
2914                 path->slots[0]++;
2915                 cond_resched();
2916         }
2917
2918         btrfs_free_path(path);
2919         atomic_inc(&fs_info->defrag_running);
2920
2921         return new;
2922
2923 out_free_path:
2924         btrfs_free_path(path);
2925 out_kfree:
2926         free_sa_defrag_extent(new);
2927         return NULL;
2928 }
2929
2930 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2931                                          u64 start, u64 len)
2932 {
2933         struct btrfs_block_group_cache *cache;
2934
2935         cache = btrfs_lookup_block_group(fs_info, start);
2936         ASSERT(cache);
2937
2938         spin_lock(&cache->lock);
2939         cache->delalloc_bytes -= len;
2940         spin_unlock(&cache->lock);
2941
2942         btrfs_put_block_group(cache);
2943 }
2944
2945 /* as ordered data IO finishes, this gets called so we can finish
2946  * an ordered extent if the range of bytes in the file it covers are
2947  * fully written.
2948  */
2949 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2950 {
2951         struct inode *inode = ordered_extent->inode;
2952         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2953         struct btrfs_root *root = BTRFS_I(inode)->root;
2954         struct btrfs_trans_handle *trans = NULL;
2955         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2956         struct extent_state *cached_state = NULL;
2957         struct new_sa_defrag_extent *new = NULL;
2958         int compress_type = 0;
2959         int ret = 0;
2960         u64 logical_len = ordered_extent->len;
2961         bool nolock;
2962         bool truncated = false;
2963         bool range_locked = false;
2964         bool clear_new_delalloc_bytes = false;
2965
2966         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2967             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2968             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2969                 clear_new_delalloc_bytes = true;
2970
2971         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2972
2973         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2974                 ret = -EIO;
2975                 goto out;
2976         }
2977
2978         btrfs_free_io_failure_record(BTRFS_I(inode),
2979                         ordered_extent->file_offset,
2980                         ordered_extent->file_offset +
2981                         ordered_extent->len - 1);
2982
2983         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2984                 truncated = true;
2985                 logical_len = ordered_extent->truncated_len;
2986                 /* Truncated the entire extent, don't bother adding */
2987                 if (!logical_len)
2988                         goto out;
2989         }
2990
2991         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2992                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2993
2994                 /*
2995                  * For mwrite(mmap + memset to write) case, we still reserve
2996                  * space for NOCOW range.
2997                  * As NOCOW won't cause a new delayed ref, just free the space
2998                  */
2999                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3000                                        ordered_extent->len);
3001                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3002                 if (nolock)
3003                         trans = btrfs_join_transaction_nolock(root);
3004                 else
3005                         trans = btrfs_join_transaction(root);
3006                 if (IS_ERR(trans)) {
3007                         ret = PTR_ERR(trans);
3008                         trans = NULL;
3009                         goto out;
3010                 }
3011                 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3012                 ret = btrfs_update_inode_fallback(trans, root, inode);
3013                 if (ret) /* -ENOMEM or corruption */
3014                         btrfs_abort_transaction(trans, ret);
3015                 goto out;
3016         }
3017
3018         range_locked = true;
3019         lock_extent_bits(io_tree, ordered_extent->file_offset,
3020                          ordered_extent->file_offset + ordered_extent->len - 1,
3021                          &cached_state);
3022
3023         ret = test_range_bit(io_tree, ordered_extent->file_offset,
3024                         ordered_extent->file_offset + ordered_extent->len - 1,
3025                         EXTENT_DEFRAG, 0, cached_state);
3026         if (ret) {
3027                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3028                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3029                         /* the inode is shared */
3030                         new = record_old_file_extents(inode, ordered_extent);
3031
3032                 clear_extent_bit(io_tree, ordered_extent->file_offset,
3033                         ordered_extent->file_offset + ordered_extent->len - 1,
3034                         EXTENT_DEFRAG, 0, 0, &cached_state);
3035         }
3036
3037         if (nolock)
3038                 trans = btrfs_join_transaction_nolock(root);
3039         else
3040                 trans = btrfs_join_transaction(root);
3041         if (IS_ERR(trans)) {
3042                 ret = PTR_ERR(trans);
3043                 trans = NULL;
3044                 goto out;
3045         }
3046
3047         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3048
3049         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3050                 compress_type = ordered_extent->compress_type;
3051         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3052                 BUG_ON(compress_type);
3053                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3054                                        ordered_extent->len);
3055                 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3056                                                 ordered_extent->file_offset,
3057                                                 ordered_extent->file_offset +
3058                                                 logical_len);
3059         } else {
3060                 BUG_ON(root == fs_info->tree_root);
3061                 ret = insert_reserved_file_extent(trans, inode,
3062                                                 ordered_extent->file_offset,
3063                                                 ordered_extent->start,
3064                                                 ordered_extent->disk_len,
3065                                                 logical_len, logical_len,
3066                                                 compress_type, 0, 0,