1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/mpage.h>
18 #include <linux/swap.h>
19 #include <linux/writeback.h>
20 #include <linux/compat.h>
21 #include <linux/bit_spinlock.h>
22 #include <linux/xattr.h>
23 #include <linux/posix_acl.h>
24 #include <linux/falloc.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/mount.h>
28 #include <linux/btrfs.h>
29 #include <linux/blkdev.h>
30 #include <linux/posix_acl_xattr.h>
31 #include <linux/uio.h>
32 #include <linux/magic.h>
33 #include <linux/iversion.h>
34 #include <asm/unaligned.h>
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
40 #include "ordered-data.h"
44 #include "compression.h"
46 #include "free-space-cache.h"
47 #include "inode-map.h"
53 struct btrfs_iget_args {
54 struct btrfs_key *location;
55 struct btrfs_root *root;
58 struct btrfs_dio_data {
60 u64 unsubmitted_oe_range_start;
61 u64 unsubmitted_oe_range_end;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct address_space_operations btrfs_symlink_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73 static const struct extent_io_ops btrfs_extent_io_ops;
75 static struct kmem_cache *btrfs_inode_cachep;
76 struct kmem_cache *btrfs_trans_handle_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
81 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
82 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
83 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
84 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
85 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
86 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
87 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
88 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
91 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
92 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
93 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
94 static noinline int cow_file_range(struct inode *inode,
95 struct page *locked_page,
96 u64 start, u64 end, u64 delalloc_end,
97 int *page_started, unsigned long *nr_written,
98 int unlock, struct btrfs_dedupe_hash *hash);
99 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
100 u64 orig_start, u64 block_start,
101 u64 block_len, u64 orig_block_len,
102 u64 ram_bytes, int compress_type,
105 static void __endio_write_update_ordered(struct inode *inode,
106 const u64 offset, const u64 bytes,
107 const bool uptodate);
110 * Cleanup all submitted ordered extents in specified range to handle errors
111 * from the fill_dellaloc() callback.
113 * NOTE: caller must ensure that when an error happens, it can not call
114 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
115 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
116 * to be released, which we want to happen only when finishing the ordered
117 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
118 * fill_delalloc() callback already does proper cleanup for the first page of
119 * the range, that is, it invokes the callback writepage_end_io_hook() for the
120 * range of the first page.
122 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
126 unsigned long index = offset >> PAGE_SHIFT;
127 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
130 while (index <= end_index) {
131 page = find_get_page(inode->i_mapping, index);
135 ClearPagePrivate2(page);
138 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
139 bytes - PAGE_SIZE, false);
142 static int btrfs_dirty_inode(struct inode *inode);
144 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
145 void btrfs_test_inode_set_ops(struct inode *inode)
147 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
151 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152 struct inode *inode, struct inode *dir,
153 const struct qstr *qstr)
157 err = btrfs_init_acl(trans, inode, dir);
159 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
164 * this does all the hard work for inserting an inline extent into
165 * the btree. The caller should have done a btrfs_drop_extents so that
166 * no overlapping inline items exist in the btree
168 static int insert_inline_extent(struct btrfs_trans_handle *trans,
169 struct btrfs_path *path, int extent_inserted,
170 struct btrfs_root *root, struct inode *inode,
171 u64 start, size_t size, size_t compressed_size,
173 struct page **compressed_pages)
175 struct extent_buffer *leaf;
176 struct page *page = NULL;
179 struct btrfs_file_extent_item *ei;
181 size_t cur_size = size;
182 unsigned long offset;
184 if (compressed_size && compressed_pages)
185 cur_size = compressed_size;
187 inode_add_bytes(inode, size);
189 if (!extent_inserted) {
190 struct btrfs_key key;
193 key.objectid = btrfs_ino(BTRFS_I(inode));
195 key.type = BTRFS_EXTENT_DATA_KEY;
197 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198 path->leave_spinning = 1;
199 ret = btrfs_insert_empty_item(trans, root, path, &key,
204 leaf = path->nodes[0];
205 ei = btrfs_item_ptr(leaf, path->slots[0],
206 struct btrfs_file_extent_item);
207 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209 btrfs_set_file_extent_encryption(leaf, ei, 0);
210 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212 ptr = btrfs_file_extent_inline_start(ei);
214 if (compress_type != BTRFS_COMPRESS_NONE) {
217 while (compressed_size > 0) {
218 cpage = compressed_pages[i];
219 cur_size = min_t(unsigned long, compressed_size,
222 kaddr = kmap_atomic(cpage);
223 write_extent_buffer(leaf, kaddr, ptr, cur_size);
224 kunmap_atomic(kaddr);
228 compressed_size -= cur_size;
230 btrfs_set_file_extent_compression(leaf, ei,
233 page = find_get_page(inode->i_mapping,
234 start >> PAGE_SHIFT);
235 btrfs_set_file_extent_compression(leaf, ei, 0);
236 kaddr = kmap_atomic(page);
237 offset = start & (PAGE_SIZE - 1);
238 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239 kunmap_atomic(kaddr);
242 btrfs_mark_buffer_dirty(leaf);
243 btrfs_release_path(path);
246 * we're an inline extent, so nobody can
247 * extend the file past i_size without locking
248 * a page we already have locked.
250 * We must do any isize and inode updates
251 * before we unlock the pages. Otherwise we
252 * could end up racing with unlink.
254 BTRFS_I(inode)->disk_i_size = inode->i_size;
255 ret = btrfs_update_inode(trans, root, inode);
263 * conditionally insert an inline extent into the file. This
264 * does the checks required to make sure the data is small enough
265 * to fit as an inline extent.
267 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
268 u64 end, size_t compressed_size,
270 struct page **compressed_pages)
272 struct btrfs_root *root = BTRFS_I(inode)->root;
273 struct btrfs_fs_info *fs_info = root->fs_info;
274 struct btrfs_trans_handle *trans;
275 u64 isize = i_size_read(inode);
276 u64 actual_end = min(end + 1, isize);
277 u64 inline_len = actual_end - start;
278 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
279 u64 data_len = inline_len;
281 struct btrfs_path *path;
282 int extent_inserted = 0;
283 u32 extent_item_size;
286 data_len = compressed_size;
289 actual_end > fs_info->sectorsize ||
290 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
292 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
294 data_len > fs_info->max_inline) {
298 path = btrfs_alloc_path();
302 trans = btrfs_join_transaction(root);
304 btrfs_free_path(path);
305 return PTR_ERR(trans);
307 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
309 if (compressed_size && compressed_pages)
310 extent_item_size = btrfs_file_extent_calc_inline_size(
313 extent_item_size = btrfs_file_extent_calc_inline_size(
316 ret = __btrfs_drop_extents(trans, root, inode, path,
317 start, aligned_end, NULL,
318 1, 1, extent_item_size, &extent_inserted);
320 btrfs_abort_transaction(trans, ret);
324 if (isize > actual_end)
325 inline_len = min_t(u64, isize, actual_end);
326 ret = insert_inline_extent(trans, path, extent_inserted,
328 inline_len, compressed_size,
329 compress_type, compressed_pages);
330 if (ret && ret != -ENOSPC) {
331 btrfs_abort_transaction(trans, ret);
333 } else if (ret == -ENOSPC) {
338 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
342 * Don't forget to free the reserved space, as for inlined extent
343 * it won't count as data extent, free them directly here.
344 * And at reserve time, it's always aligned to page size, so
345 * just free one page here.
347 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
348 btrfs_free_path(path);
349 btrfs_end_transaction(trans);
353 struct async_extent {
358 unsigned long nr_pages;
360 struct list_head list;
365 struct btrfs_root *root;
366 struct page *locked_page;
369 unsigned int write_flags;
370 struct list_head extents;
371 struct btrfs_work work;
374 static noinline int add_async_extent(struct async_cow *cow,
375 u64 start, u64 ram_size,
378 unsigned long nr_pages,
381 struct async_extent *async_extent;
383 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384 BUG_ON(!async_extent); /* -ENOMEM */
385 async_extent->start = start;
386 async_extent->ram_size = ram_size;
387 async_extent->compressed_size = compressed_size;
388 async_extent->pages = pages;
389 async_extent->nr_pages = nr_pages;
390 async_extent->compress_type = compress_type;
391 list_add_tail(&async_extent->list, &cow->extents);
395 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
400 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
403 if (BTRFS_I(inode)->defrag_compress)
405 /* bad compression ratios */
406 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
408 if (btrfs_test_opt(fs_info, COMPRESS) ||
409 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
410 BTRFS_I(inode)->prop_compress)
411 return btrfs_compress_heuristic(inode, start, end);
415 static inline void inode_should_defrag(struct btrfs_inode *inode,
416 u64 start, u64 end, u64 num_bytes, u64 small_write)
418 /* If this is a small write inside eof, kick off a defrag */
419 if (num_bytes < small_write &&
420 (start > 0 || end + 1 < inode->disk_i_size))
421 btrfs_add_inode_defrag(NULL, inode);
425 * we create compressed extents in two phases. The first
426 * phase compresses a range of pages that have already been
427 * locked (both pages and state bits are locked).
429 * This is done inside an ordered work queue, and the compression
430 * is spread across many cpus. The actual IO submission is step
431 * two, and the ordered work queue takes care of making sure that
432 * happens in the same order things were put onto the queue by
433 * writepages and friends.
435 * If this code finds it can't get good compression, it puts an
436 * entry onto the work queue to write the uncompressed bytes. This
437 * makes sure that both compressed inodes and uncompressed inodes
438 * are written in the same order that the flusher thread sent them
441 static noinline void compress_file_range(struct inode *inode,
442 struct page *locked_page,
444 struct async_cow *async_cow,
447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
448 u64 blocksize = fs_info->sectorsize;
450 u64 isize = i_size_read(inode);
452 struct page **pages = NULL;
453 unsigned long nr_pages;
454 unsigned long total_compressed = 0;
455 unsigned long total_in = 0;
458 int compress_type = fs_info->compress_type;
461 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
464 actual_end = min_t(u64, isize, end + 1);
467 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
468 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
469 nr_pages = min_t(unsigned long, nr_pages,
470 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
473 * we don't want to send crud past the end of i_size through
474 * compression, that's just a waste of CPU time. So, if the
475 * end of the file is before the start of our current
476 * requested range of bytes, we bail out to the uncompressed
477 * cleanup code that can deal with all of this.
479 * It isn't really the fastest way to fix things, but this is a
480 * very uncommon corner.
482 if (actual_end <= start)
483 goto cleanup_and_bail_uncompressed;
485 total_compressed = actual_end - start;
488 * skip compression for a small file range(<=blocksize) that
489 * isn't an inline extent, since it doesn't save disk space at all.
491 if (total_compressed <= blocksize &&
492 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
493 goto cleanup_and_bail_uncompressed;
495 total_compressed = min_t(unsigned long, total_compressed,
496 BTRFS_MAX_UNCOMPRESSED);
501 * we do compression for mount -o compress and when the
502 * inode has not been flagged as nocompress. This flag can
503 * change at any time if we discover bad compression ratios.
505 if (inode_need_compress(inode, start, end)) {
507 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
509 /* just bail out to the uncompressed code */
513 if (BTRFS_I(inode)->defrag_compress)
514 compress_type = BTRFS_I(inode)->defrag_compress;
515 else if (BTRFS_I(inode)->prop_compress)
516 compress_type = BTRFS_I(inode)->prop_compress;
519 * we need to call clear_page_dirty_for_io on each
520 * page in the range. Otherwise applications with the file
521 * mmap'd can wander in and change the page contents while
522 * we are compressing them.
524 * If the compression fails for any reason, we set the pages
525 * dirty again later on.
527 * Note that the remaining part is redirtied, the start pointer
528 * has moved, the end is the original one.
531 extent_range_clear_dirty_for_io(inode, start, end);
535 /* Compression level is applied here and only here */
536 ret = btrfs_compress_pages(
537 compress_type | (fs_info->compress_level << 4),
538 inode->i_mapping, start,
545 unsigned long offset = total_compressed &
547 struct page *page = pages[nr_pages - 1];
550 /* zero the tail end of the last page, we might be
551 * sending it down to disk
554 kaddr = kmap_atomic(page);
555 memset(kaddr + offset, 0,
557 kunmap_atomic(kaddr);
564 /* lets try to make an inline extent */
565 if (ret || total_in < actual_end) {
566 /* we didn't compress the entire range, try
567 * to make an uncompressed inline extent.
569 ret = cow_file_range_inline(inode, start, end, 0,
570 BTRFS_COMPRESS_NONE, NULL);
572 /* try making a compressed inline extent */
573 ret = cow_file_range_inline(inode, start, end,
575 compress_type, pages);
578 unsigned long clear_flags = EXTENT_DELALLOC |
579 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
580 EXTENT_DO_ACCOUNTING;
581 unsigned long page_error_op;
583 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
586 * inline extent creation worked or returned error,
587 * we don't need to create any more async work items.
588 * Unlock and free up our temp pages.
590 * We use DO_ACCOUNTING here because we need the
591 * delalloc_release_metadata to be done _after_ we drop
592 * our outstanding extent for clearing delalloc for this
595 extent_clear_unlock_delalloc(inode, start, end, end,
608 * we aren't doing an inline extent round the compressed size
609 * up to a block size boundary so the allocator does sane
612 total_compressed = ALIGN(total_compressed, blocksize);
615 * one last check to make sure the compression is really a
616 * win, compare the page count read with the blocks on disk,
617 * compression must free at least one sector size
619 total_in = ALIGN(total_in, PAGE_SIZE);
620 if (total_compressed + blocksize <= total_in) {
624 * The async work queues will take care of doing actual
625 * allocation on disk for these compressed pages, and
626 * will submit them to the elevator.
628 add_async_extent(async_cow, start, total_in,
629 total_compressed, pages, nr_pages,
632 if (start + total_in < end) {
643 * the compression code ran but failed to make things smaller,
644 * free any pages it allocated and our page pointer array
646 for (i = 0; i < nr_pages; i++) {
647 WARN_ON(pages[i]->mapping);
652 total_compressed = 0;
655 /* flag the file so we don't compress in the future */
656 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
657 !(BTRFS_I(inode)->prop_compress)) {
658 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
661 cleanup_and_bail_uncompressed:
663 * No compression, but we still need to write the pages in the file
664 * we've been given so far. redirty the locked page if it corresponds
665 * to our extent and set things up for the async work queue to run
666 * cow_file_range to do the normal delalloc dance.
668 if (page_offset(locked_page) >= start &&
669 page_offset(locked_page) <= end)
670 __set_page_dirty_nobuffers(locked_page);
671 /* unlocked later on in the async handlers */
674 extent_range_redirty_for_io(inode, start, end);
675 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
676 BTRFS_COMPRESS_NONE);
682 for (i = 0; i < nr_pages; i++) {
683 WARN_ON(pages[i]->mapping);
689 static void free_async_extent_pages(struct async_extent *async_extent)
693 if (!async_extent->pages)
696 for (i = 0; i < async_extent->nr_pages; i++) {
697 WARN_ON(async_extent->pages[i]->mapping);
698 put_page(async_extent->pages[i]);
700 kfree(async_extent->pages);
701 async_extent->nr_pages = 0;
702 async_extent->pages = NULL;
706 * phase two of compressed writeback. This is the ordered portion
707 * of the code, which only gets called in the order the work was
708 * queued. We walk all the async extents created by compress_file_range
709 * and send them down to the disk.
711 static noinline void submit_compressed_extents(struct inode *inode,
712 struct async_cow *async_cow)
714 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
715 struct async_extent *async_extent;
717 struct btrfs_key ins;
718 struct extent_map *em;
719 struct btrfs_root *root = BTRFS_I(inode)->root;
720 struct extent_io_tree *io_tree;
724 while (!list_empty(&async_cow->extents)) {
725 async_extent = list_entry(async_cow->extents.next,
726 struct async_extent, list);
727 list_del(&async_extent->list);
729 io_tree = &BTRFS_I(inode)->io_tree;
732 /* did the compression code fall back to uncompressed IO? */
733 if (!async_extent->pages) {
734 int page_started = 0;
735 unsigned long nr_written = 0;
737 lock_extent(io_tree, async_extent->start,
738 async_extent->start +
739 async_extent->ram_size - 1);
741 /* allocate blocks */
742 ret = cow_file_range(inode, async_cow->locked_page,
744 async_extent->start +
745 async_extent->ram_size - 1,
746 async_extent->start +
747 async_extent->ram_size - 1,
748 &page_started, &nr_written, 0,
754 * if page_started, cow_file_range inserted an
755 * inline extent and took care of all the unlocking
756 * and IO for us. Otherwise, we need to submit
757 * all those pages down to the drive.
759 if (!page_started && !ret)
760 extent_write_locked_range(inode,
762 async_extent->start +
763 async_extent->ram_size - 1,
766 unlock_page(async_cow->locked_page);
772 lock_extent(io_tree, async_extent->start,
773 async_extent->start + async_extent->ram_size - 1);
775 ret = btrfs_reserve_extent(root, async_extent->ram_size,
776 async_extent->compressed_size,
777 async_extent->compressed_size,
778 0, alloc_hint, &ins, 1, 1);
780 free_async_extent_pages(async_extent);
782 if (ret == -ENOSPC) {
783 unlock_extent(io_tree, async_extent->start,
784 async_extent->start +
785 async_extent->ram_size - 1);
788 * we need to redirty the pages if we decide to
789 * fallback to uncompressed IO, otherwise we
790 * will not submit these pages down to lower
793 extent_range_redirty_for_io(inode,
795 async_extent->start +
796 async_extent->ram_size - 1);
803 * here we're doing allocation and writeback of the
806 em = create_io_em(inode, async_extent->start,
807 async_extent->ram_size, /* len */
808 async_extent->start, /* orig_start */
809 ins.objectid, /* block_start */
810 ins.offset, /* block_len */
811 ins.offset, /* orig_block_len */
812 async_extent->ram_size, /* ram_bytes */
813 async_extent->compress_type,
814 BTRFS_ORDERED_COMPRESSED);
816 /* ret value is not necessary due to void function */
817 goto out_free_reserve;
820 ret = btrfs_add_ordered_extent_compress(inode,
823 async_extent->ram_size,
825 BTRFS_ORDERED_COMPRESSED,
826 async_extent->compress_type);
828 btrfs_drop_extent_cache(BTRFS_I(inode),
830 async_extent->start +
831 async_extent->ram_size - 1, 0);
832 goto out_free_reserve;
834 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
837 * clear dirty, set writeback and unlock the pages.
839 extent_clear_unlock_delalloc(inode, async_extent->start,
840 async_extent->start +
841 async_extent->ram_size - 1,
842 async_extent->start +
843 async_extent->ram_size - 1,
844 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
845 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
847 if (btrfs_submit_compressed_write(inode,
849 async_extent->ram_size,
851 ins.offset, async_extent->pages,
852 async_extent->nr_pages,
853 async_cow->write_flags)) {
854 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
855 struct page *p = async_extent->pages[0];
856 const u64 start = async_extent->start;
857 const u64 end = start + async_extent->ram_size - 1;
859 p->mapping = inode->i_mapping;
860 tree->ops->writepage_end_io_hook(p, start, end,
863 extent_clear_unlock_delalloc(inode, start, end, end,
867 free_async_extent_pages(async_extent);
869 alloc_hint = ins.objectid + ins.offset;
875 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
878 extent_clear_unlock_delalloc(inode, async_extent->start,
879 async_extent->start +
880 async_extent->ram_size - 1,
881 async_extent->start +
882 async_extent->ram_size - 1,
883 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
884 EXTENT_DELALLOC_NEW |
885 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
886 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
887 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
889 free_async_extent_pages(async_extent);
894 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
897 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
898 struct extent_map *em;
901 read_lock(&em_tree->lock);
902 em = search_extent_mapping(em_tree, start, num_bytes);
905 * if block start isn't an actual block number then find the
906 * first block in this inode and use that as a hint. If that
907 * block is also bogus then just don't worry about it.
909 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
911 em = search_extent_mapping(em_tree, 0, 0);
912 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
913 alloc_hint = em->block_start;
917 alloc_hint = em->block_start;
921 read_unlock(&em_tree->lock);
927 * when extent_io.c finds a delayed allocation range in the file,
928 * the call backs end up in this code. The basic idea is to
929 * allocate extents on disk for the range, and create ordered data structs
930 * in ram to track those extents.
932 * locked_page is the page that writepage had locked already. We use
933 * it to make sure we don't do extra locks or unlocks.
935 * *page_started is set to one if we unlock locked_page and do everything
936 * required to start IO on it. It may be clean and already done with
939 static noinline int cow_file_range(struct inode *inode,
940 struct page *locked_page,
941 u64 start, u64 end, u64 delalloc_end,
942 int *page_started, unsigned long *nr_written,
943 int unlock, struct btrfs_dedupe_hash *hash)
945 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
946 struct btrfs_root *root = BTRFS_I(inode)->root;
949 unsigned long ram_size;
950 u64 cur_alloc_size = 0;
951 u64 blocksize = fs_info->sectorsize;
952 struct btrfs_key ins;
953 struct extent_map *em;
955 unsigned long page_ops;
956 bool extent_reserved = false;
959 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
965 num_bytes = ALIGN(end - start + 1, blocksize);
966 num_bytes = max(blocksize, num_bytes);
967 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
969 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
972 /* lets try to make an inline extent */
973 ret = cow_file_range_inline(inode, start, end, 0,
974 BTRFS_COMPRESS_NONE, NULL);
977 * We use DO_ACCOUNTING here because we need the
978 * delalloc_release_metadata to be run _after_ we drop
979 * our outstanding extent for clearing delalloc for this
982 extent_clear_unlock_delalloc(inode, start, end,
984 EXTENT_LOCKED | EXTENT_DELALLOC |
985 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
986 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
987 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
989 *nr_written = *nr_written +
990 (end - start + PAGE_SIZE) / PAGE_SIZE;
993 } else if (ret < 0) {
998 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
999 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1000 start + num_bytes - 1, 0);
1002 while (num_bytes > 0) {
1003 cur_alloc_size = num_bytes;
1004 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1005 fs_info->sectorsize, 0, alloc_hint,
1009 cur_alloc_size = ins.offset;
1010 extent_reserved = true;
1012 ram_size = ins.offset;
1013 em = create_io_em(inode, start, ins.offset, /* len */
1014 start, /* orig_start */
1015 ins.objectid, /* block_start */
1016 ins.offset, /* block_len */
1017 ins.offset, /* orig_block_len */
1018 ram_size, /* ram_bytes */
1019 BTRFS_COMPRESS_NONE, /* compress_type */
1020 BTRFS_ORDERED_REGULAR /* type */);
1025 free_extent_map(em);
1027 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1028 ram_size, cur_alloc_size, 0);
1030 goto out_drop_extent_cache;
1032 if (root->root_key.objectid ==
1033 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1034 ret = btrfs_reloc_clone_csums(inode, start,
1037 * Only drop cache here, and process as normal.
1039 * We must not allow extent_clear_unlock_delalloc()
1040 * at out_unlock label to free meta of this ordered
1041 * extent, as its meta should be freed by
1042 * btrfs_finish_ordered_io().
1044 * So we must continue until @start is increased to
1045 * skip current ordered extent.
1048 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1049 start + ram_size - 1, 0);
1052 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1054 /* we're not doing compressed IO, don't unlock the first
1055 * page (which the caller expects to stay locked), don't
1056 * clear any dirty bits and don't set any writeback bits
1058 * Do set the Private2 bit so we know this page was properly
1059 * setup for writepage
1061 page_ops = unlock ? PAGE_UNLOCK : 0;
1062 page_ops |= PAGE_SET_PRIVATE2;
1064 extent_clear_unlock_delalloc(inode, start,
1065 start + ram_size - 1,
1066 delalloc_end, locked_page,
1067 EXTENT_LOCKED | EXTENT_DELALLOC,
1069 if (num_bytes < cur_alloc_size)
1072 num_bytes -= cur_alloc_size;
1073 alloc_hint = ins.objectid + ins.offset;
1074 start += cur_alloc_size;
1075 extent_reserved = false;
1078 * btrfs_reloc_clone_csums() error, since start is increased
1079 * extent_clear_unlock_delalloc() at out_unlock label won't
1080 * free metadata of current ordered extent, we're OK to exit.
1088 out_drop_extent_cache:
1089 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1091 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1092 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1094 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1095 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1096 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1099 * If we reserved an extent for our delalloc range (or a subrange) and
1100 * failed to create the respective ordered extent, then it means that
1101 * when we reserved the extent we decremented the extent's size from
1102 * the data space_info's bytes_may_use counter and incremented the
1103 * space_info's bytes_reserved counter by the same amount. We must make
1104 * sure extent_clear_unlock_delalloc() does not try to decrement again
1105 * the data space_info's bytes_may_use counter, therefore we do not pass
1106 * it the flag EXTENT_CLEAR_DATA_RESV.
1108 if (extent_reserved) {
1109 extent_clear_unlock_delalloc(inode, start,
1110 start + cur_alloc_size,
1111 start + cur_alloc_size,
1115 start += cur_alloc_size;
1119 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1121 clear_bits | EXTENT_CLEAR_DATA_RESV,
1127 * work queue call back to started compression on a file and pages
1129 static noinline void async_cow_start(struct btrfs_work *work)
1131 struct async_cow *async_cow;
1133 async_cow = container_of(work, struct async_cow, work);
1135 compress_file_range(async_cow->inode, async_cow->locked_page,
1136 async_cow->start, async_cow->end, async_cow,
1138 if (num_added == 0) {
1139 btrfs_add_delayed_iput(async_cow->inode);
1140 async_cow->inode = NULL;
1145 * work queue call back to submit previously compressed pages
1147 static noinline void async_cow_submit(struct btrfs_work *work)
1149 struct btrfs_fs_info *fs_info;
1150 struct async_cow *async_cow;
1151 struct btrfs_root *root;
1152 unsigned long nr_pages;
1154 async_cow = container_of(work, struct async_cow, work);
1156 root = async_cow->root;
1157 fs_info = root->fs_info;
1158 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1161 /* atomic_sub_return implies a barrier */
1162 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1164 cond_wake_up_nomb(&fs_info->async_submit_wait);
1166 if (async_cow->inode)
1167 submit_compressed_extents(async_cow->inode, async_cow);
1170 static noinline void async_cow_free(struct btrfs_work *work)
1172 struct async_cow *async_cow;
1173 async_cow = container_of(work, struct async_cow, work);
1174 if (async_cow->inode)
1175 btrfs_add_delayed_iput(async_cow->inode);
1179 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1180 u64 start, u64 end, int *page_started,
1181 unsigned long *nr_written,
1182 unsigned int write_flags)
1184 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1185 struct async_cow *async_cow;
1186 struct btrfs_root *root = BTRFS_I(inode)->root;
1187 unsigned long nr_pages;
1190 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1192 while (start < end) {
1193 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1194 BUG_ON(!async_cow); /* -ENOMEM */
1195 async_cow->inode = igrab(inode);
1196 async_cow->root = root;
1197 async_cow->locked_page = locked_page;
1198 async_cow->start = start;
1199 async_cow->write_flags = write_flags;
1201 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1202 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1205 cur_end = min(end, start + SZ_512K - 1);
1207 async_cow->end = cur_end;
1208 INIT_LIST_HEAD(&async_cow->extents);
1210 btrfs_init_work(&async_cow->work,
1211 btrfs_delalloc_helper,
1212 async_cow_start, async_cow_submit,
1215 nr_pages = (cur_end - start + PAGE_SIZE) >>
1217 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1219 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1221 *nr_written += nr_pages;
1222 start = cur_end + 1;
1228 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1229 u64 bytenr, u64 num_bytes)
1232 struct btrfs_ordered_sum *sums;
1235 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1236 bytenr + num_bytes - 1, &list, 0);
1237 if (ret == 0 && list_empty(&list))
1240 while (!list_empty(&list)) {
1241 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1242 list_del(&sums->list);
1251 * when nowcow writeback call back. This checks for snapshots or COW copies
1252 * of the extents that exist in the file, and COWs the file as required.
1254 * If no cow copies or snapshots exist, we write directly to the existing
1257 static noinline int run_delalloc_nocow(struct inode *inode,
1258 struct page *locked_page,
1259 u64 start, u64 end, int *page_started, int force,
1260 unsigned long *nr_written)
1262 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1263 struct btrfs_root *root = BTRFS_I(inode)->root;
1264 struct extent_buffer *leaf;
1265 struct btrfs_path *path;
1266 struct btrfs_file_extent_item *fi;
1267 struct btrfs_key found_key;
1268 struct extent_map *em;
1283 u64 ino = btrfs_ino(BTRFS_I(inode));
1285 path = btrfs_alloc_path();
1287 extent_clear_unlock_delalloc(inode, start, end, end,
1289 EXTENT_LOCKED | EXTENT_DELALLOC |
1290 EXTENT_DO_ACCOUNTING |
1291 EXTENT_DEFRAG, PAGE_UNLOCK |
1293 PAGE_SET_WRITEBACK |
1294 PAGE_END_WRITEBACK);
1298 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1300 cow_start = (u64)-1;
1303 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1307 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1308 leaf = path->nodes[0];
1309 btrfs_item_key_to_cpu(leaf, &found_key,
1310 path->slots[0] - 1);
1311 if (found_key.objectid == ino &&
1312 found_key.type == BTRFS_EXTENT_DATA_KEY)
1317 leaf = path->nodes[0];
1318 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1319 ret = btrfs_next_leaf(root, path);
1321 if (cow_start != (u64)-1)
1322 cur_offset = cow_start;
1327 leaf = path->nodes[0];
1333 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1335 if (found_key.objectid > ino)
1337 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1338 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1342 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1343 found_key.offset > end)
1346 if (found_key.offset > cur_offset) {
1347 extent_end = found_key.offset;
1352 fi = btrfs_item_ptr(leaf, path->slots[0],
1353 struct btrfs_file_extent_item);
1354 extent_type = btrfs_file_extent_type(leaf, fi);
1356 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1357 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1358 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1359 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1360 extent_offset = btrfs_file_extent_offset(leaf, fi);
1361 extent_end = found_key.offset +
1362 btrfs_file_extent_num_bytes(leaf, fi);
1364 btrfs_file_extent_disk_num_bytes(leaf, fi);
1365 if (extent_end <= start) {
1369 if (disk_bytenr == 0)
1371 if (btrfs_file_extent_compression(leaf, fi) ||
1372 btrfs_file_extent_encryption(leaf, fi) ||
1373 btrfs_file_extent_other_encoding(leaf, fi))
1376 * Do the same check as in btrfs_cross_ref_exist but
1377 * without the unnecessary search.
1379 if (btrfs_file_extent_generation(leaf, fi) <=
1380 btrfs_root_last_snapshot(&root->root_item))
1382 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1384 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1386 ret = btrfs_cross_ref_exist(root, ino,
1388 extent_offset, disk_bytenr);
1391 * ret could be -EIO if the above fails to read
1395 if (cow_start != (u64)-1)
1396 cur_offset = cow_start;
1400 WARN_ON_ONCE(nolock);
1403 disk_bytenr += extent_offset;
1404 disk_bytenr += cur_offset - found_key.offset;
1405 num_bytes = min(end + 1, extent_end) - cur_offset;
1407 * if there are pending snapshots for this root,
1408 * we fall into common COW way.
1411 err = btrfs_start_write_no_snapshotting(root);
1416 * force cow if csum exists in the range.
1417 * this ensure that csum for a given extent are
1418 * either valid or do not exist.
1420 ret = csum_exist_in_range(fs_info, disk_bytenr,
1424 btrfs_end_write_no_snapshotting(root);
1427 * ret could be -EIO if the above fails to read
1431 if (cow_start != (u64)-1)
1432 cur_offset = cow_start;
1435 WARN_ON_ONCE(nolock);
1438 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1440 btrfs_end_write_no_snapshotting(root);
1444 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1445 extent_end = found_key.offset +
1446 btrfs_file_extent_inline_len(leaf,
1447 path->slots[0], fi);
1448 extent_end = ALIGN(extent_end,
1449 fs_info->sectorsize);
1454 if (extent_end <= start) {
1456 if (!nolock && nocow)
1457 btrfs_end_write_no_snapshotting(root);
1459 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1463 if (cow_start == (u64)-1)
1464 cow_start = cur_offset;
1465 cur_offset = extent_end;
1466 if (cur_offset > end)
1472 btrfs_release_path(path);
1473 if (cow_start != (u64)-1) {
1474 ret = cow_file_range(inode, locked_page,
1475 cow_start, found_key.offset - 1,
1476 end, page_started, nr_written, 1,
1479 if (!nolock && nocow)
1480 btrfs_end_write_no_snapshotting(root);
1482 btrfs_dec_nocow_writers(fs_info,
1486 cow_start = (u64)-1;
1489 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1490 u64 orig_start = found_key.offset - extent_offset;
1492 em = create_io_em(inode, cur_offset, num_bytes,
1494 disk_bytenr, /* block_start */
1495 num_bytes, /* block_len */
1496 disk_num_bytes, /* orig_block_len */
1497 ram_bytes, BTRFS_COMPRESS_NONE,
1498 BTRFS_ORDERED_PREALLOC);
1500 if (!nolock && nocow)
1501 btrfs_end_write_no_snapshotting(root);
1503 btrfs_dec_nocow_writers(fs_info,
1508 free_extent_map(em);
1511 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1512 type = BTRFS_ORDERED_PREALLOC;
1514 type = BTRFS_ORDERED_NOCOW;
1517 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1518 num_bytes, num_bytes, type);
1520 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1521 BUG_ON(ret); /* -ENOMEM */
1523 if (root->root_key.objectid ==
1524 BTRFS_DATA_RELOC_TREE_OBJECTID)
1526 * Error handled later, as we must prevent
1527 * extent_clear_unlock_delalloc() in error handler
1528 * from freeing metadata of created ordered extent.
1530 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1533 extent_clear_unlock_delalloc(inode, cur_offset,
1534 cur_offset + num_bytes - 1, end,
1535 locked_page, EXTENT_LOCKED |
1537 EXTENT_CLEAR_DATA_RESV,
1538 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1540 if (!nolock && nocow)
1541 btrfs_end_write_no_snapshotting(root);
1542 cur_offset = extent_end;
1545 * btrfs_reloc_clone_csums() error, now we're OK to call error
1546 * handler, as metadata for created ordered extent will only
1547 * be freed by btrfs_finish_ordered_io().
1551 if (cur_offset > end)
1554 btrfs_release_path(path);
1556 if (cur_offset <= end && cow_start == (u64)-1) {
1557 cow_start = cur_offset;
1561 if (cow_start != (u64)-1) {
1562 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1563 page_started, nr_written, 1, NULL);
1569 if (ret && cur_offset < end)
1570 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1571 locked_page, EXTENT_LOCKED |
1572 EXTENT_DELALLOC | EXTENT_DEFRAG |
1573 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1575 PAGE_SET_WRITEBACK |
1576 PAGE_END_WRITEBACK);
1577 btrfs_free_path(path);
1581 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1584 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1585 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1589 * @defrag_bytes is a hint value, no spinlock held here,
1590 * if is not zero, it means the file is defragging.
1591 * Force cow if given extent needs to be defragged.
1593 if (BTRFS_I(inode)->defrag_bytes &&
1594 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1595 EXTENT_DEFRAG, 0, NULL))
1602 * extent_io.c call back to do delayed allocation processing
1604 static int run_delalloc_range(void *private_data, struct page *locked_page,
1605 u64 start, u64 end, int *page_started,
1606 unsigned long *nr_written,
1607 struct writeback_control *wbc)
1609 struct inode *inode = private_data;
1611 int force_cow = need_force_cow(inode, start, end);
1612 unsigned int write_flags = wbc_to_write_flags(wbc);
1614 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1615 ret = run_delalloc_nocow(inode, locked_page, start, end,
1616 page_started, 1, nr_written);
1617 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1618 ret = run_delalloc_nocow(inode, locked_page, start, end,
1619 page_started, 0, nr_written);
1620 } else if (!inode_need_compress(inode, start, end)) {
1621 ret = cow_file_range(inode, locked_page, start, end, end,
1622 page_started, nr_written, 1, NULL);
1624 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1625 &BTRFS_I(inode)->runtime_flags);
1626 ret = cow_file_range_async(inode, locked_page, start, end,
1627 page_started, nr_written,
1631 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1635 static void btrfs_split_extent_hook(void *private_data,
1636 struct extent_state *orig, u64 split)
1638 struct inode *inode = private_data;
1641 /* not delalloc, ignore it */
1642 if (!(orig->state & EXTENT_DELALLOC))
1645 size = orig->end - orig->start + 1;
1646 if (size > BTRFS_MAX_EXTENT_SIZE) {
1651 * See the explanation in btrfs_merge_extent_hook, the same
1652 * applies here, just in reverse.
1654 new_size = orig->end - split + 1;
1655 num_extents = count_max_extents(new_size);
1656 new_size = split - orig->start;
1657 num_extents += count_max_extents(new_size);
1658 if (count_max_extents(size) >= num_extents)
1662 spin_lock(&BTRFS_I(inode)->lock);
1663 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1664 spin_unlock(&BTRFS_I(inode)->lock);
1668 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1669 * extents so we can keep track of new extents that are just merged onto old
1670 * extents, such as when we are doing sequential writes, so we can properly
1671 * account for the metadata space we'll need.
1673 static void btrfs_merge_extent_hook(void *private_data,
1674 struct extent_state *new,
1675 struct extent_state *other)
1677 struct inode *inode = private_data;
1678 u64 new_size, old_size;
1681 /* not delalloc, ignore it */
1682 if (!(other->state & EXTENT_DELALLOC))
1685 if (new->start > other->start)
1686 new_size = new->end - other->start + 1;
1688 new_size = other->end - new->start + 1;
1690 /* we're not bigger than the max, unreserve the space and go */
1691 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1692 spin_lock(&BTRFS_I(inode)->lock);
1693 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1694 spin_unlock(&BTRFS_I(inode)->lock);
1699 * We have to add up either side to figure out how many extents were
1700 * accounted for before we merged into one big extent. If the number of
1701 * extents we accounted for is <= the amount we need for the new range
1702 * then we can return, otherwise drop. Think of it like this
1706 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1707 * need 2 outstanding extents, on one side we have 1 and the other side
1708 * we have 1 so they are == and we can return. But in this case
1710 * [MAX_SIZE+4k][MAX_SIZE+4k]
1712 * Each range on their own accounts for 2 extents, but merged together
1713 * they are only 3 extents worth of accounting, so we need to drop in
1716 old_size = other->end - other->start + 1;
1717 num_extents = count_max_extents(old_size);
1718 old_size = new->end - new->start + 1;
1719 num_extents += count_max_extents(old_size);
1720 if (count_max_extents(new_size) >= num_extents)
1723 spin_lock(&BTRFS_I(inode)->lock);
1724 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1725 spin_unlock(&BTRFS_I(inode)->lock);
1728 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1729 struct inode *inode)
1731 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1733 spin_lock(&root->delalloc_lock);
1734 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1735 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1736 &root->delalloc_inodes);
1737 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1738 &BTRFS_I(inode)->runtime_flags);
1739 root->nr_delalloc_inodes++;
1740 if (root->nr_delalloc_inodes == 1) {
1741 spin_lock(&fs_info->delalloc_root_lock);
1742 BUG_ON(!list_empty(&root->delalloc_root));
1743 list_add_tail(&root->delalloc_root,
1744 &fs_info->delalloc_roots);
1745 spin_unlock(&fs_info->delalloc_root_lock);
1748 spin_unlock(&root->delalloc_lock);
1752 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1753 struct btrfs_inode *inode)
1755 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1757 if (!list_empty(&inode->delalloc_inodes)) {
1758 list_del_init(&inode->delalloc_inodes);
1759 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1760 &inode->runtime_flags);
1761 root->nr_delalloc_inodes--;
1762 if (!root->nr_delalloc_inodes) {
1763 ASSERT(list_empty(&root->delalloc_inodes));
1764 spin_lock(&fs_info->delalloc_root_lock);
1765 BUG_ON(list_empty(&root->delalloc_root));
1766 list_del_init(&root->delalloc_root);
1767 spin_unlock(&fs_info->delalloc_root_lock);
1772 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1773 struct btrfs_inode *inode)
1775 spin_lock(&root->delalloc_lock);
1776 __btrfs_del_delalloc_inode(root, inode);
1777 spin_unlock(&root->delalloc_lock);
1781 * extent_io.c set_bit_hook, used to track delayed allocation
1782 * bytes in this file, and to maintain the list of inodes that
1783 * have pending delalloc work to be done.
1785 static void btrfs_set_bit_hook(void *private_data,
1786 struct extent_state *state, unsigned *bits)
1788 struct inode *inode = private_data;
1790 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1792 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1795 * set_bit and clear bit hooks normally require _irqsave/restore
1796 * but in this case, we are only testing for the DELALLOC
1797 * bit, which is only set or cleared with irqs on
1799 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1800 struct btrfs_root *root = BTRFS_I(inode)->root;
1801 u64 len = state->end + 1 - state->start;
1802 u32 num_extents = count_max_extents(len);
1803 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1805 spin_lock(&BTRFS_I(inode)->lock);
1806 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1807 spin_unlock(&BTRFS_I(inode)->lock);
1809 /* For sanity tests */
1810 if (btrfs_is_testing(fs_info))
1813 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1814 fs_info->delalloc_batch);
1815 spin_lock(&BTRFS_I(inode)->lock);
1816 BTRFS_I(inode)->delalloc_bytes += len;
1817 if (*bits & EXTENT_DEFRAG)
1818 BTRFS_I(inode)->defrag_bytes += len;
1819 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1820 &BTRFS_I(inode)->runtime_flags))
1821 btrfs_add_delalloc_inodes(root, inode);
1822 spin_unlock(&BTRFS_I(inode)->lock);
1825 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1826 (*bits & EXTENT_DELALLOC_NEW)) {
1827 spin_lock(&BTRFS_I(inode)->lock);
1828 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1830 spin_unlock(&BTRFS_I(inode)->lock);
1835 * extent_io.c clear_bit_hook, see set_bit_hook for why
1837 static void btrfs_clear_bit_hook(void *private_data,
1838 struct extent_state *state,
1841 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1842 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1843 u64 len = state->end + 1 - state->start;
1844 u32 num_extents = count_max_extents(len);
1846 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1847 spin_lock(&inode->lock);
1848 inode->defrag_bytes -= len;
1849 spin_unlock(&inode->lock);
1853 * set_bit and clear bit hooks normally require _irqsave/restore
1854 * but in this case, we are only testing for the DELALLOC
1855 * bit, which is only set or cleared with irqs on
1857 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1858 struct btrfs_root *root = inode->root;
1859 bool do_list = !btrfs_is_free_space_inode(inode);
1861 spin_lock(&inode->lock);
1862 btrfs_mod_outstanding_extents(inode, -num_extents);
1863 spin_unlock(&inode->lock);
1866 * We don't reserve metadata space for space cache inodes so we
1867 * don't need to call dellalloc_release_metadata if there is an
1870 if (*bits & EXTENT_CLEAR_META_RESV &&
1871 root != fs_info->tree_root)
1872 btrfs_delalloc_release_metadata(inode, len, false);
1874 /* For sanity tests. */
1875 if (btrfs_is_testing(fs_info))
1878 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1879 do_list && !(state->state & EXTENT_NORESERVE) &&
1880 (*bits & EXTENT_CLEAR_DATA_RESV))
1881 btrfs_free_reserved_data_space_noquota(
1885 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1886 fs_info->delalloc_batch);
1887 spin_lock(&inode->lock);
1888 inode->delalloc_bytes -= len;
1889 if (do_list && inode->delalloc_bytes == 0 &&
1890 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1891 &inode->runtime_flags))
1892 btrfs_del_delalloc_inode(root, inode);
1893 spin_unlock(&inode->lock);
1896 if ((state->state & EXTENT_DELALLOC_NEW) &&
1897 (*bits & EXTENT_DELALLOC_NEW)) {
1898 spin_lock(&inode->lock);
1899 ASSERT(inode->new_delalloc_bytes >= len);
1900 inode->new_delalloc_bytes -= len;
1901 spin_unlock(&inode->lock);
1906 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1907 * we don't create bios that span stripes or chunks
1909 * return 1 if page cannot be merged to bio
1910 * return 0 if page can be merged to bio
1911 * return error otherwise
1913 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1914 size_t size, struct bio *bio,
1915 unsigned long bio_flags)
1917 struct inode *inode = page->mapping->host;
1918 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1919 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1924 if (bio_flags & EXTENT_BIO_COMPRESSED)
1927 length = bio->bi_iter.bi_size;
1928 map_length = length;
1929 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1933 if (map_length < length + size)
1939 * in order to insert checksums into the metadata in large chunks,
1940 * we wait until bio submission time. All the pages in the bio are
1941 * checksummed and sums are attached onto the ordered extent record.
1943 * At IO completion time the cums attached on the ordered extent record
1944 * are inserted into the btree
1946 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1949 struct inode *inode = private_data;
1950 blk_status_t ret = 0;
1952 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1953 BUG_ON(ret); /* -ENOMEM */
1958 * in order to insert checksums into the metadata in large chunks,
1959 * we wait until bio submission time. All the pages in the bio are
1960 * checksummed and sums are attached onto the ordered extent record.
1962 * At IO completion time the cums attached on the ordered extent record
1963 * are inserted into the btree
1965 static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1968 struct inode *inode = private_data;
1969 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1972 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1974 bio->bi_status = ret;
1981 * extent_io.c submission hook. This does the right thing for csum calculation
1982 * on write, or reading the csums from the tree before a read.
1984 * Rules about async/sync submit,
1985 * a) read: sync submit
1987 * b) write without checksum: sync submit
1989 * c) write with checksum:
1990 * c-1) if bio is issued by fsync: sync submit
1991 * (sync_writers != 0)
1993 * c-2) if root is reloc root: sync submit
1994 * (only in case of buffered IO)
1996 * c-3) otherwise: async submit
1998 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1999 int mirror_num, unsigned long bio_flags,
2002 struct inode *inode = private_data;
2003 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2004 struct btrfs_root *root = BTRFS_I(inode)->root;
2005 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2006 blk_status_t ret = 0;
2008 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2010 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2012 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2013 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2015 if (bio_op(bio) != REQ_OP_WRITE) {
2016 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2020 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2021 ret = btrfs_submit_compressed_read(inode, bio,
2025 } else if (!skip_sum) {
2026 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2031 } else if (async && !skip_sum) {
2032 /* csum items have already been cloned */
2033 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2035 /* we're doing a write, do the async checksumming */
2036 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2038 btrfs_submit_bio_start,
2039 btrfs_submit_bio_done);
2041 } else if (!skip_sum) {
2042 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2048 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2052 bio->bi_status = ret;
2059 * given a list of ordered sums record them in the inode. This happens
2060 * at IO completion time based on sums calculated at bio submission time.
2062 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2063 struct inode *inode, struct list_head *list)
2065 struct btrfs_ordered_sum *sum;
2068 list_for_each_entry(sum, list, list) {
2069 trans->adding_csums = true;
2070 ret = btrfs_csum_file_blocks(trans,
2071 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2072 trans->adding_csums = false;
2079 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2080 unsigned int extra_bits,
2081 struct extent_state **cached_state, int dedupe)
2083 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2084 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2085 extra_bits, cached_state);
2088 /* see btrfs_writepage_start_hook for details on why this is required */
2089 struct btrfs_writepage_fixup {
2091 struct btrfs_work work;
2094 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2096 struct btrfs_writepage_fixup *fixup;
2097 struct btrfs_ordered_extent *ordered;
2098 struct extent_state *cached_state = NULL;
2099 struct extent_changeset *data_reserved = NULL;
2101 struct inode *inode;
2106 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2110 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2111 ClearPageChecked(page);
2115 inode = page->mapping->host;
2116 page_start = page_offset(page);
2117 page_end = page_offset(page) + PAGE_SIZE - 1;
2119 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2122 /* already ordered? We're done */
2123 if (PagePrivate2(page))
2126 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2129 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2130 page_end, &cached_state);
2132 btrfs_start_ordered_extent(inode, ordered, 1);
2133 btrfs_put_ordered_extent(ordered);
2137 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2140 mapping_set_error(page->mapping, ret);
2141 end_extent_writepage(page, ret, page_start, page_end);
2142 ClearPageChecked(page);
2146 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2149 mapping_set_error(page->mapping, ret);
2150 end_extent_writepage(page, ret, page_start, page_end);
2151 ClearPageChecked(page);
2155 ClearPageChecked(page);
2156 set_page_dirty(page);
2157 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2159 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2165 extent_changeset_free(data_reserved);
2169 * There are a few paths in the higher layers of the kernel that directly
2170 * set the page dirty bit without asking the filesystem if it is a
2171 * good idea. This causes problems because we want to make sure COW
2172 * properly happens and the data=ordered rules are followed.
2174 * In our case any range that doesn't have the ORDERED bit set
2175 * hasn't been properly setup for IO. We kick off an async process
2176 * to fix it up. The async helper will wait for ordered extents, set
2177 * the delalloc bit and make it safe to write the page.
2179 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2181 struct inode *inode = page->mapping->host;
2182 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2183 struct btrfs_writepage_fixup *fixup;
2185 /* this page is properly in the ordered list */
2186 if (TestClearPagePrivate2(page))
2189 if (PageChecked(page))
2192 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2196 SetPageChecked(page);
2198 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2199 btrfs_writepage_fixup_worker, NULL, NULL);
2201 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2205 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2206 struct inode *inode, u64 file_pos,
2207 u64 disk_bytenr, u64 disk_num_bytes,
2208 u64 num_bytes, u64 ram_bytes,
2209 u8 compression, u8 encryption,
2210 u16 other_encoding, int extent_type)
2212 struct btrfs_root *root = BTRFS_I(inode)->root;
2213 struct btrfs_file_extent_item *fi;
2214 struct btrfs_path *path;
2215 struct extent_buffer *leaf;
2216 struct btrfs_key ins;
2218 int extent_inserted = 0;
2221 path = btrfs_alloc_path();
2226 * we may be replacing one extent in the tree with another.
2227 * The new extent is pinned in the extent map, and we don't want
2228 * to drop it from the cache until it is completely in the btree.
2230 * So, tell btrfs_drop_extents to leave this extent in the cache.
2231 * the caller is expected to unpin it and allow it to be merged
2234 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2235 file_pos + num_bytes, NULL, 0,
2236 1, sizeof(*fi), &extent_inserted);
2240 if (!extent_inserted) {
2241 ins.objectid = btrfs_ino(BTRFS_I(inode));
2242 ins.offset = file_pos;
2243 ins.type = BTRFS_EXTENT_DATA_KEY;
2245 path->leave_spinning = 1;
2246 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2251 leaf = path->nodes[0];
2252 fi = btrfs_item_ptr(leaf, path->slots[0],
2253 struct btrfs_file_extent_item);
2254 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2255 btrfs_set_file_extent_type(leaf, fi, extent_type);
2256 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2257 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2258 btrfs_set_file_extent_offset(leaf, fi, 0);
2259 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2260 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2261 btrfs_set_file_extent_compression(leaf, fi, compression);
2262 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2263 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2265 btrfs_mark_buffer_dirty(leaf);
2266 btrfs_release_path(path);
2268 inode_add_bytes(inode, num_bytes);
2270 ins.objectid = disk_bytenr;
2271 ins.offset = disk_num_bytes;
2272 ins.type = BTRFS_EXTENT_ITEM_KEY;
2275 * Release the reserved range from inode dirty range map, as it is
2276 * already moved into delayed_ref_head
2278 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2282 ret = btrfs_alloc_reserved_file_extent(trans, root,
2283 btrfs_ino(BTRFS_I(inode)),
2284 file_pos, qg_released, &ins);
2286 btrfs_free_path(path);
2291 /* snapshot-aware defrag */
2292 struct sa_defrag_extent_backref {
2293 struct rb_node node;
2294 struct old_sa_defrag_extent *old;
2303 struct old_sa_defrag_extent {
2304 struct list_head list;
2305 struct new_sa_defrag_extent *new;
2314 struct new_sa_defrag_extent {
2315 struct rb_root root;
2316 struct list_head head;
2317 struct btrfs_path *path;
2318 struct inode *inode;
2326 static int backref_comp(struct sa_defrag_extent_backref *b1,
2327 struct sa_defrag_extent_backref *b2)
2329 if (b1->root_id < b2->root_id)
2331 else if (b1->root_id > b2->root_id)
2334 if (b1->inum < b2->inum)
2336 else if (b1->inum > b2->inum)
2339 if (b1->file_pos < b2->file_pos)
2341 else if (b1->file_pos > b2->file_pos)
2345 * [------------------------------] ===> (a range of space)
2346 * |<--->| |<---->| =============> (fs/file tree A)
2347 * |<---------------------------->| ===> (fs/file tree B)
2349 * A range of space can refer to two file extents in one tree while
2350 * refer to only one file extent in another tree.
2352 * So we may process a disk offset more than one time(two extents in A)
2353 * and locate at the same extent(one extent in B), then insert two same
2354 * backrefs(both refer to the extent in B).
2359 static void backref_insert(struct rb_root *root,
2360 struct sa_defrag_extent_backref *backref)
2362 struct rb_node **p = &root->rb_node;
2363 struct rb_node *parent = NULL;
2364 struct sa_defrag_extent_backref *entry;
2369 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2371 ret = backref_comp(backref, entry);
2375 p = &(*p)->rb_right;
2378 rb_link_node(&backref->node, parent, p);
2379 rb_insert_color(&backref->node, root);
2383 * Note the backref might has changed, and in this case we just return 0.
2385 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2388 struct btrfs_file_extent_item *extent;
2389 struct old_sa_defrag_extent *old = ctx;
2390 struct new_sa_defrag_extent *new = old->new;
2391 struct btrfs_path *path = new->path;
2392 struct btrfs_key key;
2393 struct btrfs_root *root;
2394 struct sa_defrag_extent_backref *backref;
2395 struct extent_buffer *leaf;
2396 struct inode *inode = new->inode;
2397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2403 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2404 inum == btrfs_ino(BTRFS_I(inode)))
2407 key.objectid = root_id;
2408 key.type = BTRFS_ROOT_ITEM_KEY;
2409 key.offset = (u64)-1;
2411 root = btrfs_read_fs_root_no_name(fs_info, &key);
2413 if (PTR_ERR(root) == -ENOENT)
2416 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2417 inum, offset, root_id);
2418 return PTR_ERR(root);
2421 key.objectid = inum;
2422 key.type = BTRFS_EXTENT_DATA_KEY;
2423 if (offset > (u64)-1 << 32)
2426 key.offset = offset;
2428 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2429 if (WARN_ON(ret < 0))
2436 leaf = path->nodes[0];
2437 slot = path->slots[0];
2439 if (slot >= btrfs_header_nritems(leaf)) {
2440 ret = btrfs_next_leaf(root, path);
2443 } else if (ret > 0) {
2452 btrfs_item_key_to_cpu(leaf, &key, slot);
2454 if (key.objectid > inum)
2457 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2460 extent = btrfs_item_ptr(leaf, slot,
2461 struct btrfs_file_extent_item);
2463 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2467 * 'offset' refers to the exact key.offset,
2468 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2469 * (key.offset - extent_offset).
2471 if (key.offset != offset)
2474 extent_offset = btrfs_file_extent_offset(leaf, extent);
2475 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2477 if (extent_offset >= old->extent_offset + old->offset +
2478 old->len || extent_offset + num_bytes <=
2479 old->extent_offset + old->offset)
2484 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2490 backref->root_id = root_id;
2491 backref->inum = inum;
2492 backref->file_pos = offset;
2493 backref->num_bytes = num_bytes;
2494 backref->extent_offset = extent_offset;
2495 backref->generation = btrfs_file_extent_generation(leaf, extent);
2497 backref_insert(&new->root, backref);
2500 btrfs_release_path(path);
2505 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2506 struct new_sa_defrag_extent *new)
2508 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2509 struct old_sa_defrag_extent *old, *tmp;
2514 list_for_each_entry_safe(old, tmp, &new->head, list) {
2515 ret = iterate_inodes_from_logical(old->bytenr +
2516 old->extent_offset, fs_info,
2517 path, record_one_backref,
2519 if (ret < 0 && ret != -ENOENT)
2522 /* no backref to be processed for this extent */
2524 list_del(&old->list);
2529 if (list_empty(&new->head))
2535 static int relink_is_mergable(struct extent_buffer *leaf,
2536 struct btrfs_file_extent_item *fi,
2537 struct new_sa_defrag_extent *new)
2539 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2542 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2545 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2548 if (btrfs_file_extent_encryption(leaf, fi) ||
2549 btrfs_file_extent_other_encoding(leaf, fi))
2556 * Note the backref might has changed, and in this case we just return 0.
2558 static noinline int relink_extent_backref(struct btrfs_path *path,
2559 struct sa_defrag_extent_backref *prev,
2560 struct sa_defrag_extent_backref *backref)
2562 struct btrfs_file_extent_item *extent;
2563 struct btrfs_file_extent_item *item;
2564 struct btrfs_ordered_extent *ordered;
2565 struct btrfs_trans_handle *trans;
2566 struct btrfs_root *root;
2567 struct btrfs_key key;
2568 struct extent_buffer *leaf;
2569 struct old_sa_defrag_extent *old = backref->old;
2570 struct new_sa_defrag_extent *new = old->new;
2571 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2572 struct inode *inode;
2573 struct extent_state *cached = NULL;
2582 if (prev && prev->root_id == backref->root_id &&
2583 prev->inum == backref->inum &&
2584 prev->file_pos + prev->num_bytes == backref->file_pos)
2587 /* step 1: get root */
2588 key.objectid = backref->root_id;
2589 key.type = BTRFS_ROOT_ITEM_KEY;
2590 key.offset = (u64)-1;
2592 index = srcu_read_lock(&fs_info->subvol_srcu);
2594 root = btrfs_read_fs_root_no_name(fs_info, &key);
2596 srcu_read_unlock(&fs_info->subvol_srcu, index);
2597 if (PTR_ERR(root) == -ENOENT)
2599 return PTR_ERR(root);
2602 if (btrfs_root_readonly(root)) {
2603 srcu_read_unlock(&fs_info->subvol_srcu, index);
2607 /* step 2: get inode */
2608 key.objectid = backref->inum;
2609 key.type = BTRFS_INODE_ITEM_KEY;
2612 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2613 if (IS_ERR(inode)) {
2614 srcu_read_unlock(&fs_info->subvol_srcu, index);
2618 srcu_read_unlock(&fs_info->subvol_srcu, index);
2620 /* step 3: relink backref */
2621 lock_start = backref->file_pos;
2622 lock_end = backref->file_pos + backref->num_bytes - 1;
2623 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2626 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2628 btrfs_put_ordered_extent(ordered);
2632 trans = btrfs_join_transaction(root);
2633 if (IS_ERR(trans)) {
2634 ret = PTR_ERR(trans);
2638 key.objectid = backref->inum;
2639 key.type = BTRFS_EXTENT_DATA_KEY;
2640 key.offset = backref->file_pos;
2642 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2645 } else if (ret > 0) {
2650 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2651 struct btrfs_file_extent_item);
2653 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2654 backref->generation)
2657 btrfs_release_path(path);
2659 start = backref->file_pos;
2660 if (backref->extent_offset < old->extent_offset + old->offset)
2661 start += old->extent_offset + old->offset -
2662 backref->extent_offset;
2664 len = min(backref->extent_offset + backref->num_bytes,
2665 old->extent_offset + old->offset + old->len);
2666 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2668 ret = btrfs_drop_extents(trans, root, inode, start,
2673 key.objectid = btrfs_ino(BTRFS_I(inode));
2674 key.type = BTRFS_EXTENT_DATA_KEY;
2677 path->leave_spinning = 1;
2679 struct btrfs_file_extent_item *fi;
2681 struct btrfs_key found_key;
2683 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2688 leaf = path->nodes[0];
2689 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2691 fi = btrfs_item_ptr(leaf, path->slots[0],
2692 struct btrfs_file_extent_item);
2693 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2695 if (extent_len + found_key.offset == start &&
2696 relink_is_mergable(leaf, fi, new)) {
2697 btrfs_set_file_extent_num_bytes(leaf, fi,
2699 btrfs_mark_buffer_dirty(leaf);
2700 inode_add_bytes(inode, len);
2706 btrfs_release_path(path);
2711 ret = btrfs_insert_empty_item(trans, root, path, &key,
2714 btrfs_abort_transaction(trans, ret);
2718 leaf = path->nodes[0];
2719 item = btrfs_item_ptr(leaf, path->slots[0],
2720 struct btrfs_file_extent_item);
2721 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2722 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2723 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2724 btrfs_set_file_extent_num_bytes(leaf, item, len);
2725 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2726 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2727 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2728 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2729 btrfs_set_file_extent_encryption(leaf, item, 0);
2730 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2732 btrfs_mark_buffer_dirty(leaf);
2733 inode_add_bytes(inode, len);
2734 btrfs_release_path(path);
2736 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2738 backref->root_id, backref->inum,
2739 new->file_pos); /* start - extent_offset */
2741 btrfs_abort_transaction(trans, ret);
2747 btrfs_release_path(path);
2748 path->leave_spinning = 0;
2749 btrfs_end_transaction(trans);
2751 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2757 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2759 struct old_sa_defrag_extent *old, *tmp;
2764 list_for_each_entry_safe(old, tmp, &new->head, list) {
2770 static void relink_file_extents(struct new_sa_defrag_extent *new)
2772 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2773 struct btrfs_path *path;
2774 struct sa_defrag_extent_backref *backref;
2775 struct sa_defrag_extent_backref *prev = NULL;
2776 struct inode *inode;
2777 struct rb_node *node;
2782 path = btrfs_alloc_path();
2786 if (!record_extent_backrefs(path, new)) {
2787 btrfs_free_path(path);
2790 btrfs_release_path(path);
2793 node = rb_first(&new->root);
2796 rb_erase(node, &new->root);
2798 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2800 ret = relink_extent_backref(path, prev, backref);
2813 btrfs_free_path(path);
2815 free_sa_defrag_extent(new);
2817 atomic_dec(&fs_info->defrag_running);
2818 wake_up(&fs_info->transaction_wait);
2821 static struct new_sa_defrag_extent *
2822 record_old_file_extents(struct inode *inode,
2823 struct btrfs_ordered_extent *ordered)
2825 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2826 struct btrfs_root *root = BTRFS_I(inode)->root;
2827 struct btrfs_path *path;
2828 struct btrfs_key key;
2829 struct old_sa_defrag_extent *old;
2830 struct new_sa_defrag_extent *new;
2833 new = kmalloc(sizeof(*new), GFP_NOFS);
2838 new->file_pos = ordered->file_offset;
2839 new->len = ordered->len;
2840 new->bytenr = ordered->start;
2841 new->disk_len = ordered->disk_len;
2842 new->compress_type = ordered->compress_type;
2843 new->root = RB_ROOT;
2844 INIT_LIST_HEAD(&new->head);
2846 path = btrfs_alloc_path();
2850 key.objectid = btrfs_ino(BTRFS_I(inode));
2851 key.type = BTRFS_EXTENT_DATA_KEY;
2852 key.offset = new->file_pos;
2854 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2857 if (ret > 0 && path->slots[0] > 0)
2860 /* find out all the old extents for the file range */
2862 struct btrfs_file_extent_item *extent;
2863 struct extent_buffer *l;
2872 slot = path->slots[0];
2874 if (slot >= btrfs_header_nritems(l)) {
2875 ret = btrfs_next_leaf(root, path);
2883 btrfs_item_key_to_cpu(l, &key, slot);
2885 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2887 if (key.type != BTRFS_EXTENT_DATA_KEY)
2889 if (key.offset >= new->file_pos + new->len)
2892 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2894 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2895 if (key.offset + num_bytes < new->file_pos)
2898 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2902 extent_offset = btrfs_file_extent_offset(l, extent);
2904 old = kmalloc(sizeof(*old), GFP_NOFS);
2908 offset = max(new->file_pos, key.offset);
2909 end = min(new->file_pos + new->len, key.offset + num_bytes);
2911 old->bytenr = disk_bytenr;
2912 old->extent_offset = extent_offset;
2913 old->offset = offset - key.offset;
2914 old->len = end - offset;
2917 list_add_tail(&old->list, &new->head);
2923 btrfs_free_path(path);
2924 atomic_inc(&fs_info->defrag_running);
2929 btrfs_free_path(path);
2931 free_sa_defrag_extent(new);
2935 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2938 struct btrfs_block_group_cache *cache;
2940 cache = btrfs_lookup_block_group(fs_info, start);
2943 spin_lock(&cache->lock);
2944 cache->delalloc_bytes -= len;
2945 spin_unlock(&cache->lock);
2947 btrfs_put_block_group(cache);
2950 /* as ordered data IO finishes, this gets called so we can finish
2951 * an ordered extent if the range of bytes in the file it covers are
2954 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2956 struct inode *inode = ordered_extent->inode;
2957 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2958 struct btrfs_root *root = BTRFS_I(inode)->root;
2959 struct btrfs_trans_handle *trans = NULL;
2960 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2961 struct extent_state *cached_state = NULL;
2962 struct new_sa_defrag_extent *new = NULL;
2963 int compress_type = 0;
2965 u64 logical_len = ordered_extent->len;
2967 bool truncated = false;
2968 bool range_locked = false;
2969 bool clear_new_delalloc_bytes = false;
2971 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2972 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2973 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2974 clear_new_delalloc_bytes = true;
2976 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2978 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2983 btrfs_free_io_failure_record(BTRFS_I(inode),
2984 ordered_extent->file_offset,
2985 ordered_extent->file_offset +
2986 ordered_extent->len - 1);
2988 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2990 logical_len = ordered_extent->truncated_len;
2991 /* Truncated the entire extent, don't bother adding */
2996 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2997 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3000 * For mwrite(mmap + memset to write) case, we still reserve
3001 * space for NOCOW range.
3002 * As NOCOW won't cause a new delayed ref, just free the space
3004 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3005 ordered_extent->len);
3006 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3008 trans = btrfs_join_transaction_nolock(root);
3010 trans = btrfs_join_transaction(root);
3011 if (IS_ERR(trans)) {
3012 ret = PTR_ERR(trans);
3016 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3017 ret = btrfs_update_inode_fallback(trans, root, inode);
3018 if (ret) /* -ENOMEM or corruption */
3019 btrfs_abort_transaction(trans, ret);
3023 range_locked = true;
3024 lock_extent_bits(io_tree, ordered_extent->file_offset,
3025 ordered_extent->file_offset + ordered_extent->len - 1,
3028 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3029 ordered_extent->file_offset + ordered_extent->len - 1,
3030 EXTENT_DEFRAG, 0, cached_state);
3032 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3033 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3034 /* the inode is shared */
3035 new = record_old_file_extents(inode, ordered_extent);
3037 clear_extent_bit(io_tree, ordered_extent->file_offset,
3038 ordered_extent->file_offset + ordered_extent->len - 1,
3039 EXTENT_DEFRAG, 0, 0, &cached_state);
3043 trans = btrfs_join_transaction_nolock(root);
3045 trans = btrfs_join_transaction(root);
3046 if (IS_ERR(trans)) {
3047 ret = PTR_ERR(trans);
3052 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3054 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3055 compress_type = ordered_extent->compress_type;
3056 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3057 BUG_ON(compress_type);
3058 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3059 ordered_extent->len);
3060 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3061 ordered_extent->file_offset,
3062 ordered_extent->file_offset +
3065 BUG_ON(root == fs_info->tree_root);
3066 ret = insert_reserved_file_extent(trans, inode,
3067 ordered_extent->file_offset,
3068 ordered_extent->start,
3069 ordered_extent->disk_len,
3070 logical_len, logical_len,
3071 compress_type, 0, 0,
3072 BTRFS_FILE_EXTENT_REG);
3074 btrfs_release_delalloc_bytes(fs_info,
3075 ordered_extent->start,
3076 ordered_extent->disk_len);
3078 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3079 ordered_extent->file_offset, ordered_extent->len,
3082 btrfs_abort_transaction(trans, ret);
3086 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3088 btrfs_abort_transaction(trans, ret);
3092 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3093 ret = btrfs_update_inode_fallback(trans, root, inode);
3094 if (ret) { /* -ENOMEM or corruption */
3095 btrfs_abort_transaction(trans, ret);
3100 if (range_locked || clear_new_delalloc_bytes) {
3101 unsigned int clear_bits = 0;
3104 clear_bits |= EXTENT_LOCKED;
3105 if (clear_new_delalloc_bytes)
3106 clear_bits |= EXTENT_DELALLOC_NEW;
3107 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3108 ordered_extent->file_offset,
3109 ordered_extent->file_offset +
3110 ordered_extent->len - 1,
3112 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3117 btrfs_end_transaction(trans);
3119 if (ret || truncated) {
3123 start = ordered_extent->file_offset + logical_len;
3125 start = ordered_extent->file_offset;
3126 end = ordered_extent->file_offset + ordered_extent->len - 1;
3127 clear_extent_uptodate(io_tree, start, end, NULL);
3129 /* Drop the cache for the part of the extent we didn't write. */
3130 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3133 * If the ordered extent had an IOERR or something else went
3134 * wrong we need to return the space for this ordered extent
3135 * back to the allocator. We only free the extent in the
3136 * truncated case if we didn't write out the extent at all.
3138 if ((ret || !logical_len) &&
3139 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3140 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3141 btrfs_free_reserved_extent(fs_info,
3142 ordered_extent->start,
3143 ordered_extent->disk_len, 1);
3148 * This needs to be done to make sure anybody waiting knows we are done
3149 * updating everything for this ordered extent.
3151 btrfs_remove_ordered_extent(inode, ordered_extent);
3153 /* for snapshot-aware defrag */
3156 free_sa_defrag_extent(new);
3157 atomic_dec(&fs_info->defrag_running);
3159 relink_file_extents(new);
3164 btrfs_put_ordered_extent(ordered_extent);
3165 /* once for the tree */
3166 btrfs_put_ordered_extent(ordered_extent);
3168 /* Try to release some metadata so we don't get an OOM but don't wait */
3169 btrfs_btree_balance_dirty_nodelay(fs_info);
3174 static void finish_ordered_fn(struct btrfs_work *work)
3176 struct btrfs_ordered_extent *ordered_extent;
3177 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3178 btrfs_finish_ordered_io(ordered_extent);
3181 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3182 struct extent_state *state, int uptodate)
3184 struct inode *inode = page->mapping->host;
3185 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3186 struct btrfs_ordered_extent *ordered_extent = NULL;
3187 struct btrfs_workqueue *wq;
3188 btrfs_work_func_t func;
3190 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3192 ClearPagePrivate2(page);
3193 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3194 end - start + 1, uptodate))
3197 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3198 wq = fs_info->endio_freespace_worker;
3199 func = btrfs_freespace_write_helper;
3201 wq = fs_info->endio_write_workers;
3202 func = btrfs_endio_write_helper;
3205 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3207 btrfs_queue_work(wq, &ordered_extent->work);
3210 static int __readpage_endio_check(struct inode *inode,
3211 struct btrfs_io_bio *io_bio,
3212 int icsum, struct page *page,
3213 int pgoff, u64 start, size_t len)
3219 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3221 kaddr = kmap_atomic(page);
3222 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3223 btrfs_csum_final(csum, (u8 *)&csum);
3224 if (csum != csum_expected)
3227 kunmap_atomic(kaddr);
3230 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3231 io_bio->mirror_num);
3232 memset(kaddr + pgoff, 1, len);
3233 flush_dcache_page(page);
3234 kunmap_atomic(kaddr);
3239 * when reads are done, we need to check csums to verify the data is correct
3240 * if there's a match, we allow the bio to finish. If not, the code in
3241 * extent_io.c will try to find good copies for us.
3243 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3244 u64 phy_offset, struct page *page,
3245 u64 start, u64 end, int mirror)
3247 size_t offset = start - page_offset(page);
3248 struct inode *inode = page->mapping->host;
3249 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3250 struct btrfs_root *root = BTRFS_I(inode)->root;
3252 if (PageChecked(page)) {
3253 ClearPageChecked(page);
3257 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3260 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3261 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3262 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3266 phy_offset >>= inode->i_sb->s_blocksize_bits;
3267 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3268 start, (size_t)(end - start + 1));
3272 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3274 * @inode: The inode we want to perform iput on
3276 * This function uses the generic vfs_inode::i_count to track whether we should
3277 * just decrement it (in case it's > 1) or if this is the last iput then link
3278 * the inode to the delayed iput machinery. Delayed iputs are processed at
3279 * transaction commit time/superblock commit/cleaner kthread.
3281 void btrfs_add_delayed_iput(struct inode *inode)
3283 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3284 struct btrfs_inode *binode = BTRFS_I(inode);
3286 if (atomic_add_unless(&inode->i_count, -1, 1))
3289 spin_lock(&fs_info->delayed_iput_lock);
3290 ASSERT(list_empty(&binode->delayed_iput));
3291 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3292 spin_unlock(&fs_info->delayed_iput_lock);
3295 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3298 spin_lock(&fs_info->delayed_iput_lock);
3299 while (!list_empty(&fs_info->delayed_iputs)) {
3300 struct btrfs_inode *inode;
3302 inode = list_first_entry(&fs_info->delayed_iputs,
3303 struct btrfs_inode, delayed_iput);
3304 list_del_init(&inode->delayed_iput);
3305 spin_unlock(&fs_info->delayed_iput_lock);
3306 iput(&inode->vfs_inode);
3307 spin_lock(&fs_info->delayed_iput_lock);
3309 spin_unlock(&fs_info->delayed_iput_lock);
3313 * This creates an orphan entry for the given inode in case something goes wrong
3314 * in the middle of an unlink.
3316 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3317 struct btrfs_inode *inode)
3321 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3322 if (ret && ret != -EEXIST) {
3323 btrfs_abort_transaction(trans, ret);
3331 * We have done the delete so we can go ahead and remove the orphan item for
3332 * this particular inode.
3334 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3335 struct btrfs_inode *inode)
3337 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3341 * this cleans up any orphans that may be left on the list from the last use
3344 int btrfs_orphan_cleanup(struct btrfs_root *root)
3346 struct btrfs_fs_info *fs_info = root->fs_info;
3347 struct btrfs_path *path;
3348 struct extent_buffer *leaf;
3349 struct btrfs_key key, found_key;
3350 struct btrfs_trans_handle *trans;
3351 struct inode *inode;
3352 u64 last_objectid = 0;
3353 int ret = 0, nr_unlink = 0;
3355 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3358 path = btrfs_alloc_path();
3363 path->reada = READA_BACK;
3365 key.objectid = BTRFS_ORPHAN_OBJECTID;
3366 key.type = BTRFS_ORPHAN_ITEM_KEY;
3367 key.offset = (u64)-1;
3370 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3375 * if ret == 0 means we found what we were searching for, which
3376 * is weird, but possible, so only screw with path if we didn't
3377 * find the key and see if we have stuff that matches
3381 if (path->slots[0] == 0)
3386 /* pull out the item */
3387 leaf = path->nodes[0];
3388 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3390 /* make sure the item matches what we want */
3391 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3393 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3396 /* release the path since we're done with it */
3397 btrfs_release_path(path);
3400 * this is where we are basically btrfs_lookup, without the
3401 * crossing root thing. we store the inode number in the
3402 * offset of the orphan item.
3405 if (found_key.offset == last_objectid) {
3407 "Error removing orphan entry, stopping orphan cleanup");
3412 last_objectid = found_key.offset;
3414 found_key.objectid = found_key.offset;
3415 found_key.type = BTRFS_INODE_ITEM_KEY;
3416 found_key.offset = 0;
3417 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3418 ret = PTR_ERR_OR_ZERO(inode);
3419 if (ret && ret != -ENOENT)
3422 if (ret == -ENOENT && root == fs_info->tree_root) {
3423 struct btrfs_root *dead_root;
3424 struct btrfs_fs_info *fs_info = root->fs_info;
3425 int is_dead_root = 0;
3428 * this is an orphan in the tree root. Currently these
3429 * could come from 2 sources:
3430 * a) a snapshot deletion in progress
3431 * b) a free space cache inode
3432 * We need to distinguish those two, as the snapshot
3433 * orphan must not get deleted.
3434 * find_dead_roots already ran before us, so if this
3435 * is a snapshot deletion, we should find the root
3436 * in the dead_roots list
3438 spin_lock(&fs_info->trans_lock);
3439 list_for_each_entry(dead_root, &fs_info->dead_roots,
3441 if (dead_root->root_key.objectid ==
3442 found_key.objectid) {
3447 spin_unlock(&fs_info->trans_lock);
3449 /* prevent this orphan from being found again */
3450 key.offset = found_key.objectid - 1;
3457 * If we have an inode with links, there are a couple of
3458 * possibilities. Old kernels (before v3.12) used to create an
3459 * orphan item for truncate indicating that there were possibly
3460 * extent items past i_size that needed to be deleted. In v3.12,
3461 * truncate was changed to update i_size in sync with the extent
3462 * items, but the (useless) orphan item was still created. Since
3463 * v4.18, we don't create the orphan item for truncate at all.
3465 * So, this item could mean that we need to do a truncate, but
3466 * only if this filesystem was last used on a pre-v3.12 kernel
3467 * and was not cleanly unmounted. The odds of that are quite
3468 * slim, and it's a pain to do the truncate now, so just delete
3471 * It's also possible that this orphan item was supposed to be
3472 * deleted but wasn't. The inode number may have been reused,
3473 * but either way, we can delete the orphan item.
3475 if (ret == -ENOENT || inode->i_nlink) {
3478 trans = btrfs_start_transaction(root, 1);
3479 if (IS_ERR(trans)) {
3480 ret = PTR_ERR(trans);
3483 btrfs_debug(fs_info, "auto deleting %Lu",
3484 found_key.objectid);
3485 ret = btrfs_del_orphan_item(trans, root,
3486 found_key.objectid);
3487 btrfs_end_transaction(trans);
3495 /* this will do delete_inode and everything for us */
3500 /* release the path since we're done with it */
3501 btrfs_release_path(path);
3503 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3505 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3506 trans = btrfs_join_transaction(root);
3508 btrfs_end_transaction(trans);
3512 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3516 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3517 btrfs_free_path(path);
3522 * very simple check to peek ahead in the leaf looking for xattrs. If we
3523 * don't find any xattrs, we know there can't be any acls.
3525 * slot is the slot the inode is in, objectid is the objectid of the inode
3527 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3528 int slot, u64 objectid,
3529 int *first_xattr_slot)
3531 u32 nritems = btrfs_header_nritems(leaf);
3532 struct btrfs_key found_key;