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