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