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