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