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/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <asm/unaligned.h>
34 #include "transaction.h"
35 #include "btrfs_inode.h"
36 #include "print-tree.h"
37 #include "ordered-data.h"
41 #include "compression.h"
43 #include "free-space-cache.h"
44 #include "inode-map.h"
50 struct btrfs_iget_args {
51 struct btrfs_key *location;
52 struct btrfs_root *root;
55 struct btrfs_dio_data {
57 u64 unsubmitted_oe_range_start;
58 u64 unsubmitted_oe_range_end;
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_aops;
68 static const struct file_operations btrfs_dir_file_operations;
69 static const struct extent_io_ops btrfs_extent_io_ops;
71 static struct kmem_cache *btrfs_inode_cachep;
72 struct kmem_cache *btrfs_trans_handle_cachep;
73 struct kmem_cache *btrfs_path_cachep;
74 struct kmem_cache *btrfs_free_space_cachep;
77 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
78 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
79 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
80 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
81 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
82 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
83 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
84 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
87 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
88 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
89 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
90 static noinline int cow_file_range(struct inode *inode,
91 struct page *locked_page,
92 u64 start, u64 end, u64 delalloc_end,
93 int *page_started, unsigned long *nr_written,
94 int unlock, struct btrfs_dedupe_hash *hash);
95 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
96 u64 orig_start, u64 block_start,
97 u64 block_len, u64 orig_block_len,
98 u64 ram_bytes, int compress_type,
101 static void __endio_write_update_ordered(struct inode *inode,
102 const u64 offset, const u64 bytes,
103 const bool uptodate);
106 * Cleanup all submitted ordered extents in specified range to handle errors
107 * from the fill_dellaloc() callback.
109 * NOTE: caller must ensure that when an error happens, it can not call
110 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
111 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
112 * to be released, which we want to happen only when finishing the ordered
113 * extent (btrfs_finish_ordered_io()). Also note that the caller of
114 * btrfs_run_delalloc_range already does proper cleanup for the first page of
115 * the range, that is, it invokes the callback writepage_end_io_hook() for the
116 * range of the first page.
118 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
122 unsigned long index = offset >> PAGE_SHIFT;
123 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
126 while (index <= end_index) {
127 page = find_get_page(inode->i_mapping, index);
131 ClearPagePrivate2(page);
134 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
135 bytes - PAGE_SIZE, false);
138 static int btrfs_dirty_inode(struct inode *inode);
140 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
141 void btrfs_test_inode_set_ops(struct inode *inode)
143 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
147 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
148 struct inode *inode, struct inode *dir,
149 const struct qstr *qstr)
153 err = btrfs_init_acl(trans, inode, dir);
155 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
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
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,
169 struct page **compressed_pages)
171 struct extent_buffer *leaf;
172 struct page *page = NULL;
175 struct btrfs_file_extent_item *ei;
177 size_t cur_size = size;
178 unsigned long offset;
180 if (compressed_size && compressed_pages)
181 cur_size = compressed_size;
183 inode_add_bytes(inode, size);
185 if (!extent_inserted) {
186 struct btrfs_key key;
189 key.objectid = btrfs_ino(BTRFS_I(inode));
191 key.type = BTRFS_EXTENT_DATA_KEY;
193 datasize = btrfs_file_extent_calc_inline_size(cur_size);
194 path->leave_spinning = 1;
195 ret = btrfs_insert_empty_item(trans, root, path, &key,
200 leaf = path->nodes[0];
201 ei = btrfs_item_ptr(leaf, path->slots[0],
202 struct btrfs_file_extent_item);
203 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
204 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
205 btrfs_set_file_extent_encryption(leaf, ei, 0);
206 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
207 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
208 ptr = btrfs_file_extent_inline_start(ei);
210 if (compress_type != BTRFS_COMPRESS_NONE) {
213 while (compressed_size > 0) {
214 cpage = compressed_pages[i];
215 cur_size = min_t(unsigned long, compressed_size,
218 kaddr = kmap_atomic(cpage);
219 write_extent_buffer(leaf, kaddr, ptr, cur_size);
220 kunmap_atomic(kaddr);
224 compressed_size -= cur_size;
226 btrfs_set_file_extent_compression(leaf, ei,
229 page = find_get_page(inode->i_mapping,
230 start >> PAGE_SHIFT);
231 btrfs_set_file_extent_compression(leaf, ei, 0);
232 kaddr = kmap_atomic(page);
233 offset = start & (PAGE_SIZE - 1);
234 write_extent_buffer(leaf, kaddr + offset, ptr, size);
235 kunmap_atomic(kaddr);
238 btrfs_mark_buffer_dirty(leaf);
239 btrfs_release_path(path);
242 * we're an inline extent, so nobody can
243 * extend the file past i_size without locking
244 * a page we already have locked.
246 * We must do any isize and inode updates
247 * before we unlock the pages. Otherwise we
248 * could end up racing with unlink.
250 BTRFS_I(inode)->disk_i_size = inode->i_size;
251 ret = btrfs_update_inode(trans, root, inode);
259 * conditionally insert an inline extent into the file. This
260 * does the checks required to make sure the data is small enough
261 * to fit as an inline extent.
263 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
264 u64 end, size_t compressed_size,
266 struct page **compressed_pages)
268 struct btrfs_root *root = BTRFS_I(inode)->root;
269 struct btrfs_fs_info *fs_info = root->fs_info;
270 struct btrfs_trans_handle *trans;
271 u64 isize = i_size_read(inode);
272 u64 actual_end = min(end + 1, isize);
273 u64 inline_len = actual_end - start;
274 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
275 u64 data_len = inline_len;
277 struct btrfs_path *path;
278 int extent_inserted = 0;
279 u32 extent_item_size;
282 data_len = compressed_size;
285 actual_end > fs_info->sectorsize ||
286 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
288 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
290 data_len > fs_info->max_inline) {
294 path = btrfs_alloc_path();
298 trans = btrfs_join_transaction(root);
300 btrfs_free_path(path);
301 return PTR_ERR(trans);
303 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
305 if (compressed_size && compressed_pages)
306 extent_item_size = btrfs_file_extent_calc_inline_size(
309 extent_item_size = btrfs_file_extent_calc_inline_size(
312 ret = __btrfs_drop_extents(trans, root, inode, path,
313 start, aligned_end, NULL,
314 1, 1, extent_item_size, &extent_inserted);
316 btrfs_abort_transaction(trans, ret);
320 if (isize > actual_end)
321 inline_len = min_t(u64, isize, actual_end);
322 ret = insert_inline_extent(trans, path, extent_inserted,
324 inline_len, compressed_size,
325 compress_type, compressed_pages);
326 if (ret && ret != -ENOSPC) {
327 btrfs_abort_transaction(trans, ret);
329 } else if (ret == -ENOSPC) {
334 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
335 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
338 * Don't forget to free the reserved space, as for inlined extent
339 * it won't count as data extent, free them directly here.
340 * And at reserve time, it's always aligned to page size, so
341 * just free one page here.
343 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
344 btrfs_free_path(path);
345 btrfs_end_transaction(trans);
349 struct async_extent {
354 unsigned long nr_pages;
356 struct list_head list;
361 struct btrfs_root *root;
362 struct page *locked_page;
365 unsigned int write_flags;
366 struct list_head extents;
367 struct btrfs_work work;
370 static noinline int add_async_extent(struct async_cow *cow,
371 u64 start, u64 ram_size,
374 unsigned long nr_pages,
377 struct async_extent *async_extent;
379 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
380 BUG_ON(!async_extent); /* -ENOMEM */
381 async_extent->start = start;
382 async_extent->ram_size = ram_size;
383 async_extent->compressed_size = compressed_size;
384 async_extent->pages = pages;
385 async_extent->nr_pages = nr_pages;
386 async_extent->compress_type = compress_type;
387 list_add_tail(&async_extent->list, &cow->extents);
391 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
393 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
396 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
399 if (BTRFS_I(inode)->defrag_compress)
401 /* bad compression ratios */
402 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
404 if (btrfs_test_opt(fs_info, COMPRESS) ||
405 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
406 BTRFS_I(inode)->prop_compress)
407 return btrfs_compress_heuristic(inode, start, end);
411 static inline void inode_should_defrag(struct btrfs_inode *inode,
412 u64 start, u64 end, u64 num_bytes, u64 small_write)
414 /* If this is a small write inside eof, kick off a defrag */
415 if (num_bytes < small_write &&
416 (start > 0 || end + 1 < inode->disk_i_size))
417 btrfs_add_inode_defrag(NULL, inode);
421 * we create compressed extents in two phases. The first
422 * phase compresses a range of pages that have already been
423 * locked (both pages and state bits are locked).
425 * This is done inside an ordered work queue, and the compression
426 * is spread across many cpus. The actual IO submission is step
427 * two, and the ordered work queue takes care of making sure that
428 * happens in the same order things were put onto the queue by
429 * writepages and friends.
431 * If this code finds it can't get good compression, it puts an
432 * entry onto the work queue to write the uncompressed bytes. This
433 * makes sure that both compressed inodes and uncompressed inodes
434 * are written in the same order that the flusher thread sent them
437 static noinline void compress_file_range(struct inode *inode,
438 struct page *locked_page,
440 struct async_cow *async_cow,
443 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
444 u64 blocksize = fs_info->sectorsize;
446 u64 isize = i_size_read(inode);
448 struct page **pages = NULL;
449 unsigned long nr_pages;
450 unsigned long total_compressed = 0;
451 unsigned long total_in = 0;
454 int compress_type = fs_info->compress_type;
457 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
460 actual_end = min_t(u64, isize, end + 1);
463 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
464 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
465 nr_pages = min_t(unsigned long, nr_pages,
466 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
469 * we don't want to send crud past the end of i_size through
470 * compression, that's just a waste of CPU time. So, if the
471 * end of the file is before the start of our current
472 * requested range of bytes, we bail out to the uncompressed
473 * cleanup code that can deal with all of this.
475 * It isn't really the fastest way to fix things, but this is a
476 * very uncommon corner.
478 if (actual_end <= start)
479 goto cleanup_and_bail_uncompressed;
481 total_compressed = actual_end - start;
484 * skip compression for a small file range(<=blocksize) that
485 * isn't an inline extent, since it doesn't save disk space at all.
487 if (total_compressed <= blocksize &&
488 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
489 goto cleanup_and_bail_uncompressed;
491 total_compressed = min_t(unsigned long, total_compressed,
492 BTRFS_MAX_UNCOMPRESSED);
497 * we do compression for mount -o compress and when the
498 * inode has not been flagged as nocompress. This flag can
499 * change at any time if we discover bad compression ratios.
501 if (inode_need_compress(inode, start, end)) {
503 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
505 /* just bail out to the uncompressed code */
510 if (BTRFS_I(inode)->defrag_compress)
511 compress_type = BTRFS_I(inode)->defrag_compress;
512 else if (BTRFS_I(inode)->prop_compress)
513 compress_type = BTRFS_I(inode)->prop_compress;
516 * we need to call clear_page_dirty_for_io on each
517 * page in the range. Otherwise applications with the file
518 * mmap'd can wander in and change the page contents while
519 * we are compressing them.
521 * If the compression fails for any reason, we set the pages
522 * dirty again later on.
524 * Note that the remaining part is redirtied, the start pointer
525 * has moved, the end is the original one.
528 extent_range_clear_dirty_for_io(inode, start, end);
532 /* Compression level is applied here and only here */
533 ret = btrfs_compress_pages(
534 compress_type | (fs_info->compress_level << 4),
535 inode->i_mapping, start,
542 unsigned long offset = total_compressed &
544 struct page *page = pages[nr_pages - 1];
547 /* zero the tail end of the last page, we might be
548 * sending it down to disk
551 kaddr = kmap_atomic(page);
552 memset(kaddr + offset, 0,
554 kunmap_atomic(kaddr);
561 /* lets try to make an inline extent */
562 if (ret || total_in < actual_end) {
563 /* we didn't compress the entire range, try
564 * to make an uncompressed inline extent.
566 ret = cow_file_range_inline(inode, start, end, 0,
567 BTRFS_COMPRESS_NONE, NULL);
569 /* try making a compressed inline extent */
570 ret = cow_file_range_inline(inode, start, end,
572 compress_type, pages);
575 unsigned long clear_flags = EXTENT_DELALLOC |
576 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
577 EXTENT_DO_ACCOUNTING;
578 unsigned long page_error_op;
580 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
583 * inline extent creation worked or returned error,
584 * we don't need to create any more async work items.
585 * Unlock and free up our temp pages.
587 * We use DO_ACCOUNTING here because we need the
588 * delalloc_release_metadata to be done _after_ we drop
589 * our outstanding extent for clearing delalloc for this
592 extent_clear_unlock_delalloc(inode, start, end, end,
605 * we aren't doing an inline extent round the compressed size
606 * up to a block size boundary so the allocator does sane
609 total_compressed = ALIGN(total_compressed, blocksize);
612 * one last check to make sure the compression is really a
613 * win, compare the page count read with the blocks on disk,
614 * compression must free at least one sector size
616 total_in = ALIGN(total_in, PAGE_SIZE);
617 if (total_compressed + blocksize <= total_in) {
621 * The async work queues will take care of doing actual
622 * allocation on disk for these compressed pages, and
623 * will submit them to the elevator.
625 add_async_extent(async_cow, start, total_in,
626 total_compressed, pages, nr_pages,
629 if (start + total_in < end) {
640 * the compression code ran but failed to make things smaller,
641 * free any pages it allocated and our page pointer array
643 for (i = 0; i < nr_pages; i++) {
644 WARN_ON(pages[i]->mapping);
649 total_compressed = 0;
652 /* flag the file so we don't compress in the future */
653 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
654 !(BTRFS_I(inode)->prop_compress)) {
655 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
658 cleanup_and_bail_uncompressed:
660 * No compression, but we still need to write the pages in the file
661 * we've been given so far. redirty the locked page if it corresponds
662 * to our extent and set things up for the async work queue to run
663 * cow_file_range to do the normal delalloc dance.
665 if (page_offset(locked_page) >= start &&
666 page_offset(locked_page) <= end)
667 __set_page_dirty_nobuffers(locked_page);
668 /* unlocked later on in the async handlers */
671 extent_range_redirty_for_io(inode, start, end);
672 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
673 BTRFS_COMPRESS_NONE);
679 for (i = 0; i < nr_pages; i++) {
680 WARN_ON(pages[i]->mapping);
686 static void free_async_extent_pages(struct async_extent *async_extent)
690 if (!async_extent->pages)
693 for (i = 0; i < async_extent->nr_pages; i++) {
694 WARN_ON(async_extent->pages[i]->mapping);
695 put_page(async_extent->pages[i]);
697 kfree(async_extent->pages);
698 async_extent->nr_pages = 0;
699 async_extent->pages = NULL;
703 * phase two of compressed writeback. This is the ordered portion
704 * of the code, which only gets called in the order the work was
705 * queued. We walk all the async extents created by compress_file_range
706 * and send them down to the disk.
708 static noinline void submit_compressed_extents(struct inode *inode,
709 struct async_cow *async_cow)
711 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
712 struct async_extent *async_extent;
714 struct btrfs_key ins;
715 struct extent_map *em;
716 struct btrfs_root *root = BTRFS_I(inode)->root;
717 struct extent_io_tree *io_tree;
721 while (!list_empty(&async_cow->extents)) {
722 async_extent = list_entry(async_cow->extents.next,
723 struct async_extent, list);
724 list_del(&async_extent->list);
726 io_tree = &BTRFS_I(inode)->io_tree;
729 /* did the compression code fall back to uncompressed IO? */
730 if (!async_extent->pages) {
731 int page_started = 0;
732 unsigned long nr_written = 0;
734 lock_extent(io_tree, async_extent->start,
735 async_extent->start +
736 async_extent->ram_size - 1);
738 /* allocate blocks */
739 ret = cow_file_range(inode, async_cow->locked_page,
741 async_extent->start +
742 async_extent->ram_size - 1,
743 async_extent->start +
744 async_extent->ram_size - 1,
745 &page_started, &nr_written, 0,
751 * if page_started, cow_file_range inserted an
752 * inline extent and took care of all the unlocking
753 * and IO for us. Otherwise, we need to submit
754 * all those pages down to the drive.
756 if (!page_started && !ret)
757 extent_write_locked_range(inode,
759 async_extent->start +
760 async_extent->ram_size - 1,
763 unlock_page(async_cow->locked_page);
769 lock_extent(io_tree, async_extent->start,
770 async_extent->start + async_extent->ram_size - 1);
772 ret = btrfs_reserve_extent(root, async_extent->ram_size,
773 async_extent->compressed_size,
774 async_extent->compressed_size,
775 0, alloc_hint, &ins, 1, 1);
777 free_async_extent_pages(async_extent);
779 if (ret == -ENOSPC) {
780 unlock_extent(io_tree, async_extent->start,
781 async_extent->start +
782 async_extent->ram_size - 1);
785 * we need to redirty the pages if we decide to
786 * fallback to uncompressed IO, otherwise we
787 * will not submit these pages down to lower
790 extent_range_redirty_for_io(inode,
792 async_extent->start +
793 async_extent->ram_size - 1);
800 * here we're doing allocation and writeback of the
803 em = create_io_em(inode, async_extent->start,
804 async_extent->ram_size, /* len */
805 async_extent->start, /* orig_start */
806 ins.objectid, /* block_start */
807 ins.offset, /* block_len */
808 ins.offset, /* orig_block_len */
809 async_extent->ram_size, /* ram_bytes */
810 async_extent->compress_type,
811 BTRFS_ORDERED_COMPRESSED);
813 /* ret value is not necessary due to void function */
814 goto out_free_reserve;
817 ret = btrfs_add_ordered_extent_compress(inode,
820 async_extent->ram_size,
822 BTRFS_ORDERED_COMPRESSED,
823 async_extent->compress_type);
825 btrfs_drop_extent_cache(BTRFS_I(inode),
827 async_extent->start +
828 async_extent->ram_size - 1, 0);
829 goto out_free_reserve;
831 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
834 * clear dirty, set writeback and unlock the pages.
836 extent_clear_unlock_delalloc(inode, async_extent->start,
837 async_extent->start +
838 async_extent->ram_size - 1,
839 async_extent->start +
840 async_extent->ram_size - 1,
841 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
842 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
844 if (btrfs_submit_compressed_write(inode,
846 async_extent->ram_size,
848 ins.offset, async_extent->pages,
849 async_extent->nr_pages,
850 async_cow->write_flags)) {
851 struct page *p = async_extent->pages[0];
852 const u64 start = async_extent->start;
853 const u64 end = start + async_extent->ram_size - 1;
855 p->mapping = inode->i_mapping;
856 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
859 extent_clear_unlock_delalloc(inode, start, end, end,
863 free_async_extent_pages(async_extent);
865 alloc_hint = ins.objectid + ins.offset;
871 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
872 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
874 extent_clear_unlock_delalloc(inode, async_extent->start,
875 async_extent->start +
876 async_extent->ram_size - 1,
877 async_extent->start +
878 async_extent->ram_size - 1,
879 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
880 EXTENT_DELALLOC_NEW |
881 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
882 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
883 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
885 free_async_extent_pages(async_extent);
890 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
893 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
894 struct extent_map *em;
897 read_lock(&em_tree->lock);
898 em = search_extent_mapping(em_tree, start, num_bytes);
901 * if block start isn't an actual block number then find the
902 * first block in this inode and use that as a hint. If that
903 * block is also bogus then just don't worry about it.
905 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
907 em = search_extent_mapping(em_tree, 0, 0);
908 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
909 alloc_hint = em->block_start;
913 alloc_hint = em->block_start;
917 read_unlock(&em_tree->lock);
923 * when extent_io.c finds a delayed allocation range in the file,
924 * the call backs end up in this code. The basic idea is to
925 * allocate extents on disk for the range, and create ordered data structs
926 * in ram to track those extents.
928 * locked_page is the page that writepage had locked already. We use
929 * it to make sure we don't do extra locks or unlocks.
931 * *page_started is set to one if we unlock locked_page and do everything
932 * required to start IO on it. It may be clean and already done with
935 static noinline int cow_file_range(struct inode *inode,
936 struct page *locked_page,
937 u64 start, u64 end, u64 delalloc_end,
938 int *page_started, unsigned long *nr_written,
939 int unlock, struct btrfs_dedupe_hash *hash)
941 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
942 struct btrfs_root *root = BTRFS_I(inode)->root;
945 unsigned long ram_size;
946 u64 cur_alloc_size = 0;
947 u64 blocksize = fs_info->sectorsize;
948 struct btrfs_key ins;
949 struct extent_map *em;
951 unsigned long page_ops;
952 bool extent_reserved = false;
955 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
961 num_bytes = ALIGN(end - start + 1, blocksize);
962 num_bytes = max(blocksize, num_bytes);
963 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
965 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
968 /* lets try to make an inline extent */
969 ret = cow_file_range_inline(inode, start, end, 0,
970 BTRFS_COMPRESS_NONE, NULL);
973 * We use DO_ACCOUNTING here because we need the
974 * delalloc_release_metadata to be run _after_ we drop
975 * our outstanding extent for clearing delalloc for this
978 extent_clear_unlock_delalloc(inode, start, end,
980 EXTENT_LOCKED | EXTENT_DELALLOC |
981 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
982 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
983 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
985 *nr_written = *nr_written +
986 (end - start + PAGE_SIZE) / PAGE_SIZE;
989 } else if (ret < 0) {
994 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
995 btrfs_drop_extent_cache(BTRFS_I(inode), start,
996 start + num_bytes - 1, 0);
998 while (num_bytes > 0) {
999 cur_alloc_size = num_bytes;
1000 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1001 fs_info->sectorsize, 0, alloc_hint,
1005 cur_alloc_size = ins.offset;
1006 extent_reserved = true;
1008 ram_size = ins.offset;
1009 em = create_io_em(inode, start, ins.offset, /* len */
1010 start, /* orig_start */
1011 ins.objectid, /* block_start */
1012 ins.offset, /* block_len */
1013 ins.offset, /* orig_block_len */
1014 ram_size, /* ram_bytes */
1015 BTRFS_COMPRESS_NONE, /* compress_type */
1016 BTRFS_ORDERED_REGULAR /* type */);
1021 free_extent_map(em);
1023 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1024 ram_size, cur_alloc_size, 0);
1026 goto out_drop_extent_cache;
1028 if (root->root_key.objectid ==
1029 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1030 ret = btrfs_reloc_clone_csums(inode, start,
1033 * Only drop cache here, and process as normal.
1035 * We must not allow extent_clear_unlock_delalloc()
1036 * at out_unlock label to free meta of this ordered
1037 * extent, as its meta should be freed by
1038 * btrfs_finish_ordered_io().
1040 * So we must continue until @start is increased to
1041 * skip current ordered extent.
1044 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1045 start + ram_size - 1, 0);
1048 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1050 /* we're not doing compressed IO, don't unlock the first
1051 * page (which the caller expects to stay locked), don't
1052 * clear any dirty bits and don't set any writeback bits
1054 * Do set the Private2 bit so we know this page was properly
1055 * setup for writepage
1057 page_ops = unlock ? PAGE_UNLOCK : 0;
1058 page_ops |= PAGE_SET_PRIVATE2;
1060 extent_clear_unlock_delalloc(inode, start,
1061 start + ram_size - 1,
1062 delalloc_end, locked_page,
1063 EXTENT_LOCKED | EXTENT_DELALLOC,
1065 if (num_bytes < cur_alloc_size)
1068 num_bytes -= cur_alloc_size;
1069 alloc_hint = ins.objectid + ins.offset;
1070 start += cur_alloc_size;
1071 extent_reserved = false;
1074 * btrfs_reloc_clone_csums() error, since start is increased
1075 * extent_clear_unlock_delalloc() at out_unlock label won't
1076 * free metadata of current ordered extent, we're OK to exit.
1084 out_drop_extent_cache:
1085 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1087 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1088 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1090 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1091 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1092 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1095 * If we reserved an extent for our delalloc range (or a subrange) and
1096 * failed to create the respective ordered extent, then it means that
1097 * when we reserved the extent we decremented the extent's size from
1098 * the data space_info's bytes_may_use counter and incremented the
1099 * space_info's bytes_reserved counter by the same amount. We must make
1100 * sure extent_clear_unlock_delalloc() does not try to decrement again
1101 * the data space_info's bytes_may_use counter, therefore we do not pass
1102 * it the flag EXTENT_CLEAR_DATA_RESV.
1104 if (extent_reserved) {
1105 extent_clear_unlock_delalloc(inode, start,
1106 start + cur_alloc_size,
1107 start + cur_alloc_size,
1111 start += cur_alloc_size;
1115 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1117 clear_bits | EXTENT_CLEAR_DATA_RESV,
1123 * work queue call back to started compression on a file and pages
1125 static noinline void async_cow_start(struct btrfs_work *work)
1127 struct async_cow *async_cow;
1129 async_cow = container_of(work, struct async_cow, work);
1131 compress_file_range(async_cow->inode, async_cow->locked_page,
1132 async_cow->start, async_cow->end, async_cow,
1134 if (num_added == 0) {
1135 btrfs_add_delayed_iput(async_cow->inode);
1136 async_cow->inode = NULL;
1141 * work queue call back to submit previously compressed pages
1143 static noinline void async_cow_submit(struct btrfs_work *work)
1145 struct btrfs_fs_info *fs_info;
1146 struct async_cow *async_cow;
1147 struct btrfs_root *root;
1148 unsigned long nr_pages;
1150 async_cow = container_of(work, struct async_cow, work);
1152 root = async_cow->root;
1153 fs_info = root->fs_info;
1154 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1157 /* atomic_sub_return implies a barrier */
1158 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1160 cond_wake_up_nomb(&fs_info->async_submit_wait);
1162 if (async_cow->inode)
1163 submit_compressed_extents(async_cow->inode, async_cow);
1166 static noinline void async_cow_free(struct btrfs_work *work)
1168 struct async_cow *async_cow;
1169 async_cow = container_of(work, struct async_cow, work);
1170 if (async_cow->inode)
1171 btrfs_add_delayed_iput(async_cow->inode);
1175 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1176 u64 start, u64 end, int *page_started,
1177 unsigned long *nr_written,
1178 unsigned int write_flags)
1180 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1181 struct async_cow *async_cow;
1182 struct btrfs_root *root = BTRFS_I(inode)->root;
1183 unsigned long nr_pages;
1186 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1188 while (start < end) {
1189 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1190 BUG_ON(!async_cow); /* -ENOMEM */
1191 async_cow->inode = igrab(inode);
1192 async_cow->root = root;
1193 async_cow->locked_page = locked_page;
1194 async_cow->start = start;
1195 async_cow->write_flags = write_flags;
1197 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1198 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1201 cur_end = min(end, start + SZ_512K - 1);
1203 async_cow->end = cur_end;
1204 INIT_LIST_HEAD(&async_cow->extents);
1206 btrfs_init_work(&async_cow->work,
1207 btrfs_delalloc_helper,
1208 async_cow_start, async_cow_submit,
1211 nr_pages = (cur_end - start + PAGE_SIZE) >>
1213 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1215 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1217 *nr_written += nr_pages;
1218 start = cur_end + 1;
1224 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1225 u64 bytenr, u64 num_bytes)
1228 struct btrfs_ordered_sum *sums;
1231 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1232 bytenr + num_bytes - 1, &list, 0);
1233 if (ret == 0 && list_empty(&list))
1236 while (!list_empty(&list)) {
1237 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1238 list_del(&sums->list);
1247 * when nowcow writeback call back. This checks for snapshots or COW copies
1248 * of the extents that exist in the file, and COWs the file as required.
1250 * If no cow copies or snapshots exist, we write directly to the existing
1253 static noinline int run_delalloc_nocow(struct inode *inode,
1254 struct page *locked_page,
1255 u64 start, u64 end, int *page_started, int force,
1256 unsigned long *nr_written)
1258 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1259 struct btrfs_root *root = BTRFS_I(inode)->root;
1260 struct extent_buffer *leaf;
1261 struct btrfs_path *path;
1262 struct btrfs_file_extent_item *fi;
1263 struct btrfs_key found_key;
1264 struct extent_map *em;
1279 u64 ino = btrfs_ino(BTRFS_I(inode));
1281 path = btrfs_alloc_path();
1283 extent_clear_unlock_delalloc(inode, start, end, end,
1285 EXTENT_LOCKED | EXTENT_DELALLOC |
1286 EXTENT_DO_ACCOUNTING |
1287 EXTENT_DEFRAG, PAGE_UNLOCK |
1289 PAGE_SET_WRITEBACK |
1290 PAGE_END_WRITEBACK);
1294 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1296 cow_start = (u64)-1;
1299 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1303 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1304 leaf = path->nodes[0];
1305 btrfs_item_key_to_cpu(leaf, &found_key,
1306 path->slots[0] - 1);
1307 if (found_key.objectid == ino &&
1308 found_key.type == BTRFS_EXTENT_DATA_KEY)
1313 leaf = path->nodes[0];
1314 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1315 ret = btrfs_next_leaf(root, path);
1317 if (cow_start != (u64)-1)
1318 cur_offset = cow_start;
1323 leaf = path->nodes[0];
1329 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1331 if (found_key.objectid > ino)
1333 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1334 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1338 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1339 found_key.offset > end)
1342 if (found_key.offset > cur_offset) {
1343 extent_end = found_key.offset;
1348 fi = btrfs_item_ptr(leaf, path->slots[0],
1349 struct btrfs_file_extent_item);
1350 extent_type = btrfs_file_extent_type(leaf, fi);
1352 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1353 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1354 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1355 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1356 extent_offset = btrfs_file_extent_offset(leaf, fi);
1357 extent_end = found_key.offset +
1358 btrfs_file_extent_num_bytes(leaf, fi);
1360 btrfs_file_extent_disk_num_bytes(leaf, fi);
1361 if (extent_end <= start) {
1365 if (disk_bytenr == 0)
1367 if (btrfs_file_extent_compression(leaf, fi) ||
1368 btrfs_file_extent_encryption(leaf, fi) ||
1369 btrfs_file_extent_other_encoding(leaf, fi))
1372 * Do the same check as in btrfs_cross_ref_exist but
1373 * without the unnecessary search.
1375 if (btrfs_file_extent_generation(leaf, fi) <=
1376 btrfs_root_last_snapshot(&root->root_item))
1378 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1380 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1382 ret = btrfs_cross_ref_exist(root, ino,
1384 extent_offset, disk_bytenr);
1387 * ret could be -EIO if the above fails to read
1391 if (cow_start != (u64)-1)
1392 cur_offset = cow_start;
1396 WARN_ON_ONCE(nolock);
1399 disk_bytenr += extent_offset;
1400 disk_bytenr += cur_offset - found_key.offset;
1401 num_bytes = min(end + 1, extent_end) - cur_offset;
1403 * if there are pending snapshots for this root,
1404 * we fall into common COW way.
1406 if (!nolock && atomic_read(&root->snapshot_force_cow))
1409 * force cow if csum exists in the range.
1410 * this ensure that csum for a given extent are
1411 * either valid or do not exist.
1413 ret = csum_exist_in_range(fs_info, disk_bytenr,
1417 * ret could be -EIO if the above fails to read
1421 if (cow_start != (u64)-1)
1422 cur_offset = cow_start;
1425 WARN_ON_ONCE(nolock);
1428 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1431 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1432 extent_end = found_key.offset +
1433 btrfs_file_extent_ram_bytes(leaf, fi);
1434 extent_end = ALIGN(extent_end,
1435 fs_info->sectorsize);
1440 if (extent_end <= start) {
1443 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1447 if (cow_start == (u64)-1)
1448 cow_start = cur_offset;
1449 cur_offset = extent_end;
1450 if (cur_offset > end)
1456 btrfs_release_path(path);
1457 if (cow_start != (u64)-1) {
1458 ret = cow_file_range(inode, locked_page,
1459 cow_start, found_key.offset - 1,
1460 end, page_started, nr_written, 1,
1464 btrfs_dec_nocow_writers(fs_info,
1468 cow_start = (u64)-1;
1471 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1472 u64 orig_start = found_key.offset - extent_offset;
1474 em = create_io_em(inode, cur_offset, num_bytes,
1476 disk_bytenr, /* block_start */
1477 num_bytes, /* block_len */
1478 disk_num_bytes, /* orig_block_len */
1479 ram_bytes, BTRFS_COMPRESS_NONE,
1480 BTRFS_ORDERED_PREALLOC);
1483 btrfs_dec_nocow_writers(fs_info,
1488 free_extent_map(em);
1491 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1492 type = BTRFS_ORDERED_PREALLOC;
1494 type = BTRFS_ORDERED_NOCOW;
1497 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1498 num_bytes, num_bytes, type);
1500 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1501 BUG_ON(ret); /* -ENOMEM */
1503 if (root->root_key.objectid ==
1504 BTRFS_DATA_RELOC_TREE_OBJECTID)
1506 * Error handled later, as we must prevent
1507 * extent_clear_unlock_delalloc() in error handler
1508 * from freeing metadata of created ordered extent.
1510 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1513 extent_clear_unlock_delalloc(inode, cur_offset,
1514 cur_offset + num_bytes - 1, end,
1515 locked_page, EXTENT_LOCKED |
1517 EXTENT_CLEAR_DATA_RESV,
1518 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1520 cur_offset = extent_end;
1523 * btrfs_reloc_clone_csums() error, now we're OK to call error
1524 * handler, as metadata for created ordered extent will only
1525 * be freed by btrfs_finish_ordered_io().
1529 if (cur_offset > end)
1532 btrfs_release_path(path);
1534 if (cur_offset <= end && cow_start == (u64)-1)
1535 cow_start = cur_offset;
1537 if (cow_start != (u64)-1) {
1539 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1540 page_started, nr_written, 1, NULL);
1546 if (ret && cur_offset < end)
1547 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1548 locked_page, EXTENT_LOCKED |
1549 EXTENT_DELALLOC | EXTENT_DEFRAG |
1550 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1552 PAGE_SET_WRITEBACK |
1553 PAGE_END_WRITEBACK);
1554 btrfs_free_path(path);
1558 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1561 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1562 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1566 * @defrag_bytes is a hint value, no spinlock held here,
1567 * if is not zero, it means the file is defragging.
1568 * Force cow if given extent needs to be defragged.
1570 if (BTRFS_I(inode)->defrag_bytes &&
1571 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1572 EXTENT_DEFRAG, 0, NULL))
1579 * Function to process delayed allocation (create CoW) for ranges which are
1580 * being touched for the first time.
1582 int btrfs_run_delalloc_range(void *private_data, struct page *locked_page,
1583 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1584 struct writeback_control *wbc)
1586 struct inode *inode = private_data;
1588 int force_cow = need_force_cow(inode, start, end);
1589 unsigned int write_flags = wbc_to_write_flags(wbc);
1591 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1592 ret = run_delalloc_nocow(inode, locked_page, start, end,
1593 page_started, 1, nr_written);
1594 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1595 ret = run_delalloc_nocow(inode, locked_page, start, end,
1596 page_started, 0, nr_written);
1597 } else if (!inode_need_compress(inode, start, end)) {
1598 ret = cow_file_range(inode, locked_page, start, end, end,
1599 page_started, nr_written, 1, NULL);
1601 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1602 &BTRFS_I(inode)->runtime_flags);
1603 ret = cow_file_range_async(inode, locked_page, start, end,
1604 page_started, nr_written,
1608 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1612 void btrfs_split_delalloc_extent(struct inode *inode,
1613 struct extent_state *orig, u64 split)
1617 /* not delalloc, ignore it */
1618 if (!(orig->state & EXTENT_DELALLOC))
1621 size = orig->end - orig->start + 1;
1622 if (size > BTRFS_MAX_EXTENT_SIZE) {
1627 * See the explanation in btrfs_merge_delalloc_extent, the same
1628 * applies here, just in reverse.
1630 new_size = orig->end - split + 1;
1631 num_extents = count_max_extents(new_size);
1632 new_size = split - orig->start;
1633 num_extents += count_max_extents(new_size);
1634 if (count_max_extents(size) >= num_extents)
1638 spin_lock(&BTRFS_I(inode)->lock);
1639 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1640 spin_unlock(&BTRFS_I(inode)->lock);
1644 * Handle merged delayed allocation extents so we can keep track of new extents
1645 * that are just merged onto old extents, such as when we are doing sequential
1646 * writes, so we can properly account for the metadata space we'll need.
1648 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1649 struct extent_state *other)
1651 u64 new_size, old_size;
1654 /* not delalloc, ignore it */
1655 if (!(other->state & EXTENT_DELALLOC))
1658 if (new->start > other->start)
1659 new_size = new->end - other->start + 1;
1661 new_size = other->end - new->start + 1;
1663 /* we're not bigger than the max, unreserve the space and go */
1664 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1665 spin_lock(&BTRFS_I(inode)->lock);
1666 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1667 spin_unlock(&BTRFS_I(inode)->lock);
1672 * We have to add up either side to figure out how many extents were
1673 * accounted for before we merged into one big extent. If the number of
1674 * extents we accounted for is <= the amount we need for the new range
1675 * then we can return, otherwise drop. Think of it like this
1679 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1680 * need 2 outstanding extents, on one side we have 1 and the other side
1681 * we have 1 so they are == and we can return. But in this case
1683 * [MAX_SIZE+4k][MAX_SIZE+4k]
1685 * Each range on their own accounts for 2 extents, but merged together
1686 * they are only 3 extents worth of accounting, so we need to drop in
1689 old_size = other->end - other->start + 1;
1690 num_extents = count_max_extents(old_size);
1691 old_size = new->end - new->start + 1;
1692 num_extents += count_max_extents(old_size);
1693 if (count_max_extents(new_size) >= num_extents)
1696 spin_lock(&BTRFS_I(inode)->lock);
1697 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1698 spin_unlock(&BTRFS_I(inode)->lock);
1701 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1702 struct inode *inode)
1704 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1706 spin_lock(&root->delalloc_lock);
1707 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1708 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1709 &root->delalloc_inodes);
1710 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1711 &BTRFS_I(inode)->runtime_flags);
1712 root->nr_delalloc_inodes++;
1713 if (root->nr_delalloc_inodes == 1) {
1714 spin_lock(&fs_info->delalloc_root_lock);
1715 BUG_ON(!list_empty(&root->delalloc_root));
1716 list_add_tail(&root->delalloc_root,
1717 &fs_info->delalloc_roots);
1718 spin_unlock(&fs_info->delalloc_root_lock);
1721 spin_unlock(&root->delalloc_lock);
1725 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1726 struct btrfs_inode *inode)
1728 struct btrfs_fs_info *fs_info = root->fs_info;
1730 if (!list_empty(&inode->delalloc_inodes)) {
1731 list_del_init(&inode->delalloc_inodes);
1732 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1733 &inode->runtime_flags);
1734 root->nr_delalloc_inodes--;
1735 if (!root->nr_delalloc_inodes) {
1736 ASSERT(list_empty(&root->delalloc_inodes));
1737 spin_lock(&fs_info->delalloc_root_lock);
1738 BUG_ON(list_empty(&root->delalloc_root));
1739 list_del_init(&root->delalloc_root);
1740 spin_unlock(&fs_info->delalloc_root_lock);
1745 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1746 struct btrfs_inode *inode)
1748 spin_lock(&root->delalloc_lock);
1749 __btrfs_del_delalloc_inode(root, inode);
1750 spin_unlock(&root->delalloc_lock);
1754 * Properly track delayed allocation bytes in the inode and to maintain the
1755 * list of inodes that have pending delalloc work to be done.
1757 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1760 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1762 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1765 * set_bit and clear bit hooks normally require _irqsave/restore
1766 * but in this case, we are only testing for the DELALLOC
1767 * bit, which is only set or cleared with irqs on
1769 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1770 struct btrfs_root *root = BTRFS_I(inode)->root;
1771 u64 len = state->end + 1 - state->start;
1772 u32 num_extents = count_max_extents(len);
1773 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1775 spin_lock(&BTRFS_I(inode)->lock);
1776 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1777 spin_unlock(&BTRFS_I(inode)->lock);
1779 /* For sanity tests */
1780 if (btrfs_is_testing(fs_info))
1783 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1784 fs_info->delalloc_batch);
1785 spin_lock(&BTRFS_I(inode)->lock);
1786 BTRFS_I(inode)->delalloc_bytes += len;
1787 if (*bits & EXTENT_DEFRAG)
1788 BTRFS_I(inode)->defrag_bytes += len;
1789 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1790 &BTRFS_I(inode)->runtime_flags))
1791 btrfs_add_delalloc_inodes(root, inode);
1792 spin_unlock(&BTRFS_I(inode)->lock);
1795 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1796 (*bits & EXTENT_DELALLOC_NEW)) {
1797 spin_lock(&BTRFS_I(inode)->lock);
1798 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1800 spin_unlock(&BTRFS_I(inode)->lock);
1805 * Once a range is no longer delalloc this function ensures that proper
1806 * accounting happens.
1808 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1809 struct extent_state *state, unsigned *bits)
1811 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1812 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1813 u64 len = state->end + 1 - state->start;
1814 u32 num_extents = count_max_extents(len);
1816 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1817 spin_lock(&inode->lock);
1818 inode->defrag_bytes -= len;
1819 spin_unlock(&inode->lock);
1823 * set_bit and clear bit hooks normally require _irqsave/restore
1824 * but in this case, we are only testing for the DELALLOC
1825 * bit, which is only set or cleared with irqs on
1827 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1828 struct btrfs_root *root = inode->root;
1829 bool do_list = !btrfs_is_free_space_inode(inode);
1831 spin_lock(&inode->lock);
1832 btrfs_mod_outstanding_extents(inode, -num_extents);
1833 spin_unlock(&inode->lock);
1836 * We don't reserve metadata space for space cache inodes so we
1837 * don't need to call dellalloc_release_metadata if there is an
1840 if (*bits & EXTENT_CLEAR_META_RESV &&
1841 root != fs_info->tree_root)
1842 btrfs_delalloc_release_metadata(inode, len, false);
1844 /* For sanity tests. */
1845 if (btrfs_is_testing(fs_info))
1848 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1849 do_list && !(state->state & EXTENT_NORESERVE) &&
1850 (*bits & EXTENT_CLEAR_DATA_RESV))
1851 btrfs_free_reserved_data_space_noquota(
1855 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1856 fs_info->delalloc_batch);
1857 spin_lock(&inode->lock);
1858 inode->delalloc_bytes -= len;
1859 if (do_list && inode->delalloc_bytes == 0 &&
1860 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1861 &inode->runtime_flags))
1862 btrfs_del_delalloc_inode(root, inode);
1863 spin_unlock(&inode->lock);
1866 if ((state->state & EXTENT_DELALLOC_NEW) &&
1867 (*bits & EXTENT_DELALLOC_NEW)) {
1868 spin_lock(&inode->lock);
1869 ASSERT(inode->new_delalloc_bytes >= len);
1870 inode->new_delalloc_bytes -= len;
1871 spin_unlock(&inode->lock);
1876 * Merge bio hook, this must check the chunk tree to make sure we don't create
1877 * bios that span stripes or chunks
1879 * return 1 if page cannot be merged to bio
1880 * return 0 if page can be merged to bio
1881 * return error otherwise
1883 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1884 size_t size, struct bio *bio,
1885 unsigned long bio_flags)
1887 struct inode *inode = page->mapping->host;
1888 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1889 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1894 if (bio_flags & EXTENT_BIO_COMPRESSED)
1897 length = bio->bi_iter.bi_size;
1898 map_length = length;
1899 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1903 if (map_length < length + size)
1909 * in order to insert checksums into the metadata in large chunks,
1910 * we wait until bio submission time. All the pages in the bio are
1911 * checksummed and sums are attached onto the ordered extent record.
1913 * At IO completion time the cums attached on the ordered extent record
1914 * are inserted into the btree
1916 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1919 struct inode *inode = private_data;
1920 blk_status_t ret = 0;
1922 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1923 BUG_ON(ret); /* -ENOMEM */
1928 * in order to insert checksums into the metadata in large chunks,
1929 * we wait until bio submission time. All the pages in the bio are
1930 * checksummed and sums are attached onto the ordered extent record.
1932 * At IO completion time the cums attached on the ordered extent record
1933 * are inserted into the btree
1935 blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1938 struct inode *inode = private_data;
1939 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1942 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1944 bio->bi_status = ret;
1951 * extent_io.c submission hook. This does the right thing for csum calculation
1952 * on write, or reading the csums from the tree before a read.
1954 * Rules about async/sync submit,
1955 * a) read: sync submit
1957 * b) write without checksum: sync submit
1959 * c) write with checksum:
1960 * c-1) if bio is issued by fsync: sync submit
1961 * (sync_writers != 0)
1963 * c-2) if root is reloc root: sync submit
1964 * (only in case of buffered IO)
1966 * c-3) otherwise: async submit
1968 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1969 int mirror_num, unsigned long bio_flags,
1972 struct inode *inode = private_data;
1973 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1974 struct btrfs_root *root = BTRFS_I(inode)->root;
1975 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1976 blk_status_t ret = 0;
1978 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1980 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1982 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1983 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1985 if (bio_op(bio) != REQ_OP_WRITE) {
1986 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1990 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1991 ret = btrfs_submit_compressed_read(inode, bio,
1995 } else if (!skip_sum) {
1996 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2001 } else if (async && !skip_sum) {
2002 /* csum items have already been cloned */
2003 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2005 /* we're doing a write, do the async checksumming */
2006 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2008 btrfs_submit_bio_start);
2010 } else if (!skip_sum) {
2011 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2017 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2021 bio->bi_status = ret;
2028 * given a list of ordered sums record them in the inode. This happens
2029 * at IO completion time based on sums calculated at bio submission time.
2031 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2032 struct inode *inode, struct list_head *list)
2034 struct btrfs_ordered_sum *sum;
2037 list_for_each_entry(sum, list, list) {
2038 trans->adding_csums = true;
2039 ret = btrfs_csum_file_blocks(trans,
2040 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2041 trans->adding_csums = false;
2048 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2049 unsigned int extra_bits,
2050 struct extent_state **cached_state, int dedupe)
2052 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2053 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2054 extra_bits, cached_state);
2057 /* see btrfs_writepage_start_hook for details on why this is required */
2058 struct btrfs_writepage_fixup {
2060 struct btrfs_work work;
2063 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2065 struct btrfs_writepage_fixup *fixup;
2066 struct btrfs_ordered_extent *ordered;
2067 struct extent_state *cached_state = NULL;
2068 struct extent_changeset *data_reserved = NULL;
2070 struct inode *inode;
2075 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2079 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2080 ClearPageChecked(page);
2084 inode = page->mapping->host;
2085 page_start = page_offset(page);
2086 page_end = page_offset(page) + PAGE_SIZE - 1;
2088 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2091 /* already ordered? We're done */
2092 if (PagePrivate2(page))
2095 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2098 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2099 page_end, &cached_state);
2101 btrfs_start_ordered_extent(inode, ordered, 1);
2102 btrfs_put_ordered_extent(ordered);
2106 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2109 mapping_set_error(page->mapping, ret);
2110 end_extent_writepage(page, ret, page_start, page_end);
2111 ClearPageChecked(page);
2115 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2118 mapping_set_error(page->mapping, ret);
2119 end_extent_writepage(page, ret, page_start, page_end);
2120 ClearPageChecked(page);
2124 ClearPageChecked(page);
2125 set_page_dirty(page);
2126 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2128 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2134 extent_changeset_free(data_reserved);
2138 * There are a few paths in the higher layers of the kernel that directly
2139 * set the page dirty bit without asking the filesystem if it is a
2140 * good idea. This causes problems because we want to make sure COW
2141 * properly happens and the data=ordered rules are followed.
2143 * In our case any range that doesn't have the ORDERED bit set
2144 * hasn't been properly setup for IO. We kick off an async process
2145 * to fix it up. The async helper will wait for ordered extents, set
2146 * the delalloc bit and make it safe to write the page.
2148 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2150 struct inode *inode = page->mapping->host;
2151 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2152 struct btrfs_writepage_fixup *fixup;
2154 /* this page is properly in the ordered list */
2155 if (TestClearPagePrivate2(page))
2158 if (PageChecked(page))
2161 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2165 SetPageChecked(page);
2167 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2168 btrfs_writepage_fixup_worker, NULL, NULL);
2170 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2174 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2175 struct inode *inode, u64 file_pos,
2176 u64 disk_bytenr, u64 disk_num_bytes,
2177 u64 num_bytes, u64 ram_bytes,
2178 u8 compression, u8 encryption,
2179 u16 other_encoding, int extent_type)
2181 struct btrfs_root *root = BTRFS_I(inode)->root;
2182 struct btrfs_file_extent_item *fi;
2183 struct btrfs_path *path;
2184 struct extent_buffer *leaf;
2185 struct btrfs_key ins;
2187 int extent_inserted = 0;
2190 path = btrfs_alloc_path();
2195 * we may be replacing one extent in the tree with another.
2196 * The new extent is pinned in the extent map, and we don't want
2197 * to drop it from the cache until it is completely in the btree.
2199 * So, tell btrfs_drop_extents to leave this extent in the cache.
2200 * the caller is expected to unpin it and allow it to be merged
2203 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2204 file_pos + num_bytes, NULL, 0,
2205 1, sizeof(*fi), &extent_inserted);
2209 if (!extent_inserted) {
2210 ins.objectid = btrfs_ino(BTRFS_I(inode));
2211 ins.offset = file_pos;
2212 ins.type = BTRFS_EXTENT_DATA_KEY;
2214 path->leave_spinning = 1;
2215 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2220 leaf = path->nodes[0];
2221 fi = btrfs_item_ptr(leaf, path->slots[0],
2222 struct btrfs_file_extent_item);
2223 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2224 btrfs_set_file_extent_type(leaf, fi, extent_type);
2225 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2226 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2227 btrfs_set_file_extent_offset(leaf, fi, 0);
2228 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2229 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2230 btrfs_set_file_extent_compression(leaf, fi, compression);
2231 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2232 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2234 btrfs_mark_buffer_dirty(leaf);
2235 btrfs_release_path(path);
2237 inode_add_bytes(inode, num_bytes);
2239 ins.objectid = disk_bytenr;
2240 ins.offset = disk_num_bytes;
2241 ins.type = BTRFS_EXTENT_ITEM_KEY;
2244 * Release the reserved range from inode dirty range map, as it is
2245 * already moved into delayed_ref_head
2247 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2251 ret = btrfs_alloc_reserved_file_extent(trans, root,
2252 btrfs_ino(BTRFS_I(inode)),
2253 file_pos, qg_released, &ins);
2255 btrfs_free_path(path);
2260 /* snapshot-aware defrag */
2261 struct sa_defrag_extent_backref {
2262 struct rb_node node;
2263 struct old_sa_defrag_extent *old;
2272 struct old_sa_defrag_extent {
2273 struct list_head list;
2274 struct new_sa_defrag_extent *new;
2283 struct new_sa_defrag_extent {
2284 struct rb_root root;
2285 struct list_head head;
2286 struct btrfs_path *path;
2287 struct inode *inode;
2295 static int backref_comp(struct sa_defrag_extent_backref *b1,
2296 struct sa_defrag_extent_backref *b2)
2298 if (b1->root_id < b2->root_id)
2300 else if (b1->root_id > b2->root_id)
2303 if (b1->inum < b2->inum)
2305 else if (b1->inum > b2->inum)
2308 if (b1->file_pos < b2->file_pos)
2310 else if (b1->file_pos > b2->file_pos)
2314 * [------------------------------] ===> (a range of space)
2315 * |<--->| |<---->| =============> (fs/file tree A)
2316 * |<---------------------------->| ===> (fs/file tree B)
2318 * A range of space can refer to two file extents in one tree while
2319 * refer to only one file extent in another tree.
2321 * So we may process a disk offset more than one time(two extents in A)
2322 * and locate at the same extent(one extent in B), then insert two same
2323 * backrefs(both refer to the extent in B).
2328 static void backref_insert(struct rb_root *root,
2329 struct sa_defrag_extent_backref *backref)
2331 struct rb_node **p = &root->rb_node;
2332 struct rb_node *parent = NULL;
2333 struct sa_defrag_extent_backref *entry;
2338 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2340 ret = backref_comp(backref, entry);
2344 p = &(*p)->rb_right;
2347 rb_link_node(&backref->node, parent, p);
2348 rb_insert_color(&backref->node, root);
2352 * Note the backref might has changed, and in this case we just return 0.
2354 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2357 struct btrfs_file_extent_item *extent;
2358 struct old_sa_defrag_extent *old = ctx;
2359 struct new_sa_defrag_extent *new = old->new;
2360 struct btrfs_path *path = new->path;
2361 struct btrfs_key key;
2362 struct btrfs_root *root;
2363 struct sa_defrag_extent_backref *backref;
2364 struct extent_buffer *leaf;
2365 struct inode *inode = new->inode;
2366 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2372 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2373 inum == btrfs_ino(BTRFS_I(inode)))
2376 key.objectid = root_id;
2377 key.type = BTRFS_ROOT_ITEM_KEY;
2378 key.offset = (u64)-1;
2380 root = btrfs_read_fs_root_no_name(fs_info, &key);
2382 if (PTR_ERR(root) == -ENOENT)
2385 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2386 inum, offset, root_id);
2387 return PTR_ERR(root);
2390 key.objectid = inum;
2391 key.type = BTRFS_EXTENT_DATA_KEY;
2392 if (offset > (u64)-1 << 32)
2395 key.offset = offset;
2397 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2398 if (WARN_ON(ret < 0))
2405 leaf = path->nodes[0];
2406 slot = path->slots[0];
2408 if (slot >= btrfs_header_nritems(leaf)) {
2409 ret = btrfs_next_leaf(root, path);
2412 } else if (ret > 0) {
2421 btrfs_item_key_to_cpu(leaf, &key, slot);
2423 if (key.objectid > inum)
2426 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2429 extent = btrfs_item_ptr(leaf, slot,
2430 struct btrfs_file_extent_item);
2432 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2436 * 'offset' refers to the exact key.offset,
2437 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2438 * (key.offset - extent_offset).
2440 if (key.offset != offset)
2443 extent_offset = btrfs_file_extent_offset(leaf, extent);
2444 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2446 if (extent_offset >= old->extent_offset + old->offset +
2447 old->len || extent_offset + num_bytes <=
2448 old->extent_offset + old->offset)
2453 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2459 backref->root_id = root_id;
2460 backref->inum = inum;
2461 backref->file_pos = offset;
2462 backref->num_bytes = num_bytes;
2463 backref->extent_offset = extent_offset;
2464 backref->generation = btrfs_file_extent_generation(leaf, extent);
2466 backref_insert(&new->root, backref);
2469 btrfs_release_path(path);
2474 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2475 struct new_sa_defrag_extent *new)
2477 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2478 struct old_sa_defrag_extent *old, *tmp;
2483 list_for_each_entry_safe(old, tmp, &new->head, list) {
2484 ret = iterate_inodes_from_logical(old->bytenr +
2485 old->extent_offset, fs_info,
2486 path, record_one_backref,
2488 if (ret < 0 && ret != -ENOENT)
2491 /* no backref to be processed for this extent */
2493 list_del(&old->list);
2498 if (list_empty(&new->head))
2504 static int relink_is_mergable(struct extent_buffer *leaf,
2505 struct btrfs_file_extent_item *fi,
2506 struct new_sa_defrag_extent *new)
2508 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2511 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2514 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2517 if (btrfs_file_extent_encryption(leaf, fi) ||
2518 btrfs_file_extent_other_encoding(leaf, fi))
2525 * Note the backref might has changed, and in this case we just return 0.
2527 static noinline int relink_extent_backref(struct btrfs_path *path,
2528 struct sa_defrag_extent_backref *prev,
2529 struct sa_defrag_extent_backref *backref)
2531 struct btrfs_file_extent_item *extent;
2532 struct btrfs_file_extent_item *item;
2533 struct btrfs_ordered_extent *ordered;
2534 struct btrfs_trans_handle *trans;
2535 struct btrfs_root *root;
2536 struct btrfs_key key;
2537 struct extent_buffer *leaf;
2538 struct old_sa_defrag_extent *old = backref->old;
2539 struct new_sa_defrag_extent *new = old->new;
2540 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2541 struct inode *inode;
2542 struct extent_state *cached = NULL;
2551 if (prev && prev->root_id == backref->root_id &&
2552 prev->inum == backref->inum &&
2553 prev->file_pos + prev->num_bytes == backref->file_pos)
2556 /* step 1: get root */
2557 key.objectid = backref->root_id;
2558 key.type = BTRFS_ROOT_ITEM_KEY;
2559 key.offset = (u64)-1;
2561 index = srcu_read_lock(&fs_info->subvol_srcu);
2563 root = btrfs_read_fs_root_no_name(fs_info, &key);
2565 srcu_read_unlock(&fs_info->subvol_srcu, index);
2566 if (PTR_ERR(root) == -ENOENT)
2568 return PTR_ERR(root);
2571 if (btrfs_root_readonly(root)) {
2572 srcu_read_unlock(&fs_info->subvol_srcu, index);
2576 /* step 2: get inode */
2577 key.objectid = backref->inum;
2578 key.type = BTRFS_INODE_ITEM_KEY;
2581 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2582 if (IS_ERR(inode)) {
2583 srcu_read_unlock(&fs_info->subvol_srcu, index);
2587 srcu_read_unlock(&fs_info->subvol_srcu, index);
2589 /* step 3: relink backref */
2590 lock_start = backref->file_pos;
2591 lock_end = backref->file_pos + backref->num_bytes - 1;
2592 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2595 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2597 btrfs_put_ordered_extent(ordered);
2601 trans = btrfs_join_transaction(root);
2602 if (IS_ERR(trans)) {
2603 ret = PTR_ERR(trans);
2607 key.objectid = backref->inum;
2608 key.type = BTRFS_EXTENT_DATA_KEY;
2609 key.offset = backref->file_pos;
2611 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2614 } else if (ret > 0) {
2619 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2620 struct btrfs_file_extent_item);
2622 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2623 backref->generation)
2626 btrfs_release_path(path);
2628 start = backref->file_pos;
2629 if (backref->extent_offset < old->extent_offset + old->offset)
2630 start += old->extent_offset + old->offset -
2631 backref->extent_offset;
2633 len = min(backref->extent_offset + backref->num_bytes,
2634 old->extent_offset + old->offset + old->len);
2635 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2637 ret = btrfs_drop_extents(trans, root, inode, start,
2642 key.objectid = btrfs_ino(BTRFS_I(inode));
2643 key.type = BTRFS_EXTENT_DATA_KEY;
2646 path->leave_spinning = 1;
2648 struct btrfs_file_extent_item *fi;
2650 struct btrfs_key found_key;
2652 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2657 leaf = path->nodes[0];
2658 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2660 fi = btrfs_item_ptr(leaf, path->slots[0],
2661 struct btrfs_file_extent_item);
2662 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2664 if (extent_len + found_key.offset == start &&
2665 relink_is_mergable(leaf, fi, new)) {
2666 btrfs_set_file_extent_num_bytes(leaf, fi,
2668 btrfs_mark_buffer_dirty(leaf);
2669 inode_add_bytes(inode, len);
2675 btrfs_release_path(path);
2680 ret = btrfs_insert_empty_item(trans, root, path, &key,
2683 btrfs_abort_transaction(trans, ret);
2687 leaf = path->nodes[0];
2688 item = btrfs_item_ptr(leaf, path->slots[0],
2689 struct btrfs_file_extent_item);
2690 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2691 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2692 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2693 btrfs_set_file_extent_num_bytes(leaf, item, len);
2694 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2695 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2696 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2697 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2698 btrfs_set_file_extent_encryption(leaf, item, 0);
2699 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2701 btrfs_mark_buffer_dirty(leaf);
2702 inode_add_bytes(inode, len);
2703 btrfs_release_path(path);
2705 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2707 backref->root_id, backref->inum,
2708 new->file_pos); /* start - extent_offset */
2710 btrfs_abort_transaction(trans, ret);
2716 btrfs_release_path(path);
2717 path->leave_spinning = 0;
2718 btrfs_end_transaction(trans);
2720 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2726 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2728 struct old_sa_defrag_extent *old, *tmp;
2733 list_for_each_entry_safe(old, tmp, &new->head, list) {
2739 static void relink_file_extents(struct new_sa_defrag_extent *new)
2741 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2742 struct btrfs_path *path;
2743 struct sa_defrag_extent_backref *backref;
2744 struct sa_defrag_extent_backref *prev = NULL;
2745 struct rb_node *node;
2748 path = btrfs_alloc_path();
2752 if (!record_extent_backrefs(path, new)) {
2753 btrfs_free_path(path);
2756 btrfs_release_path(path);
2759 node = rb_first(&new->root);
2762 rb_erase(node, &new->root);
2764 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2766 ret = relink_extent_backref(path, prev, backref);
2779 btrfs_free_path(path);
2781 free_sa_defrag_extent(new);
2783 atomic_dec(&fs_info->defrag_running);
2784 wake_up(&fs_info->transaction_wait);
2787 static struct new_sa_defrag_extent *
2788 record_old_file_extents(struct inode *inode,
2789 struct btrfs_ordered_extent *ordered)
2791 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2792 struct btrfs_root *root = BTRFS_I(inode)->root;
2793 struct btrfs_path *path;
2794 struct btrfs_key key;
2795 struct old_sa_defrag_extent *old;
2796 struct new_sa_defrag_extent *new;
2799 new = kmalloc(sizeof(*new), GFP_NOFS);
2804 new->file_pos = ordered->file_offset;
2805 new->len = ordered->len;
2806 new->bytenr = ordered->start;
2807 new->disk_len = ordered->disk_len;
2808 new->compress_type = ordered->compress_type;
2809 new->root = RB_ROOT;
2810 INIT_LIST_HEAD(&new->head);
2812 path = btrfs_alloc_path();
2816 key.objectid = btrfs_ino(BTRFS_I(inode));
2817 key.type = BTRFS_EXTENT_DATA_KEY;
2818 key.offset = new->file_pos;
2820 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2823 if (ret > 0 && path->slots[0] > 0)
2826 /* find out all the old extents for the file range */
2828 struct btrfs_file_extent_item *extent;
2829 struct extent_buffer *l;
2838 slot = path->slots[0];
2840 if (slot >= btrfs_header_nritems(l)) {
2841 ret = btrfs_next_leaf(root, path);
2849 btrfs_item_key_to_cpu(l, &key, slot);
2851 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2853 if (key.type != BTRFS_EXTENT_DATA_KEY)
2855 if (key.offset >= new->file_pos + new->len)
2858 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2860 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2861 if (key.offset + num_bytes < new->file_pos)
2864 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2868 extent_offset = btrfs_file_extent_offset(l, extent);
2870 old = kmalloc(sizeof(*old), GFP_NOFS);
2874 offset = max(new->file_pos, key.offset);
2875 end = min(new->file_pos + new->len, key.offset + num_bytes);
2877 old->bytenr = disk_bytenr;
2878 old->extent_offset = extent_offset;
2879 old->offset = offset - key.offset;
2880 old->len = end - offset;
2883 list_add_tail(&old->list, &new->head);
2889 btrfs_free_path(path);
2890 atomic_inc(&fs_info->defrag_running);
2895 btrfs_free_path(path);
2897 free_sa_defrag_extent(new);
2901 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2904 struct btrfs_block_group_cache *cache;
2906 cache = btrfs_lookup_block_group(fs_info, start);
2909 spin_lock(&cache->lock);
2910 cache->delalloc_bytes -= len;
2911 spin_unlock(&cache->lock);
2913 btrfs_put_block_group(cache);
2916 /* as ordered data IO finishes, this gets called so we can finish
2917 * an ordered extent if the range of bytes in the file it covers are
2920 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2922 struct inode *inode = ordered_extent->inode;
2923 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2924 struct btrfs_root *root = BTRFS_I(inode)->root;
2925 struct btrfs_trans_handle *trans = NULL;
2926 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2927 struct extent_state *cached_state = NULL;
2928 struct new_sa_defrag_extent *new = NULL;
2929 int compress_type = 0;
2931 u64 logical_len = ordered_extent->len;
2933 bool truncated = false;
2934 bool range_locked = false;
2935 bool clear_new_delalloc_bytes = false;
2936 bool clear_reserved_extent = true;
2938 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2939 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2940 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2941 clear_new_delalloc_bytes = true;
2943 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2945 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2950 btrfs_free_io_failure_record(BTRFS_I(inode),
2951 ordered_extent->file_offset,
2952 ordered_extent->file_offset +
2953 ordered_extent->len - 1);
2955 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2957 logical_len = ordered_extent->truncated_len;
2958 /* Truncated the entire extent, don't bother adding */
2963 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2964 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2967 * For mwrite(mmap + memset to write) case, we still reserve
2968 * space for NOCOW range.
2969 * As NOCOW won't cause a new delayed ref, just free the space
2971 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2972 ordered_extent->len);
2973 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2975 trans = btrfs_join_transaction_nolock(root);
2977 trans = btrfs_join_transaction(root);
2978 if (IS_ERR(trans)) {
2979 ret = PTR_ERR(trans);
2983 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2984 ret = btrfs_update_inode_fallback(trans, root, inode);
2985 if (ret) /* -ENOMEM or corruption */
2986 btrfs_abort_transaction(trans, ret);
2990 range_locked = true;
2991 lock_extent_bits(io_tree, ordered_extent->file_offset,
2992 ordered_extent->file_offset + ordered_extent->len - 1,
2995 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2996 ordered_extent->file_offset + ordered_extent->len - 1,
2997 EXTENT_DEFRAG, 0, cached_state);
2999 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3000 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3001 /* the inode is shared */
3002 new = record_old_file_extents(inode, ordered_extent);
3004 clear_extent_bit(io_tree, ordered_extent->file_offset,
3005 ordered_extent->file_offset + ordered_extent->len - 1,
3006 EXTENT_DEFRAG, 0, 0, &cached_state);
3010 trans = btrfs_join_transaction_nolock(root);
3012 trans = btrfs_join_transaction(root);
3013 if (IS_ERR(trans)) {
3014 ret = PTR_ERR(trans);
3019 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3021 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3022 compress_type = ordered_extent->compress_type;
3023 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3024 BUG_ON(compress_type);
3025 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3026 ordered_extent->len);
3027 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3028 ordered_extent->file_offset,
3029 ordered_extent->file_offset +
3032 BUG_ON(root == fs_info->tree_root);
3033 ret = insert_reserved_file_extent(trans, inode,
3034 ordered_extent->file_offset,
3035 ordered_extent->start,
3036 ordered_extent->disk_len,
3037 logical_len, logical_len,
3038 compress_type, 0, 0,
3039 BTRFS_FILE_EXTENT_REG);
3041 clear_reserved_extent = false;
3042 btrfs_release_delalloc_bytes(fs_info,
3043 ordered_extent->start,
3044 ordered_extent->disk_len);
3047 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3048 ordered_extent->file_offset, ordered_extent->len,
3051 btrfs_abort_transaction(trans, ret);
3055 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3057 btrfs_abort_transaction(trans, ret);
3061 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3062 ret = btrfs_update_inode_fallback(trans, root, inode);
3063 if (ret) { /* -ENOMEM or corruption */
3064 btrfs_abort_transaction(trans, ret);
3069 if (range_locked || clear_new_delalloc_bytes) {
3070 unsigned int clear_bits = 0;
3073 clear_bits |= EXTENT_LOCKED;
3074 if (clear_new_delalloc_bytes)
3075 clear_bits |= EXTENT_DELALLOC_NEW;
3076 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3077 ordered_extent->file_offset,
3078 ordered_extent->file_offset +
3079 ordered_extent->len - 1,
3081 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3086 btrfs_end_transaction(trans);
3088 if (ret || truncated) {
3092 start = ordered_extent->file_offset + logical_len;
3094 start = ordered_extent->file_offset;
3095 end = ordered_extent->file_offset + ordered_extent->len - 1;
3096 clear_extent_uptodate(io_tree, start, end, NULL);
3098 /* Drop the cache for the part of the extent we didn't write. */
3099 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3102 * If the ordered extent had an IOERR or something else went
3103 * wrong we need to return the space for this ordered extent
3104 * back to the allocator. We only free the extent in the
3105 * truncated case if we didn't write out the extent at all.
3107 * If we made it past insert_reserved_file_extent before we
3108 * errored out then we don't need to do this as the accounting
3109 * has already been done.
3111 if ((ret || !logical_len) &&
3112 clear_reserved_extent &&
3113 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3114 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3115 btrfs_free_reserved_extent(fs_info,
3116 ordered_extent->start,
3117 ordered_extent->disk_len, 1);
3122 * This needs to be done to make sure anybody waiting knows we are done
3123 * updating everything for this ordered extent.
3125 btrfs_remove_ordered_extent(inode, ordered_extent);
3127 /* for snapshot-aware defrag */
3130 free_sa_defrag_extent(new);
3131 atomic_dec(&fs_info->defrag_running);
3133 relink_file_extents(new);
3138 btrfs_put_ordered_extent(ordered_extent);
3139 /* once for the tree */
3140 btrfs_put_ordered_extent(ordered_extent);
3142 /* Try to release some metadata so we don't get an OOM but don't wait */
3143 btrfs_btree_balance_dirty_nodelay(fs_info);
3148 static void finish_ordered_fn(struct btrfs_work *work)
3150 struct btrfs_ordered_extent *ordered_extent;
3151 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3152 btrfs_finish_ordered_io(ordered_extent);
3155 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3156 u64 end, int uptodate)
3158 struct inode *inode = page->mapping->host;
3159 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3160 struct btrfs_ordered_extent *ordered_extent = NULL;
3161 struct btrfs_workqueue *wq;
3162 btrfs_work_func_t func;
3164 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3166 ClearPagePrivate2(page);
3167 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3168 end - start + 1, uptodate))
3171 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3172 wq = fs_info->endio_freespace_worker;
3173 func = btrfs_freespace_write_helper;
3175 wq = fs_info->endio_write_workers;
3176 func = btrfs_endio_write_helper;
3179 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3181 btrfs_queue_work(wq, &ordered_extent->work);
3184 static int __readpage_endio_check(struct inode *inode,
3185 struct btrfs_io_bio *io_bio,
3186 int icsum, struct page *page,
3187 int pgoff, u64 start, size_t len)
3193 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3195 kaddr = kmap_atomic(page);
3196 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3197 btrfs_csum_final(csum, (u8 *)&csum);
3198 if (csum != csum_expected)
3201 kunmap_atomic(kaddr);
3204 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3205 io_bio->mirror_num);
3206 memset(kaddr + pgoff, 1, len);
3207 flush_dcache_page(page);
3208 kunmap_atomic(kaddr);
3213 * when reads are done, we need to check csums to verify the data is correct
3214 * if there's a match, we allow the bio to finish. If not, the code in
3215 * extent_io.c will try to find good copies for us.
3217 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3218 u64 phy_offset, struct page *page,
3219 u64 start, u64 end, int mirror)
3221 size_t offset = start - page_offset(page);
3222 struct inode *inode = page->mapping->host;
3223 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3224 struct btrfs_root *root = BTRFS_I(inode)->root;
3226 if (PageChecked(page)) {
3227 ClearPageChecked(page);
3231 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3234 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3235 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3236 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3240 phy_offset >>= inode->i_sb->s_blocksize_bits;
3241 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3242 start, (size_t)(end - start + 1));
3246 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3248 * @inode: The inode we want to perform iput on
3250 * This function uses the generic vfs_inode::i_count to track whether we should
3251 * just decrement it (in case it's > 1) or if this is the last iput then link
3252 * the inode to the delayed iput machinery. Delayed iputs are processed at
3253 * transaction commit time/superblock commit/cleaner kthread.
3255 void btrfs_add_delayed_iput(struct inode *inode)
3257 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3258 struct btrfs_inode *binode = BTRFS_I(inode);
3260 if (atomic_add_unless(&inode->i_count, -1, 1))
3263 spin_lock(&fs_info->delayed_iput_lock);
3264 ASSERT(list_empty(&binode->delayed_iput));
3265 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3266 spin_unlock(&fs_info->delayed_iput_lock);
3269 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3272 spin_lock(&fs_info->delayed_iput_lock);
3273 while (!list_empty(&fs_info->delayed_iputs)) {
3274 struct btrfs_inode *inode;
3276 inode = list_first_entry(&fs_info->delayed_iputs,
3277 struct btrfs_inode, delayed_iput);
3278 list_del_init(&inode->delayed_iput);
3279 spin_unlock(&fs_info->delayed_iput_lock);
3280 iput(&inode->vfs_inode);
3281 spin_lock(&fs_info->delayed_iput_lock);
3283 spin_unlock(&fs_info->delayed_iput_lock);
3287 * This creates an orphan entry for the given inode in case something goes wrong
3288 * in the middle of an unlink.
3290 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3291 struct btrfs_inode *inode)
3295 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3296 if (ret && ret != -EEXIST) {
3297 btrfs_abort_transaction(trans, ret);
3305 * We have done the delete so we can go ahead and remove the orphan item for
3306 * this particular inode.
3308 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3309 struct btrfs_inode *inode)
3311 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3315 * this cleans up any orphans that may be left on the list from the last use
3318 int btrfs_orphan_cleanup(struct btrfs_root *root)
3320 struct btrfs_fs_info *fs_info = root->fs_info;
3321 struct btrfs_path *path;
3322 struct extent_buffer *leaf;
3323 struct btrfs_key key, found_key;
3324 struct btrfs_trans_handle *trans;
3325 struct inode *inode;
3326 u64 last_objectid = 0;
3327 int ret = 0, nr_unlink = 0;
3329 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3332 path = btrfs_alloc_path();
3337 path->reada = READA_BACK;
3339 key.objectid = BTRFS_ORPHAN_OBJECTID;
3340 key.type = BTRFS_ORPHAN_ITEM_KEY;
3341 key.offset = (u64)-1;
3344 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3349 * if ret == 0 means we found what we were searching for, which
3350 * is weird, but possible, so only screw with path if we didn't
3351 * find the key and see if we have stuff that matches
3355 if (path->slots[0] == 0)
3360 /* pull out the item */
3361 leaf = path->nodes[0];
3362 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3364 /* make sure the item matches what we want */
3365 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3367 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3370 /* release the path since we're done with it */
3371 btrfs_release_path(path);
3374 * this is where we are basically btrfs_lookup, without the
3375 * crossing root thing. we store the inode number in the
3376 * offset of the orphan item.
3379 if (found_key.offset == last_objectid) {
3381 "Error removing orphan entry, stopping orphan cleanup");
3386 last_objectid = found_key.offset;
3388 found_key.objectid = found_key.offset;
3389 found_key.type = BTRFS_INODE_ITEM_KEY;
3390 found_key.offset = 0;
3391 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3392 ret = PTR_ERR_OR_ZERO(inode);
3393 if (ret && ret != -ENOENT)
3396 if (ret == -ENOENT && root == fs_info->tree_root) {
3397 struct btrfs_root *dead_root;
3398 struct btrfs_fs_info *fs_info = root->fs_info;
3399 int is_dead_root = 0;
3402 * this is an orphan in the tree root. Currently these
3403 * could come from 2 sources:
3404 * a) a snapshot deletion in progress
3405 * b) a free space cache inode
3406 * We need to distinguish those two, as the snapshot
3407 * orphan must not get deleted.
3408 * find_dead_roots already ran before us, so if this
3409 * is a snapshot deletion, we should find the root
3410 * in the dead_roots list
3412 spin_lock(&fs_info->trans_lock);
3413 list_for_each_entry(dead_root, &fs_info->dead_roots,
3415 if (dead_root->root_key.objectid ==
3416 found_key.objectid) {
3421 spin_unlock(&fs_info->trans_lock);
3423 /* prevent this orphan from being found again */
3424 key.offset = found_key.objectid - 1;
3431 * If we have an inode with links, there are a couple of
3432 * possibilities. Old kernels (before v3.12) used to create an
3433 * orphan item for truncate indicating that there were possibly
3434 * extent items past i_size that needed to be deleted. In v3.12,
3435 * truncate was changed to update i_size in sync with the extent
3436 * items, but the (useless) orphan item was still created. Since
3437 * v4.18, we don't create the orphan item for truncate at all.
3439 * So, this item could mean that we need to do a truncate, but
3440 * only if this filesystem was last used on a pre-v3.12 kernel
3441 * and was not cleanly unmounted. The odds of that are quite
3442 * slim, and it's a pain to do the truncate now, so just delete
3445 * It's also possible that this orphan item was supposed to be
3446 * deleted but wasn't. The inode number may have been reused,
3447 * but either way, we can delete the orphan item.
3449 if (ret == -ENOENT || inode->i_nlink) {
3452 trans = btrfs_start_transaction(root, 1);
3453 if (IS_ERR(trans)) {
3454 ret = PTR_ERR(trans);
3457 btrfs_debug(fs_info, "auto deleting %Lu",
3458 found_key.objectid);
3459 ret = btrfs_del_orphan_item(trans, root,
3460 found_key.objectid);
3461 btrfs_end_transaction(trans);
3469 /* this will do delete_inode and everything for us */
3472 /* release the path since we're done with it */
3473 btrfs_release_path(path);
3475 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3477 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3478 trans = btrfs_join_transaction(root);
3480 btrfs_end_transaction(trans);
3484 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3488 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3489 btrfs_free_path(path);
3494 * very simple check to peek ahead in the leaf looking for xattrs. If we
3495 * don't find any xattrs, we know there can't be any acls.
3497 * slot is the slot the inode is in, objectid is the objectid of the inode
3499 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3500 int slot, u64 objectid,
3501 int *first_xattr_slot)
3503 u32 nritems = btrfs_header_nritems(leaf);
3504 struct btrfs_key found_key;
3505 static u64 xattr_access = 0;
3506 static u64 xattr_default = 0;
3509 if (!xattr_access) {
3510 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3511 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3512 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3513 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3517 *first_xattr_slot = -1;
3518 while (slot < nritems) {
3519 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3521 /* we found a different objectid, there must not be acls */
3522 if (found_key.objectid != objectid)
3525 /* we found an xattr, assume we've got an acl */
3526 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3527 if (*first_xattr_slot == -1)
3528 *first_xattr_slot = slot;
3529 if (found_key.offset == xattr_access ||
3530 found_key.offset == xattr_default)
3535 * we found a key greater than an xattr key, there can't
3536 * be any acls later on