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