1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <crypto/hash.h>
7 #include <linux/kernel.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 <linux/migrate.h>
32 #include <linux/sched/mm.h>
33 #include <linux/iomap.h>
34 #include <asm/unaligned.h>
38 #include "transaction.h"
39 #include "btrfs_inode.h"
40 #include "print-tree.h"
41 #include "ordered-data.h"
45 #include "compression.h"
47 #include "free-space-cache.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
52 #include "space-info.h"
55 struct btrfs_iget_args {
57 struct btrfs_root *root;
60 struct btrfs_dio_data {
64 struct extent_changeset *data_reserved;
67 static const struct inode_operations btrfs_dir_inode_operations;
68 static const struct inode_operations btrfs_symlink_inode_operations;
69 static const struct inode_operations btrfs_special_inode_operations;
70 static const struct inode_operations btrfs_file_inode_operations;
71 static const struct address_space_operations btrfs_aops;
72 static const struct file_operations btrfs_dir_file_operations;
74 static struct kmem_cache *btrfs_inode_cachep;
75 struct kmem_cache *btrfs_trans_handle_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
78 struct kmem_cache *btrfs_free_space_bitmap_cachep;
80 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
81 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
82 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
83 static noinline int cow_file_range(struct btrfs_inode *inode,
84 struct page *locked_page,
85 u64 start, u64 end, int *page_started,
86 unsigned long *nr_written, int unlock);
87 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
88 u64 len, u64 orig_start, u64 block_start,
89 u64 block_len, u64 orig_block_len,
90 u64 ram_bytes, int compress_type,
93 static void __endio_write_update_ordered(struct btrfs_inode *inode,
94 const u64 offset, const u64 bytes,
98 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
100 * ilock_flags can have the following bit set:
102 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
103 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
105 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
107 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
109 if (ilock_flags & BTRFS_ILOCK_SHARED) {
110 if (ilock_flags & BTRFS_ILOCK_TRY) {
111 if (!inode_trylock_shared(inode))
116 inode_lock_shared(inode);
118 if (ilock_flags & BTRFS_ILOCK_TRY) {
119 if (!inode_trylock(inode))
126 if (ilock_flags & BTRFS_ILOCK_MMAP)
127 down_write(&BTRFS_I(inode)->i_mmap_lock);
132 * btrfs_inode_unlock - unock inode i_rwsem
134 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
135 * to decide whether the lock acquired is shared or exclusive.
137 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
139 if (ilock_flags & BTRFS_ILOCK_MMAP)
140 up_write(&BTRFS_I(inode)->i_mmap_lock);
141 if (ilock_flags & BTRFS_ILOCK_SHARED)
142 inode_unlock_shared(inode);
148 * Cleanup all submitted ordered extents in specified range to handle errors
149 * from the btrfs_run_delalloc_range() callback.
151 * NOTE: caller must ensure that when an error happens, it can not call
152 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
153 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
154 * to be released, which we want to happen only when finishing the ordered
155 * extent (btrfs_finish_ordered_io()).
157 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
158 struct page *locked_page,
159 u64 offset, u64 bytes)
161 unsigned long index = offset >> PAGE_SHIFT;
162 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
163 u64 page_start = page_offset(locked_page);
164 u64 page_end = page_start + PAGE_SIZE - 1;
168 while (index <= end_index) {
169 page = find_get_page(inode->vfs_inode.i_mapping, index);
173 ClearPagePrivate2(page);
178 * In case this page belongs to the delalloc range being instantiated
179 * then skip it, since the first page of a range is going to be
180 * properly cleaned up by the caller of run_delalloc_range
182 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
187 return __endio_write_update_ordered(inode, offset, bytes, false);
190 static int btrfs_dirty_inode(struct inode *inode);
192 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
193 struct inode *inode, struct inode *dir,
194 const struct qstr *qstr)
198 err = btrfs_init_acl(trans, inode, dir);
200 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
205 * this does all the hard work for inserting an inline extent into
206 * the btree. The caller should have done a btrfs_drop_extents so that
207 * no overlapping inline items exist in the btree
209 static int insert_inline_extent(struct btrfs_trans_handle *trans,
210 struct btrfs_path *path, bool extent_inserted,
211 struct btrfs_root *root, struct inode *inode,
212 u64 start, size_t size, size_t compressed_size,
214 struct page **compressed_pages)
216 struct extent_buffer *leaf;
217 struct page *page = NULL;
220 struct btrfs_file_extent_item *ei;
222 size_t cur_size = size;
223 unsigned long offset;
225 ASSERT((compressed_size > 0 && compressed_pages) ||
226 (compressed_size == 0 && !compressed_pages));
228 if (compressed_size && compressed_pages)
229 cur_size = compressed_size;
231 if (!extent_inserted) {
232 struct btrfs_key key;
235 key.objectid = btrfs_ino(BTRFS_I(inode));
237 key.type = BTRFS_EXTENT_DATA_KEY;
239 datasize = btrfs_file_extent_calc_inline_size(cur_size);
240 ret = btrfs_insert_empty_item(trans, root, path, &key,
245 leaf = path->nodes[0];
246 ei = btrfs_item_ptr(leaf, path->slots[0],
247 struct btrfs_file_extent_item);
248 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
249 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
250 btrfs_set_file_extent_encryption(leaf, ei, 0);
251 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
252 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
253 ptr = btrfs_file_extent_inline_start(ei);
255 if (compress_type != BTRFS_COMPRESS_NONE) {
258 while (compressed_size > 0) {
259 cpage = compressed_pages[i];
260 cur_size = min_t(unsigned long, compressed_size,
263 kaddr = kmap_atomic(cpage);
264 write_extent_buffer(leaf, kaddr, ptr, cur_size);
265 kunmap_atomic(kaddr);
269 compressed_size -= cur_size;
271 btrfs_set_file_extent_compression(leaf, ei,
274 page = find_get_page(inode->i_mapping,
275 start >> PAGE_SHIFT);
276 btrfs_set_file_extent_compression(leaf, ei, 0);
277 kaddr = kmap_atomic(page);
278 offset = offset_in_page(start);
279 write_extent_buffer(leaf, kaddr + offset, ptr, size);
280 kunmap_atomic(kaddr);
283 btrfs_mark_buffer_dirty(leaf);
284 btrfs_release_path(path);
287 * We align size to sectorsize for inline extents just for simplicity
290 size = ALIGN(size, root->fs_info->sectorsize);
291 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
296 * we're an inline extent, so nobody can
297 * extend the file past i_size without locking
298 * a page we already have locked.
300 * We must do any isize and inode updates
301 * before we unlock the pages. Otherwise we
302 * could end up racing with unlink.
304 BTRFS_I(inode)->disk_i_size = inode->i_size;
311 * conditionally insert an inline extent into the file. This
312 * does the checks required to make sure the data is small enough
313 * to fit as an inline extent.
315 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
316 u64 end, size_t compressed_size,
318 struct page **compressed_pages)
320 struct btrfs_drop_extents_args drop_args = { 0 };
321 struct btrfs_root *root = inode->root;
322 struct btrfs_fs_info *fs_info = root->fs_info;
323 struct btrfs_trans_handle *trans;
324 u64 isize = i_size_read(&inode->vfs_inode);
325 u64 actual_end = min(end + 1, isize);
326 u64 inline_len = actual_end - start;
327 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
328 u64 data_len = inline_len;
330 struct btrfs_path *path;
333 data_len = compressed_size;
336 actual_end > fs_info->sectorsize ||
337 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
339 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
341 data_len > fs_info->max_inline) {
345 path = btrfs_alloc_path();
349 trans = btrfs_join_transaction(root);
351 btrfs_free_path(path);
352 return PTR_ERR(trans);
354 trans->block_rsv = &inode->block_rsv;
356 drop_args.path = path;
357 drop_args.start = start;
358 drop_args.end = aligned_end;
359 drop_args.drop_cache = true;
360 drop_args.replace_extent = true;
362 if (compressed_size && compressed_pages)
363 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
366 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
369 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
371 btrfs_abort_transaction(trans, ret);
375 if (isize > actual_end)
376 inline_len = min_t(u64, isize, actual_end);
377 ret = insert_inline_extent(trans, path, drop_args.extent_inserted,
378 root, &inode->vfs_inode, start,
379 inline_len, compressed_size,
380 compress_type, compressed_pages);
381 if (ret && ret != -ENOSPC) {
382 btrfs_abort_transaction(trans, ret);
384 } else if (ret == -ENOSPC) {
389 btrfs_update_inode_bytes(inode, inline_len, drop_args.bytes_found);
390 ret = btrfs_update_inode(trans, root, inode);
391 if (ret && ret != -ENOSPC) {
392 btrfs_abort_transaction(trans, ret);
394 } else if (ret == -ENOSPC) {
399 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
402 * Don't forget to free the reserved space, as for inlined extent
403 * it won't count as data extent, free them directly here.
404 * And at reserve time, it's always aligned to page size, so
405 * just free one page here.
407 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
408 btrfs_free_path(path);
409 btrfs_end_transaction(trans);
413 struct async_extent {
418 unsigned long nr_pages;
420 struct list_head list;
425 struct page *locked_page;
428 unsigned int write_flags;
429 struct list_head extents;
430 struct cgroup_subsys_state *blkcg_css;
431 struct btrfs_work work;
436 /* Number of chunks in flight; must be first in the structure */
438 struct async_chunk chunks[];
441 static noinline int add_async_extent(struct async_chunk *cow,
442 u64 start, u64 ram_size,
445 unsigned long nr_pages,
448 struct async_extent *async_extent;
450 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
451 BUG_ON(!async_extent); /* -ENOMEM */
452 async_extent->start = start;
453 async_extent->ram_size = ram_size;
454 async_extent->compressed_size = compressed_size;
455 async_extent->pages = pages;
456 async_extent->nr_pages = nr_pages;
457 async_extent->compress_type = compress_type;
458 list_add_tail(&async_extent->list, &cow->extents);
463 * Check if the inode has flags compatible with compression
465 static inline bool inode_can_compress(struct btrfs_inode *inode)
467 if (inode->flags & BTRFS_INODE_NODATACOW ||
468 inode->flags & BTRFS_INODE_NODATASUM)
474 * Check if the inode needs to be submitted to compression, based on mount
475 * options, defragmentation, properties or heuristics.
477 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
480 struct btrfs_fs_info *fs_info = inode->root->fs_info;
482 if (!inode_can_compress(inode)) {
483 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
484 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
489 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
492 if (inode->defrag_compress)
494 /* bad compression ratios */
495 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
497 if (btrfs_test_opt(fs_info, COMPRESS) ||
498 inode->flags & BTRFS_INODE_COMPRESS ||
499 inode->prop_compress)
500 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
504 static inline void inode_should_defrag(struct btrfs_inode *inode,
505 u64 start, u64 end, u64 num_bytes, u64 small_write)
507 /* If this is a small write inside eof, kick off a defrag */
508 if (num_bytes < small_write &&
509 (start > 0 || end + 1 < inode->disk_i_size))
510 btrfs_add_inode_defrag(NULL, inode);
514 * we create compressed extents in two phases. The first
515 * phase compresses a range of pages that have already been
516 * locked (both pages and state bits are locked).
518 * This is done inside an ordered work queue, and the compression
519 * is spread across many cpus. The actual IO submission is step
520 * two, and the ordered work queue takes care of making sure that
521 * happens in the same order things were put onto the queue by
522 * writepages and friends.
524 * If this code finds it can't get good compression, it puts an
525 * entry onto the work queue to write the uncompressed bytes. This
526 * makes sure that both compressed inodes and uncompressed inodes
527 * are written in the same order that the flusher thread sent them
530 static noinline int compress_file_range(struct async_chunk *async_chunk)
532 struct inode *inode = async_chunk->inode;
533 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
534 u64 blocksize = fs_info->sectorsize;
535 u64 start = async_chunk->start;
536 u64 end = async_chunk->end;
540 struct page **pages = NULL;
541 unsigned long nr_pages;
542 unsigned long total_compressed = 0;
543 unsigned long total_in = 0;
546 int compress_type = fs_info->compress_type;
547 int compressed_extents = 0;
550 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
554 * We need to save i_size before now because it could change in between
555 * us evaluating the size and assigning it. This is because we lock and
556 * unlock the page in truncate and fallocate, and then modify the i_size
559 * The barriers are to emulate READ_ONCE, remove that once i_size_read
563 i_size = i_size_read(inode);
565 actual_end = min_t(u64, i_size, end + 1);
568 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
569 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
570 nr_pages = min_t(unsigned long, nr_pages,
571 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
574 * we don't want to send crud past the end of i_size through
575 * compression, that's just a waste of CPU time. So, if the
576 * end of the file is before the start of our current
577 * requested range of bytes, we bail out to the uncompressed
578 * cleanup code that can deal with all of this.
580 * It isn't really the fastest way to fix things, but this is a
581 * very uncommon corner.
583 if (actual_end <= start)
584 goto cleanup_and_bail_uncompressed;
586 total_compressed = actual_end - start;
589 * skip compression for a small file range(<=blocksize) that
590 * isn't an inline extent, since it doesn't save disk space at all.
592 if (total_compressed <= blocksize &&
593 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
594 goto cleanup_and_bail_uncompressed;
596 total_compressed = min_t(unsigned long, total_compressed,
597 BTRFS_MAX_UNCOMPRESSED);
602 * we do compression for mount -o compress and when the
603 * inode has not been flagged as nocompress. This flag can
604 * change at any time if we discover bad compression ratios.
606 if (inode_need_compress(BTRFS_I(inode), start, end)) {
608 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
610 /* just bail out to the uncompressed code */
615 if (BTRFS_I(inode)->defrag_compress)
616 compress_type = BTRFS_I(inode)->defrag_compress;
617 else if (BTRFS_I(inode)->prop_compress)
618 compress_type = BTRFS_I(inode)->prop_compress;
621 * we need to call clear_page_dirty_for_io on each
622 * page in the range. Otherwise applications with the file
623 * mmap'd can wander in and change the page contents while
624 * we are compressing them.
626 * If the compression fails for any reason, we set the pages
627 * dirty again later on.
629 * Note that the remaining part is redirtied, the start pointer
630 * has moved, the end is the original one.
633 extent_range_clear_dirty_for_io(inode, start, end);
637 /* Compression level is applied here and only here */
638 ret = btrfs_compress_pages(
639 compress_type | (fs_info->compress_level << 4),
640 inode->i_mapping, start,
647 unsigned long offset = offset_in_page(total_compressed);
648 struct page *page = pages[nr_pages - 1];
651 /* zero the tail end of the last page, we might be
652 * sending it down to disk
655 kaddr = kmap_atomic(page);
656 memset(kaddr + offset, 0,
658 kunmap_atomic(kaddr);
665 /* lets try to make an inline extent */
666 if (ret || total_in < actual_end) {
667 /* we didn't compress the entire range, try
668 * to make an uncompressed inline extent.
670 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
671 0, BTRFS_COMPRESS_NONE,
674 /* try making a compressed inline extent */
675 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
677 compress_type, pages);
680 unsigned long clear_flags = EXTENT_DELALLOC |
681 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
682 EXTENT_DO_ACCOUNTING;
683 unsigned long page_error_op;
685 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
688 * inline extent creation worked or returned error,
689 * we don't need to create any more async work items.
690 * Unlock and free up our temp pages.
692 * We use DO_ACCOUNTING here because we need the
693 * delalloc_release_metadata to be done _after_ we drop
694 * our outstanding extent for clearing delalloc for this
697 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
701 PAGE_START_WRITEBACK |
706 * Ensure we only free the compressed pages if we have
707 * them allocated, as we can still reach here with
708 * inode_need_compress() == false.
711 for (i = 0; i < nr_pages; i++) {
712 WARN_ON(pages[i]->mapping);
723 * we aren't doing an inline extent round the compressed size
724 * up to a block size boundary so the allocator does sane
727 total_compressed = ALIGN(total_compressed, blocksize);
730 * one last check to make sure the compression is really a
731 * win, compare the page count read with the blocks on disk,
732 * compression must free at least one sector size
734 total_in = ALIGN(total_in, PAGE_SIZE);
735 if (total_compressed + blocksize <= total_in) {
736 compressed_extents++;
739 * The async work queues will take care of doing actual
740 * allocation on disk for these compressed pages, and
741 * will submit them to the elevator.
743 add_async_extent(async_chunk, start, total_in,
744 total_compressed, pages, nr_pages,
747 if (start + total_in < end) {
753 return compressed_extents;
758 * the compression code ran but failed to make things smaller,
759 * free any pages it allocated and our page pointer array
761 for (i = 0; i < nr_pages; i++) {
762 WARN_ON(pages[i]->mapping);
767 total_compressed = 0;
770 /* flag the file so we don't compress in the future */
771 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
772 !(BTRFS_I(inode)->prop_compress)) {
773 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
776 cleanup_and_bail_uncompressed:
778 * No compression, but we still need to write the pages in the file
779 * we've been given so far. redirty the locked page if it corresponds
780 * to our extent and set things up for the async work queue to run
781 * cow_file_range to do the normal delalloc dance.
783 if (async_chunk->locked_page &&
784 (page_offset(async_chunk->locked_page) >= start &&
785 page_offset(async_chunk->locked_page)) <= end) {
786 __set_page_dirty_nobuffers(async_chunk->locked_page);
787 /* unlocked later on in the async handlers */
791 extent_range_redirty_for_io(inode, start, end);
792 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
793 BTRFS_COMPRESS_NONE);
794 compressed_extents++;
796 return compressed_extents;
799 static void free_async_extent_pages(struct async_extent *async_extent)
803 if (!async_extent->pages)
806 for (i = 0; i < async_extent->nr_pages; i++) {
807 WARN_ON(async_extent->pages[i]->mapping);
808 put_page(async_extent->pages[i]);
810 kfree(async_extent->pages);
811 async_extent->nr_pages = 0;
812 async_extent->pages = NULL;
816 * phase two of compressed writeback. This is the ordered portion
817 * of the code, which only gets called in the order the work was
818 * queued. We walk all the async extents created by compress_file_range
819 * and send them down to the disk.
821 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
823 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
824 struct btrfs_fs_info *fs_info = inode->root->fs_info;
825 struct async_extent *async_extent;
827 struct btrfs_key ins;
828 struct extent_map *em;
829 struct btrfs_root *root = inode->root;
830 struct extent_io_tree *io_tree = &inode->io_tree;
834 while (!list_empty(&async_chunk->extents)) {
835 async_extent = list_entry(async_chunk->extents.next,
836 struct async_extent, list);
837 list_del(&async_extent->list);
840 lock_extent(io_tree, async_extent->start,
841 async_extent->start + async_extent->ram_size - 1);
842 /* did the compression code fall back to uncompressed IO? */
843 if (!async_extent->pages) {
844 int page_started = 0;
845 unsigned long nr_written = 0;
847 /* allocate blocks */
848 ret = cow_file_range(inode, async_chunk->locked_page,
850 async_extent->start +
851 async_extent->ram_size - 1,
852 &page_started, &nr_written, 0);
857 * if page_started, cow_file_range inserted an
858 * inline extent and took care of all the unlocking
859 * and IO for us. Otherwise, we need to submit
860 * all those pages down to the drive.
862 if (!page_started && !ret)
863 extent_write_locked_range(&inode->vfs_inode,
865 async_extent->start +
866 async_extent->ram_size - 1,
868 else if (ret && async_chunk->locked_page)
869 unlock_page(async_chunk->locked_page);
875 ret = btrfs_reserve_extent(root, async_extent->ram_size,
876 async_extent->compressed_size,
877 async_extent->compressed_size,
878 0, alloc_hint, &ins, 1, 1);
880 free_async_extent_pages(async_extent);
882 if (ret == -ENOSPC) {
883 unlock_extent(io_tree, async_extent->start,
884 async_extent->start +
885 async_extent->ram_size - 1);
888 * we need to redirty the pages if we decide to
889 * fallback to uncompressed IO, otherwise we
890 * will not submit these pages down to lower
893 extent_range_redirty_for_io(&inode->vfs_inode,
895 async_extent->start +
896 async_extent->ram_size - 1);
903 * here we're doing allocation and writeback of the
906 em = create_io_em(inode, async_extent->start,
907 async_extent->ram_size, /* len */
908 async_extent->start, /* orig_start */
909 ins.objectid, /* block_start */
910 ins.offset, /* block_len */
911 ins.offset, /* orig_block_len */
912 async_extent->ram_size, /* ram_bytes */
913 async_extent->compress_type,
914 BTRFS_ORDERED_COMPRESSED);
916 /* ret value is not necessary due to void function */
917 goto out_free_reserve;
920 ret = btrfs_add_ordered_extent_compress(inode,
923 async_extent->ram_size,
925 async_extent->compress_type);
927 btrfs_drop_extent_cache(inode, async_extent->start,
928 async_extent->start +
929 async_extent->ram_size - 1, 0);
930 goto out_free_reserve;
932 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
935 * clear dirty, set writeback and unlock the pages.
937 extent_clear_unlock_delalloc(inode, async_extent->start,
938 async_extent->start +
939 async_extent->ram_size - 1,
940 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
941 PAGE_UNLOCK | PAGE_START_WRITEBACK);
942 if (btrfs_submit_compressed_write(inode, async_extent->start,
943 async_extent->ram_size,
945 ins.offset, async_extent->pages,
946 async_extent->nr_pages,
947 async_chunk->write_flags,
948 async_chunk->blkcg_css)) {
949 struct page *p = async_extent->pages[0];
950 const u64 start = async_extent->start;
951 const u64 end = start + async_extent->ram_size - 1;
953 p->mapping = inode->vfs_inode.i_mapping;
954 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
957 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
960 free_async_extent_pages(async_extent);
962 alloc_hint = ins.objectid + ins.offset;
968 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
969 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
971 extent_clear_unlock_delalloc(inode, async_extent->start,
972 async_extent->start +
973 async_extent->ram_size - 1,
974 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
975 EXTENT_DELALLOC_NEW |
976 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
977 PAGE_UNLOCK | PAGE_START_WRITEBACK |
978 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
979 free_async_extent_pages(async_extent);
984 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
987 struct extent_map_tree *em_tree = &inode->extent_tree;
988 struct extent_map *em;
991 read_lock(&em_tree->lock);
992 em = search_extent_mapping(em_tree, start, num_bytes);
995 * if block start isn't an actual block number then find the
996 * first block in this inode and use that as a hint. If that
997 * block is also bogus then just don't worry about it.
999 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1000 free_extent_map(em);
1001 em = search_extent_mapping(em_tree, 0, 0);
1002 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1003 alloc_hint = em->block_start;
1005 free_extent_map(em);
1007 alloc_hint = em->block_start;
1008 free_extent_map(em);
1011 read_unlock(&em_tree->lock);
1017 * when extent_io.c finds a delayed allocation range in the file,
1018 * the call backs end up in this code. The basic idea is to
1019 * allocate extents on disk for the range, and create ordered data structs
1020 * in ram to track those extents.
1022 * locked_page is the page that writepage had locked already. We use
1023 * it to make sure we don't do extra locks or unlocks.
1025 * *page_started is set to one if we unlock locked_page and do everything
1026 * required to start IO on it. It may be clean and already done with
1027 * IO when we return.
1029 static noinline int cow_file_range(struct btrfs_inode *inode,
1030 struct page *locked_page,
1031 u64 start, u64 end, int *page_started,
1032 unsigned long *nr_written, int unlock)
1034 struct btrfs_root *root = inode->root;
1035 struct btrfs_fs_info *fs_info = root->fs_info;
1038 unsigned long ram_size;
1039 u64 cur_alloc_size = 0;
1041 u64 blocksize = fs_info->sectorsize;
1042 struct btrfs_key ins;
1043 struct extent_map *em;
1044 unsigned clear_bits;
1045 unsigned long page_ops;
1046 bool extent_reserved = false;
1049 if (btrfs_is_free_space_inode(inode)) {
1055 num_bytes = ALIGN(end - start + 1, blocksize);
1056 num_bytes = max(blocksize, num_bytes);
1057 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1059 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1062 /* lets try to make an inline extent */
1063 ret = cow_file_range_inline(inode, start, end, 0,
1064 BTRFS_COMPRESS_NONE, NULL);
1067 * We use DO_ACCOUNTING here because we need the
1068 * delalloc_release_metadata to be run _after_ we drop
1069 * our outstanding extent for clearing delalloc for this
1072 extent_clear_unlock_delalloc(inode, start, end, NULL,
1073 EXTENT_LOCKED | EXTENT_DELALLOC |
1074 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1075 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1076 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1077 *nr_written = *nr_written +
1078 (end - start + PAGE_SIZE) / PAGE_SIZE;
1081 } else if (ret < 0) {
1086 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1087 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1090 * Relocation relies on the relocated extents to have exactly the same
1091 * size as the original extents. Normally writeback for relocation data
1092 * extents follows a NOCOW path because relocation preallocates the
1093 * extents. However, due to an operation such as scrub turning a block
1094 * group to RO mode, it may fallback to COW mode, so we must make sure
1095 * an extent allocated during COW has exactly the requested size and can
1096 * not be split into smaller extents, otherwise relocation breaks and
1097 * fails during the stage where it updates the bytenr of file extent
1100 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1101 min_alloc_size = num_bytes;
1103 min_alloc_size = fs_info->sectorsize;
1105 while (num_bytes > 0) {
1106 cur_alloc_size = num_bytes;
1107 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1108 min_alloc_size, 0, alloc_hint,
1112 cur_alloc_size = ins.offset;
1113 extent_reserved = true;
1115 ram_size = ins.offset;
1116 em = create_io_em(inode, start, ins.offset, /* len */
1117 start, /* orig_start */
1118 ins.objectid, /* block_start */
1119 ins.offset, /* block_len */
1120 ins.offset, /* orig_block_len */
1121 ram_size, /* ram_bytes */
1122 BTRFS_COMPRESS_NONE, /* compress_type */
1123 BTRFS_ORDERED_REGULAR /* type */);
1128 free_extent_map(em);
1130 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1131 ram_size, cur_alloc_size,
1132 BTRFS_ORDERED_REGULAR);
1134 goto out_drop_extent_cache;
1136 if (root->root_key.objectid ==
1137 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1138 ret = btrfs_reloc_clone_csums(inode, start,
1141 * Only drop cache here, and process as normal.
1143 * We must not allow extent_clear_unlock_delalloc()
1144 * at out_unlock label to free meta of this ordered
1145 * extent, as its meta should be freed by
1146 * btrfs_finish_ordered_io().
1148 * So we must continue until @start is increased to
1149 * skip current ordered extent.
1152 btrfs_drop_extent_cache(inode, start,
1153 start + ram_size - 1, 0);
1156 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1158 /* we're not doing compressed IO, don't unlock the first
1159 * page (which the caller expects to stay locked), don't
1160 * clear any dirty bits and don't set any writeback bits
1162 * Do set the Private2 bit so we know this page was properly
1163 * setup for writepage
1165 page_ops = unlock ? PAGE_UNLOCK : 0;
1166 page_ops |= PAGE_SET_PRIVATE2;
1168 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1170 EXTENT_LOCKED | EXTENT_DELALLOC,
1172 if (num_bytes < cur_alloc_size)
1175 num_bytes -= cur_alloc_size;
1176 alloc_hint = ins.objectid + ins.offset;
1177 start += cur_alloc_size;
1178 extent_reserved = false;
1181 * btrfs_reloc_clone_csums() error, since start is increased
1182 * extent_clear_unlock_delalloc() at out_unlock label won't
1183 * free metadata of current ordered extent, we're OK to exit.
1191 out_drop_extent_cache:
1192 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1194 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1195 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1197 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1198 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1199 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1201 * If we reserved an extent for our delalloc range (or a subrange) and
1202 * failed to create the respective ordered extent, then it means that
1203 * when we reserved the extent we decremented the extent's size from
1204 * the data space_info's bytes_may_use counter and incremented the
1205 * space_info's bytes_reserved counter by the same amount. We must make
1206 * sure extent_clear_unlock_delalloc() does not try to decrement again
1207 * the data space_info's bytes_may_use counter, therefore we do not pass
1208 * it the flag EXTENT_CLEAR_DATA_RESV.
1210 if (extent_reserved) {
1211 extent_clear_unlock_delalloc(inode, start,
1212 start + cur_alloc_size - 1,
1216 start += cur_alloc_size;
1220 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1221 clear_bits | EXTENT_CLEAR_DATA_RESV,
1227 * work queue call back to started compression on a file and pages
1229 static noinline void async_cow_start(struct btrfs_work *work)
1231 struct async_chunk *async_chunk;
1232 int compressed_extents;
1234 async_chunk = container_of(work, struct async_chunk, work);
1236 compressed_extents = compress_file_range(async_chunk);
1237 if (compressed_extents == 0) {
1238 btrfs_add_delayed_iput(async_chunk->inode);
1239 async_chunk->inode = NULL;
1244 * work queue call back to submit previously compressed pages
1246 static noinline void async_cow_submit(struct btrfs_work *work)
1248 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1250 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1251 unsigned long nr_pages;
1253 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1256 /* atomic_sub_return implies a barrier */
1257 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1259 cond_wake_up_nomb(&fs_info->async_submit_wait);
1262 * ->inode could be NULL if async_chunk_start has failed to compress,
1263 * in which case we don't have anything to submit, yet we need to
1264 * always adjust ->async_delalloc_pages as its paired with the init
1265 * happening in cow_file_range_async
1267 if (async_chunk->inode)
1268 submit_compressed_extents(async_chunk);
1271 static noinline void async_cow_free(struct btrfs_work *work)
1273 struct async_chunk *async_chunk;
1275 async_chunk = container_of(work, struct async_chunk, work);
1276 if (async_chunk->inode)
1277 btrfs_add_delayed_iput(async_chunk->inode);
1278 if (async_chunk->blkcg_css)
1279 css_put(async_chunk->blkcg_css);
1281 * Since the pointer to 'pending' is at the beginning of the array of
1282 * async_chunk's, freeing it ensures the whole array has been freed.
1284 if (atomic_dec_and_test(async_chunk->pending))
1285 kvfree(async_chunk->pending);
1288 static int cow_file_range_async(struct btrfs_inode *inode,
1289 struct writeback_control *wbc,
1290 struct page *locked_page,
1291 u64 start, u64 end, int *page_started,
1292 unsigned long *nr_written)
1294 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1295 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1296 struct async_cow *ctx;
1297 struct async_chunk *async_chunk;
1298 unsigned long nr_pages;
1300 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1302 bool should_compress;
1304 const unsigned int write_flags = wbc_to_write_flags(wbc);
1306 unlock_extent(&inode->io_tree, start, end);
1308 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1309 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1311 should_compress = false;
1313 should_compress = true;
1316 nofs_flag = memalloc_nofs_save();
1317 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1318 memalloc_nofs_restore(nofs_flag);
1321 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1322 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1323 EXTENT_DO_ACCOUNTING;
1324 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1325 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1327 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1328 clear_bits, page_ops);
1332 async_chunk = ctx->chunks;
1333 atomic_set(&ctx->num_chunks, num_chunks);
1335 for (i = 0; i < num_chunks; i++) {
1336 if (should_compress)
1337 cur_end = min(end, start + SZ_512K - 1);
1342 * igrab is called higher up in the call chain, take only the
1343 * lightweight reference for the callback lifetime
1345 ihold(&inode->vfs_inode);
1346 async_chunk[i].pending = &ctx->num_chunks;
1347 async_chunk[i].inode = &inode->vfs_inode;
1348 async_chunk[i].start = start;
1349 async_chunk[i].end = cur_end;
1350 async_chunk[i].write_flags = write_flags;
1351 INIT_LIST_HEAD(&async_chunk[i].extents);
1354 * The locked_page comes all the way from writepage and its
1355 * the original page we were actually given. As we spread
1356 * this large delalloc region across multiple async_chunk
1357 * structs, only the first struct needs a pointer to locked_page
1359 * This way we don't need racey decisions about who is supposed
1364 * Depending on the compressibility, the pages might or
1365 * might not go through async. We want all of them to
1366 * be accounted against wbc once. Let's do it here
1367 * before the paths diverge. wbc accounting is used
1368 * only for foreign writeback detection and doesn't
1369 * need full accuracy. Just account the whole thing
1370 * against the first page.
1372 wbc_account_cgroup_owner(wbc, locked_page,
1374 async_chunk[i].locked_page = locked_page;
1377 async_chunk[i].locked_page = NULL;
1380 if (blkcg_css != blkcg_root_css) {
1382 async_chunk[i].blkcg_css = blkcg_css;
1384 async_chunk[i].blkcg_css = NULL;
1387 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1388 async_cow_submit, async_cow_free);
1390 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1391 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1393 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1395 *nr_written += nr_pages;
1396 start = cur_end + 1;
1402 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1403 struct page *locked_page, u64 start,
1404 u64 end, int *page_started,
1405 unsigned long *nr_written)
1409 ret = cow_file_range(inode, locked_page, start, end, page_started,
1417 __set_page_dirty_nobuffers(locked_page);
1418 account_page_redirty(locked_page);
1419 extent_write_locked_range(&inode->vfs_inode, start, end, WB_SYNC_ALL);
1425 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1426 u64 bytenr, u64 num_bytes)
1429 struct btrfs_ordered_sum *sums;
1432 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1433 bytenr + num_bytes - 1, &list, 0);
1434 if (ret == 0 && list_empty(&list))
1437 while (!list_empty(&list)) {
1438 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1439 list_del(&sums->list);
1447 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1448 const u64 start, const u64 end,
1449 int *page_started, unsigned long *nr_written)
1451 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1452 const bool is_reloc_ino = (inode->root->root_key.objectid ==
1453 BTRFS_DATA_RELOC_TREE_OBJECTID);
1454 const u64 range_bytes = end + 1 - start;
1455 struct extent_io_tree *io_tree = &inode->io_tree;
1456 u64 range_start = start;
1460 * If EXTENT_NORESERVE is set it means that when the buffered write was
1461 * made we had not enough available data space and therefore we did not
1462 * reserve data space for it, since we though we could do NOCOW for the
1463 * respective file range (either there is prealloc extent or the inode
1464 * has the NOCOW bit set).
1466 * However when we need to fallback to COW mode (because for example the
1467 * block group for the corresponding extent was turned to RO mode by a
1468 * scrub or relocation) we need to do the following:
1470 * 1) We increment the bytes_may_use counter of the data space info.
1471 * If COW succeeds, it allocates a new data extent and after doing
1472 * that it decrements the space info's bytes_may_use counter and
1473 * increments its bytes_reserved counter by the same amount (we do
1474 * this at btrfs_add_reserved_bytes()). So we need to increment the
1475 * bytes_may_use counter to compensate (when space is reserved at
1476 * buffered write time, the bytes_may_use counter is incremented);
1478 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1479 * that if the COW path fails for any reason, it decrements (through
1480 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1481 * data space info, which we incremented in the step above.
1483 * If we need to fallback to cow and the inode corresponds to a free
1484 * space cache inode or an inode of the data relocation tree, we must
1485 * also increment bytes_may_use of the data space_info for the same
1486 * reason. Space caches and relocated data extents always get a prealloc
1487 * extent for them, however scrub or balance may have set the block
1488 * group that contains that extent to RO mode and therefore force COW
1489 * when starting writeback.
1491 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1492 EXTENT_NORESERVE, 0);
1493 if (count > 0 || is_space_ino || is_reloc_ino) {
1495 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1496 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1498 if (is_space_ino || is_reloc_ino)
1499 bytes = range_bytes;
1501 spin_lock(&sinfo->lock);
1502 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1503 spin_unlock(&sinfo->lock);
1506 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1510 return cow_file_range(inode, locked_page, start, end, page_started,
1515 * when nowcow writeback call back. This checks for snapshots or COW copies
1516 * of the extents that exist in the file, and COWs the file as required.
1518 * If no cow copies or snapshots exist, we write directly to the existing
1521 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1522 struct page *locked_page,
1523 const u64 start, const u64 end,
1525 unsigned long *nr_written)
1527 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1528 struct btrfs_root *root = inode->root;
1529 struct btrfs_path *path;
1530 u64 cow_start = (u64)-1;
1531 u64 cur_offset = start;
1533 bool check_prev = true;
1534 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1535 u64 ino = btrfs_ino(inode);
1537 u64 disk_bytenr = 0;
1538 const bool force = inode->flags & BTRFS_INODE_NODATACOW;
1540 path = btrfs_alloc_path();
1542 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1543 EXTENT_LOCKED | EXTENT_DELALLOC |
1544 EXTENT_DO_ACCOUNTING |
1545 EXTENT_DEFRAG, PAGE_UNLOCK |
1546 PAGE_START_WRITEBACK |
1547 PAGE_END_WRITEBACK);
1552 struct btrfs_key found_key;
1553 struct btrfs_file_extent_item *fi;
1554 struct extent_buffer *leaf;
1564 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1570 * If there is no extent for our range when doing the initial
1571 * search, then go back to the previous slot as it will be the
1572 * one containing the search offset
1574 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1575 leaf = path->nodes[0];
1576 btrfs_item_key_to_cpu(leaf, &found_key,
1577 path->slots[0] - 1);
1578 if (found_key.objectid == ino &&
1579 found_key.type == BTRFS_EXTENT_DATA_KEY)
1584 /* Go to next leaf if we have exhausted the current one */
1585 leaf = path->nodes[0];
1586 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1587 ret = btrfs_next_leaf(root, path);
1589 if (cow_start != (u64)-1)
1590 cur_offset = cow_start;
1595 leaf = path->nodes[0];
1598 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1600 /* Didn't find anything for our INO */
1601 if (found_key.objectid > ino)
1604 * Keep searching until we find an EXTENT_ITEM or there are no
1605 * more extents for this inode
1607 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1608 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1613 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1614 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1615 found_key.offset > end)
1619 * If the found extent starts after requested offset, then
1620 * adjust extent_end to be right before this extent begins
1622 if (found_key.offset > cur_offset) {
1623 extent_end = found_key.offset;
1629 * Found extent which begins before our range and potentially
1632 fi = btrfs_item_ptr(leaf, path->slots[0],
1633 struct btrfs_file_extent_item);
1634 extent_type = btrfs_file_extent_type(leaf, fi);
1636 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1637 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1638 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1639 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1640 extent_offset = btrfs_file_extent_offset(leaf, fi);
1641 extent_end = found_key.offset +
1642 btrfs_file_extent_num_bytes(leaf, fi);
1644 btrfs_file_extent_disk_num_bytes(leaf, fi);
1646 * If the extent we got ends before our current offset,
1647 * skip to the next extent.
1649 if (extent_end <= cur_offset) {
1654 if (disk_bytenr == 0)
1656 /* Skip compressed/encrypted/encoded extents */
1657 if (btrfs_file_extent_compression(leaf, fi) ||
1658 btrfs_file_extent_encryption(leaf, fi) ||
1659 btrfs_file_extent_other_encoding(leaf, fi))
1662 * If extent is created before the last volume's snapshot
1663 * this implies the extent is shared, hence we can't do
1664 * nocow. This is the same check as in
1665 * btrfs_cross_ref_exist but without calling
1666 * btrfs_search_slot.
1668 if (!freespace_inode &&
1669 btrfs_file_extent_generation(leaf, fi) <=
1670 btrfs_root_last_snapshot(&root->root_item))
1672 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1676 * The following checks can be expensive, as they need to
1677 * take other locks and do btree or rbtree searches, so
1678 * release the path to avoid blocking other tasks for too
1681 btrfs_release_path(path);
1683 ret = btrfs_cross_ref_exist(root, ino,
1685 extent_offset, disk_bytenr, false);
1688 * ret could be -EIO if the above fails to read
1692 if (cow_start != (u64)-1)
1693 cur_offset = cow_start;
1697 WARN_ON_ONCE(freespace_inode);
1700 disk_bytenr += extent_offset;
1701 disk_bytenr += cur_offset - found_key.offset;
1702 num_bytes = min(end + 1, extent_end) - cur_offset;
1704 * If there are pending snapshots for this root, we
1705 * fall into common COW way
1707 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1710 * force cow if csum exists in the range.
1711 * this ensure that csum for a given extent are
1712 * either valid or do not exist.
1714 ret = csum_exist_in_range(fs_info, disk_bytenr,
1718 * ret could be -EIO if the above fails to read
1722 if (cow_start != (u64)-1)
1723 cur_offset = cow_start;
1726 WARN_ON_ONCE(freespace_inode);
1729 /* If the extent's block group is RO, we must COW */
1730 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1733 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1734 extent_end = found_key.offset + ram_bytes;
1735 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1736 /* Skip extents outside of our requested range */
1737 if (extent_end <= start) {
1742 /* If this triggers then we have a memory corruption */
1747 * If nocow is false then record the beginning of the range
1748 * that needs to be COWed
1751 if (cow_start == (u64)-1)
1752 cow_start = cur_offset;
1753 cur_offset = extent_end;
1754 if (cur_offset > end)
1756 if (!path->nodes[0])
1763 * COW range from cow_start to found_key.offset - 1. As the key
1764 * will contain the beginning of the first extent that can be
1765 * NOCOW, following one which needs to be COW'ed
1767 if (cow_start != (u64)-1) {
1768 ret = fallback_to_cow(inode, locked_page,
1769 cow_start, found_key.offset - 1,
1770 page_started, nr_written);
1773 cow_start = (u64)-1;
1776 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1777 u64 orig_start = found_key.offset - extent_offset;
1778 struct extent_map *em;
1780 em = create_io_em(inode, cur_offset, num_bytes,
1782 disk_bytenr, /* block_start */
1783 num_bytes, /* block_len */
1784 disk_num_bytes, /* orig_block_len */
1785 ram_bytes, BTRFS_COMPRESS_NONE,
1786 BTRFS_ORDERED_PREALLOC);
1791 free_extent_map(em);
1792 ret = btrfs_add_ordered_extent(inode, cur_offset,
1793 disk_bytenr, num_bytes,
1795 BTRFS_ORDERED_PREALLOC);
1797 btrfs_drop_extent_cache(inode, cur_offset,
1798 cur_offset + num_bytes - 1,
1803 ret = btrfs_add_ordered_extent(inode, cur_offset,
1804 disk_bytenr, num_bytes,
1806 BTRFS_ORDERED_NOCOW);
1812 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1815 if (root->root_key.objectid ==
1816 BTRFS_DATA_RELOC_TREE_OBJECTID)
1818 * Error handled later, as we must prevent
1819 * extent_clear_unlock_delalloc() in error handler
1820 * from freeing metadata of created ordered extent.
1822 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1825 extent_clear_unlock_delalloc(inode, cur_offset,
1826 cur_offset + num_bytes - 1,
1827 locked_page, EXTENT_LOCKED |
1829 EXTENT_CLEAR_DATA_RESV,
1830 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1832 cur_offset = extent_end;
1835 * btrfs_reloc_clone_csums() error, now we're OK to call error
1836 * handler, as metadata for created ordered extent will only
1837 * be freed by btrfs_finish_ordered_io().
1841 if (cur_offset > end)
1844 btrfs_release_path(path);
1846 if (cur_offset <= end && cow_start == (u64)-1)
1847 cow_start = cur_offset;
1849 if (cow_start != (u64)-1) {
1851 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1852 page_started, nr_written);
1859 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1861 if (ret && cur_offset < end)
1862 extent_clear_unlock_delalloc(inode, cur_offset, end,
1863 locked_page, EXTENT_LOCKED |
1864 EXTENT_DELALLOC | EXTENT_DEFRAG |
1865 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1866 PAGE_START_WRITEBACK |
1867 PAGE_END_WRITEBACK);
1868 btrfs_free_path(path);
1872 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
1874 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
1875 if (inode->defrag_bytes &&
1876 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
1885 * Function to process delayed allocation (create CoW) for ranges which are
1886 * being touched for the first time.
1888 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1889 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1890 struct writeback_control *wbc)
1893 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
1895 if (should_nocow(inode, start, end)) {
1897 ret = run_delalloc_nocow(inode, locked_page, start, end,
1898 page_started, nr_written);
1899 } else if (!inode_can_compress(inode) ||
1900 !inode_need_compress(inode, start, end)) {
1902 ret = run_delalloc_zoned(inode, locked_page, start, end,
1903 page_started, nr_written);
1905 ret = cow_file_range(inode, locked_page, start, end,
1906 page_started, nr_written, 1);
1908 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1909 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1910 page_started, nr_written);
1913 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1918 void btrfs_split_delalloc_extent(struct inode *inode,
1919 struct extent_state *orig, u64 split)
1923 /* not delalloc, ignore it */
1924 if (!(orig->state & EXTENT_DELALLOC))
1927 size = orig->end - orig->start + 1;
1928 if (size > BTRFS_MAX_EXTENT_SIZE) {
1933 * See the explanation in btrfs_merge_delalloc_extent, the same
1934 * applies here, just in reverse.
1936 new_size = orig->end - split + 1;
1937 num_extents = count_max_extents(new_size);
1938 new_size = split - orig->start;
1939 num_extents += count_max_extents(new_size);
1940 if (count_max_extents(size) >= num_extents)
1944 spin_lock(&BTRFS_I(inode)->lock);
1945 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1946 spin_unlock(&BTRFS_I(inode)->lock);
1950 * Handle merged delayed allocation extents so we can keep track of new extents
1951 * that are just merged onto old extents, such as when we are doing sequential
1952 * writes, so we can properly account for the metadata space we'll need.
1954 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1955 struct extent_state *other)
1957 u64 new_size, old_size;
1960 /* not delalloc, ignore it */
1961 if (!(other->state & EXTENT_DELALLOC))
1964 if (new->start > other->start)
1965 new_size = new->end - other->start + 1;
1967 new_size = other->end - new->start + 1;
1969 /* we're not bigger than the max, unreserve the space and go */
1970 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1971 spin_lock(&BTRFS_I(inode)->lock);
1972 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1973 spin_unlock(&BTRFS_I(inode)->lock);
1978 * We have to add up either side to figure out how many extents were
1979 * accounted for before we merged into one big extent. If the number of
1980 * extents we accounted for is <= the amount we need for the new range
1981 * then we can return, otherwise drop. Think of it like this
1985 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1986 * need 2 outstanding extents, on one side we have 1 and the other side
1987 * we have 1 so they are == and we can return. But in this case
1989 * [MAX_SIZE+4k][MAX_SIZE+4k]
1991 * Each range on their own accounts for 2 extents, but merged together
1992 * they are only 3 extents worth of accounting, so we need to drop in
1995 old_size = other->end - other->start + 1;
1996 num_extents = count_max_extents(old_size);
1997 old_size = new->end - new->start + 1;
1998 num_extents += count_max_extents(old_size);
1999 if (count_max_extents(new_size) >= num_extents)
2002 spin_lock(&BTRFS_I(inode)->lock);
2003 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2004 spin_unlock(&BTRFS_I(inode)->lock);
2007 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2008 struct inode *inode)
2010 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2012 spin_lock(&root->delalloc_lock);
2013 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2014 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2015 &root->delalloc_inodes);
2016 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2017 &BTRFS_I(inode)->runtime_flags);
2018 root->nr_delalloc_inodes++;
2019 if (root->nr_delalloc_inodes == 1) {
2020 spin_lock(&fs_info->delalloc_root_lock);
2021 BUG_ON(!list_empty(&root->delalloc_root));
2022 list_add_tail(&root->delalloc_root,
2023 &fs_info->delalloc_roots);
2024 spin_unlock(&fs_info->delalloc_root_lock);
2027 spin_unlock(&root->delalloc_lock);
2031 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2032 struct btrfs_inode *inode)
2034 struct btrfs_fs_info *fs_info = root->fs_info;
2036 if (!list_empty(&inode->delalloc_inodes)) {
2037 list_del_init(&inode->delalloc_inodes);
2038 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2039 &inode->runtime_flags);
2040 root->nr_delalloc_inodes--;
2041 if (!root->nr_delalloc_inodes) {
2042 ASSERT(list_empty(&root->delalloc_inodes));
2043 spin_lock(&fs_info->delalloc_root_lock);
2044 BUG_ON(list_empty(&root->delalloc_root));
2045 list_del_init(&root->delalloc_root);
2046 spin_unlock(&fs_info->delalloc_root_lock);
2051 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2052 struct btrfs_inode *inode)
2054 spin_lock(&root->delalloc_lock);
2055 __btrfs_del_delalloc_inode(root, inode);
2056 spin_unlock(&root->delalloc_lock);
2060 * Properly track delayed allocation bytes in the inode and to maintain the
2061 * list of inodes that have pending delalloc work to be done.
2063 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2066 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2068 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2071 * set_bit and clear bit hooks normally require _irqsave/restore
2072 * but in this case, we are only testing for the DELALLOC
2073 * bit, which is only set or cleared with irqs on
2075 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2076 struct btrfs_root *root = BTRFS_I(inode)->root;
2077 u64 len = state->end + 1 - state->start;
2078 u32 num_extents = count_max_extents(len);
2079 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2081 spin_lock(&BTRFS_I(inode)->lock);
2082 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2083 spin_unlock(&BTRFS_I(inode)->lock);
2085 /* For sanity tests */
2086 if (btrfs_is_testing(fs_info))
2089 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2090 fs_info->delalloc_batch);
2091 spin_lock(&BTRFS_I(inode)->lock);
2092 BTRFS_I(inode)->delalloc_bytes += len;
2093 if (*bits & EXTENT_DEFRAG)
2094 BTRFS_I(inode)->defrag_bytes += len;
2095 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2096 &BTRFS_I(inode)->runtime_flags))
2097 btrfs_add_delalloc_inodes(root, inode);
2098 spin_unlock(&BTRFS_I(inode)->lock);
2101 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2102 (*bits & EXTENT_DELALLOC_NEW)) {
2103 spin_lock(&BTRFS_I(inode)->lock);
2104 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2106 spin_unlock(&BTRFS_I(inode)->lock);
2111 * Once a range is no longer delalloc this function ensures that proper
2112 * accounting happens.
2114 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2115 struct extent_state *state, unsigned *bits)
2117 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2118 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2119 u64 len = state->end + 1 - state->start;
2120 u32 num_extents = count_max_extents(len);
2122 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2123 spin_lock(&inode->lock);
2124 inode->defrag_bytes -= len;
2125 spin_unlock(&inode->lock);
2129 * set_bit and clear bit hooks normally require _irqsave/restore
2130 * but in this case, we are only testing for the DELALLOC
2131 * bit, which is only set or cleared with irqs on
2133 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2134 struct btrfs_root *root = inode->root;
2135 bool do_list = !btrfs_is_free_space_inode(inode);
2137 spin_lock(&inode->lock);
2138 btrfs_mod_outstanding_extents(inode, -num_extents);
2139 spin_unlock(&inode->lock);
2142 * We don't reserve metadata space for space cache inodes so we
2143 * don't need to call delalloc_release_metadata if there is an
2146 if (*bits & EXTENT_CLEAR_META_RESV &&
2147 root != fs_info->tree_root)
2148 btrfs_delalloc_release_metadata(inode, len, false);
2150 /* For sanity tests. */
2151 if (btrfs_is_testing(fs_info))
2154 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2155 do_list && !(state->state & EXTENT_NORESERVE) &&
2156 (*bits & EXTENT_CLEAR_DATA_RESV))
2157 btrfs_free_reserved_data_space_noquota(fs_info, len);
2159 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2160 fs_info->delalloc_batch);
2161 spin_lock(&inode->lock);
2162 inode->delalloc_bytes -= len;
2163 if (do_list && inode->delalloc_bytes == 0 &&
2164 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2165 &inode->runtime_flags))
2166 btrfs_del_delalloc_inode(root, inode);
2167 spin_unlock(&inode->lock);
2170 if ((state->state & EXTENT_DELALLOC_NEW) &&
2171 (*bits & EXTENT_DELALLOC_NEW)) {
2172 spin_lock(&inode->lock);
2173 ASSERT(inode->new_delalloc_bytes >= len);
2174 inode->new_delalloc_bytes -= len;
2175 if (*bits & EXTENT_ADD_INODE_BYTES)
2176 inode_add_bytes(&inode->vfs_inode, len);
2177 spin_unlock(&inode->lock);
2182 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2183 * in a chunk's stripe. This function ensures that bios do not span a
2186 * @page - The page we are about to add to the bio
2187 * @size - size we want to add to the bio
2188 * @bio - bio we want to ensure is smaller than a stripe
2189 * @bio_flags - flags of the bio
2191 * return 1 if page cannot be added to the bio
2192 * return 0 if page can be added to the bio
2193 * return error otherwise
2195 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2196 unsigned long bio_flags)
2198 struct inode *inode = page->mapping->host;
2199 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2200 u64 logical = bio->bi_iter.bi_sector << 9;
2201 struct extent_map *em;
2205 struct btrfs_io_geometry geom;
2207 if (bio_flags & EXTENT_BIO_COMPRESSED)
2210 length = bio->bi_iter.bi_size;
2211 map_length = length;
2212 em = btrfs_get_chunk_map(fs_info, logical, map_length);
2215 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), logical,
2220 if (geom.len < length + size)
2223 free_extent_map(em);
2228 * in order to insert checksums into the metadata in large chunks,
2229 * we wait until bio submission time. All the pages in the bio are
2230 * checksummed and sums are attached onto the ordered extent record.
2232 * At IO completion time the cums attached on the ordered extent record
2233 * are inserted into the btree
2235 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2236 u64 dio_file_offset)
2238 return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2241 bool btrfs_bio_fits_in_ordered_extent(struct page *page, struct bio *bio,
2244 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
2245 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2246 struct btrfs_ordered_extent *ordered;
2247 u64 len = bio->bi_iter.bi_size + size;
2250 ASSERT(btrfs_is_zoned(fs_info));
2251 ASSERT(fs_info->max_zone_append_size > 0);
2252 ASSERT(bio_op(bio) == REQ_OP_ZONE_APPEND);
2254 /* Ordered extent not yet created, so we're good */
2255 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
2259 if ((bio->bi_iter.bi_sector << SECTOR_SHIFT) + len >
2260 ordered->disk_bytenr + ordered->disk_num_bytes)
2263 btrfs_put_ordered_extent(ordered);
2268 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2269 struct bio *bio, loff_t file_offset)
2271 struct btrfs_ordered_extent *ordered;
2272 struct extent_map *em = NULL, *em_new = NULL;
2273 struct extent_map_tree *em_tree = &inode->extent_tree;
2274 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2275 u64 len = bio->bi_iter.bi_size;
2276 u64 end = start + len;
2281 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2282 if (WARN_ON_ONCE(!ordered))
2283 return BLK_STS_IOERR;
2285 /* No need to split */
2286 if (ordered->disk_num_bytes == len)
2289 /* We cannot split once end_bio'd ordered extent */
2290 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2295 /* We cannot split a compressed ordered extent */
2296 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2301 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2302 /* bio must be in one ordered extent */
2303 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2308 /* Checksum list should be empty */
2309 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2314 pre = start - ordered->disk_bytenr;
2315 post = ordered_end - end;
2317 ret = btrfs_split_ordered_extent(ordered, pre, post);
2321 read_lock(&em_tree->lock);
2322 em = lookup_extent_mapping(em_tree, ordered->file_offset, len);
2324 read_unlock(&em_tree->lock);
2328 read_unlock(&em_tree->lock);
2330 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2332 * We cannot reuse em_new here but have to create a new one, as
2333 * unpin_extent_cache() expects the start of the extent map to be the
2334 * logical offset of the file, which does not hold true anymore after
2337 em_new = create_io_em(inode, em->start + pre, len,
2338 em->start + pre, em->block_start + pre, len,
2339 len, len, BTRFS_COMPRESS_NONE,
2340 BTRFS_ORDERED_REGULAR);
2341 if (IS_ERR(em_new)) {
2342 ret = PTR_ERR(em_new);
2345 free_extent_map(em_new);
2348 free_extent_map(em);
2349 btrfs_put_ordered_extent(ordered);
2351 return errno_to_blk_status(ret);
2355 * extent_io.c submission hook. This does the right thing for csum calculation
2356 * on write, or reading the csums from the tree before a read.
2358 * Rules about async/sync submit,
2359 * a) read: sync submit
2361 * b) write without checksum: sync submit
2363 * c) write with checksum:
2364 * c-1) if bio is issued by fsync: sync submit
2365 * (sync_writers != 0)
2367 * c-2) if root is reloc root: sync submit
2368 * (only in case of buffered IO)
2370 * c-3) otherwise: async submit
2372 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2373 int mirror_num, unsigned long bio_flags)
2376 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2377 struct btrfs_root *root = BTRFS_I(inode)->root;
2378 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2379 blk_status_t ret = 0;
2381 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2383 skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2384 !fs_info->csum_root;
2386 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2387 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2389 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2390 struct page *page = bio_first_bvec_all(bio)->bv_page;
2391 loff_t file_offset = page_offset(page);
2393 ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2398 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2399 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2403 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2404 ret = btrfs_submit_compressed_read(inode, bio,
2410 * Lookup bio sums does extra checks around whether we
2411 * need to csum or not, which is why we ignore skip_sum
2414 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2419 } else if (async && !skip_sum) {
2420 /* csum items have already been cloned */
2421 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2423 /* we're doing a write, do the async checksumming */
2424 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2425 0, btrfs_submit_bio_start);
2427 } else if (!skip_sum) {
2428 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2434 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2438 bio->bi_status = ret;
2445 * given a list of ordered sums record them in the inode. This happens
2446 * at IO completion time based on sums calculated at bio submission time.
2448 static int add_pending_csums(struct btrfs_trans_handle *trans,
2449 struct list_head *list)
2451 struct btrfs_ordered_sum *sum;
2454 list_for_each_entry(sum, list, list) {
2455 trans->adding_csums = true;
2456 ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2457 trans->adding_csums = false;
2464 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2467 struct extent_state **cached_state)
2469 u64 search_start = start;
2470 const u64 end = start + len - 1;
2472 while (search_start < end) {
2473 const u64 search_len = end - search_start + 1;
2474 struct extent_map *em;
2478 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2482 if (em->block_start != EXTENT_MAP_HOLE)
2486 if (em->start < search_start)
2487 em_len -= search_start - em->start;
2488 if (em_len > search_len)
2489 em_len = search_len;
2491 ret = set_extent_bit(&inode->io_tree, search_start,
2492 search_start + em_len - 1,
2493 EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2496 search_start = extent_map_end(em);
2497 free_extent_map(em);
2504 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2505 unsigned int extra_bits,
2506 struct extent_state **cached_state)
2508 WARN_ON(PAGE_ALIGNED(end));
2510 if (start >= i_size_read(&inode->vfs_inode) &&
2511 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2513 * There can't be any extents following eof in this case so just
2514 * set the delalloc new bit for the range directly.
2516 extra_bits |= EXTENT_DELALLOC_NEW;
2520 ret = btrfs_find_new_delalloc_bytes(inode, start,
2527 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2531 /* see btrfs_writepage_start_hook for details on why this is required */
2532 struct btrfs_writepage_fixup {
2534 struct inode *inode;
2535 struct btrfs_work work;
2538 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2540 struct btrfs_writepage_fixup *fixup;
2541 struct btrfs_ordered_extent *ordered;
2542 struct extent_state *cached_state = NULL;
2543 struct extent_changeset *data_reserved = NULL;
2545 struct btrfs_inode *inode;
2549 bool free_delalloc_space = true;
2551 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2553 inode = BTRFS_I(fixup->inode);
2554 page_start = page_offset(page);
2555 page_end = page_offset(page) + PAGE_SIZE - 1;
2558 * This is similar to page_mkwrite, we need to reserve the space before
2559 * we take the page lock.
2561 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2567 * Before we queued this fixup, we took a reference on the page.
2568 * page->mapping may go NULL, but it shouldn't be moved to a different
2571 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2573 * Unfortunately this is a little tricky, either
2575 * 1) We got here and our page had already been dealt with and
2576 * we reserved our space, thus ret == 0, so we need to just
2577 * drop our space reservation and bail. This can happen the
2578 * first time we come into the fixup worker, or could happen
2579 * while waiting for the ordered extent.
2580 * 2) Our page was already dealt with, but we happened to get an
2581 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2582 * this case we obviously don't have anything to release, but
2583 * because the page was already dealt with we don't want to
2584 * mark the page with an error, so make sure we're resetting
2585 * ret to 0. This is why we have this check _before_ the ret
2586 * check, because we do not want to have a surprise ENOSPC
2587 * when the page was already properly dealt with.
2590 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2591 btrfs_delalloc_release_space(inode, data_reserved,
2592 page_start, PAGE_SIZE,
2600 * We can't mess with the page state unless it is locked, so now that
2601 * it is locked bail if we failed to make our space reservation.
2606 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2608 /* already ordered? We're done */
2609 if (PagePrivate2(page))
2612 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2614 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2617 btrfs_start_ordered_extent(ordered, 1);
2618 btrfs_put_ordered_extent(ordered);
2622 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2628 * Everything went as planned, we're now the owner of a dirty page with
2629 * delayed allocation bits set and space reserved for our COW
2632 * The page was dirty when we started, nothing should have cleaned it.
2634 BUG_ON(!PageDirty(page));
2635 free_delalloc_space = false;
2637 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2638 if (free_delalloc_space)
2639 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2641 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2646 * We hit ENOSPC or other errors. Update the mapping and page
2647 * to reflect the errors and clean the page.
2649 mapping_set_error(page->mapping, ret);
2650 end_extent_writepage(page, ret, page_start, page_end);
2651 clear_page_dirty_for_io(page);
2654 ClearPageChecked(page);
2658 extent_changeset_free(data_reserved);
2660 * As a precaution, do a delayed iput in case it would be the last iput
2661 * that could need flushing space. Recursing back to fixup worker would
2664 btrfs_add_delayed_iput(&inode->vfs_inode);
2668 * There are a few paths in the higher layers of the kernel that directly
2669 * set the page dirty bit without asking the filesystem if it is a
2670 * good idea. This causes problems because we want to make sure COW
2671 * properly happens and the data=ordered rules are followed.
2673 * In our case any range that doesn't have the ORDERED bit set
2674 * hasn't been properly setup for IO. We kick off an async process
2675 * to fix it up. The async helper will wait for ordered extents, set
2676 * the delalloc bit and make it safe to write the page.
2678 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2680 struct inode *inode = page->mapping->host;
2681 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2682 struct btrfs_writepage_fixup *fixup;
2684 /* this page is properly in the ordered list */
2685 if (TestClearPagePrivate2(page))
2689 * PageChecked is set below when we create a fixup worker for this page,
2690 * don't try to create another one if we're already PageChecked()
2692 * The extent_io writepage code will redirty the page if we send back
2695 if (PageChecked(page))
2698 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2703 * We are already holding a reference to this inode from
2704 * write_cache_pages. We need to hold it because the space reservation
2705 * takes place outside of the page lock, and we can't trust
2706 * page->mapping outside of the page lock.
2709 SetPageChecked(page);
2711 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2713 fixup->inode = inode;
2714 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2719 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2720 struct btrfs_inode *inode, u64 file_pos,
2721 struct btrfs_file_extent_item *stack_fi,
2722 const bool update_inode_bytes,
2723 u64 qgroup_reserved)
2725 struct btrfs_root *root = inode->root;
2726 const u64 sectorsize = root->fs_info->sectorsize;
2727 struct btrfs_path *path;
2728 struct extent_buffer *leaf;
2729 struct btrfs_key ins;
2730 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2731 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2732 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2733 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2734 struct btrfs_drop_extents_args drop_args = { 0 };
2737 path = btrfs_alloc_path();
2742 * we may be replacing one extent in the tree with another.
2743 * The new extent is pinned in the extent map, and we don't want
2744 * to drop it from the cache until it is completely in the btree.
2746 * So, tell btrfs_drop_extents to leave this extent in the cache.
2747 * the caller is expected to unpin it and allow it to be merged
2750 drop_args.path = path;
2751 drop_args.start = file_pos;
2752 drop_args.end = file_pos + num_bytes;
2753 drop_args.replace_extent = true;
2754 drop_args.extent_item_size = sizeof(*stack_fi);
2755 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2759 if (!drop_args.extent_inserted) {
2760 ins.objectid = btrfs_ino(inode);
2761 ins.offset = file_pos;
2762 ins.type = BTRFS_EXTENT_DATA_KEY;
2764 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2769 leaf = path->nodes[0];
2770 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2771 write_extent_buffer(leaf, stack_fi,
2772 btrfs_item_ptr_offset(leaf, path->slots[0]),
2773 sizeof(struct btrfs_file_extent_item));
2775 btrfs_mark_buffer_dirty(leaf);
2776 btrfs_release_path(path);
2779 * If we dropped an inline extent here, we know the range where it is
2780 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2781 * number of bytes only for that range contaning the inline extent.
2782 * The remaining of the range will be processed when clearning the
2783 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2785 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2786 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2788 inline_size = drop_args.bytes_found - inline_size;
2789 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2790 drop_args.bytes_found -= inline_size;
2791 num_bytes -= sectorsize;
2794 if (update_inode_bytes)
2795 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2797 ins.objectid = disk_bytenr;
2798 ins.offset = disk_num_bytes;
2799 ins.type = BTRFS_EXTENT_ITEM_KEY;
2801 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2805 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2806 file_pos, qgroup_reserved, &ins);
2808 btrfs_free_path(path);
2813 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2816 struct btrfs_block_group *cache;
2818 cache = btrfs_lookup_block_group(fs_info, start);
2821 spin_lock(&cache->lock);
2822 cache->delalloc_bytes -= len;
2823 spin_unlock(&cache->lock);
2825 btrfs_put_block_group(cache);
2828 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2829 struct btrfs_ordered_extent *oe)
2831 struct btrfs_file_extent_item stack_fi;
2833 bool update_inode_bytes;
2835 memset(&stack_fi, 0, sizeof(stack_fi));
2836 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2837 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2838 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2839 oe->disk_num_bytes);
2840 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2841 logical_len = oe->truncated_len;
2843 logical_len = oe->num_bytes;
2844 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2845 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2846 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2847 /* Encryption and other encoding is reserved and all 0 */
2850 * For delalloc, when completing an ordered extent we update the inode's
2851 * bytes when clearing the range in the inode's io tree, so pass false
2852 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
2853 * except if the ordered extent was truncated.
2855 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
2856 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
2858 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
2859 oe->file_offset, &stack_fi,
2860 update_inode_bytes, oe->qgroup_rsv);
2864 * As ordered data IO finishes, this gets called so we can finish
2865 * an ordered extent if the range of bytes in the file it covers are
2868 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2870 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
2871 struct btrfs_root *root = inode->root;
2872 struct btrfs_fs_info *fs_info = root->fs_info;
2873 struct btrfs_trans_handle *trans = NULL;
2874 struct extent_io_tree *io_tree = &inode->io_tree;
2875 struct extent_state *cached_state = NULL;
2877 int compress_type = 0;
2879 u64 logical_len = ordered_extent->num_bytes;
2880 bool freespace_inode;
2881 bool truncated = false;
2882 bool clear_reserved_extent = true;
2883 unsigned int clear_bits = EXTENT_DEFRAG;
2885 start = ordered_extent->file_offset;
2886 end = start + ordered_extent->num_bytes - 1;
2888 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2889 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2890 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2891 clear_bits |= EXTENT_DELALLOC_NEW;
2893 freespace_inode = btrfs_is_free_space_inode(inode);
2895 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2900 if (ordered_extent->disk)
2901 btrfs_rewrite_logical_zoned(ordered_extent);
2903 btrfs_free_io_failure_record(inode, start, end);
2905 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2907 logical_len = ordered_extent->truncated_len;
2908 /* Truncated the entire extent, don't bother adding */
2913 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2914 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2916 btrfs_inode_safe_disk_i_size_write(inode, 0);
2917 if (freespace_inode)
2918 trans = btrfs_join_transaction_spacecache(root);
2920 trans = btrfs_join_transaction(root);
2921 if (IS_ERR(trans)) {
2922 ret = PTR_ERR(trans);
2926 trans->block_rsv = &inode->block_rsv;
2927 ret = btrfs_update_inode_fallback(trans, root, inode);
2928 if (ret) /* -ENOMEM or corruption */
2929 btrfs_abort_transaction(trans, ret);
2933 clear_bits |= EXTENT_LOCKED;
2934 lock_extent_bits(io_tree, start, end, &cached_state);
2936 if (freespace_inode)
2937 trans = btrfs_join_transaction_spacecache(root);
2939 trans = btrfs_join_transaction(root);
2940 if (IS_ERR(trans)) {
2941 ret = PTR_ERR(trans);
2946 trans->block_rsv = &inode->block_rsv;
2948 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2949 compress_type = ordered_extent->compress_type;
2950 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2951 BUG_ON(compress_type);
2952 ret = btrfs_mark_extent_written(trans, inode,
2953 ordered_extent->file_offset,
2954 ordered_extent->file_offset +
2957 BUG_ON(root == fs_info->tree_root);
2958 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
2960 clear_reserved_extent = false;
2961 btrfs_release_delalloc_bytes(fs_info,
2962 ordered_extent->disk_bytenr,
2963 ordered_extent->disk_num_bytes);
2966 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
2967 ordered_extent->num_bytes, trans->transid);
2969 btrfs_abort_transaction(trans, ret);
2973 ret = add_pending_csums(trans, &ordered_extent->list);
2975 btrfs_abort_transaction(trans, ret);
2980 * If this is a new delalloc range, clear its new delalloc flag to
2981 * update the inode's number of bytes. This needs to be done first
2982 * before updating the inode item.
2984 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
2985 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
2986 clear_extent_bit(&inode->io_tree, start, end,
2987 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
2988 0, 0, &cached_state);
2990 btrfs_inode_safe_disk_i_size_write(inode, 0);
2991 ret = btrfs_update_inode_fallback(trans, root, inode);
2992 if (ret) { /* -ENOMEM or corruption */
2993 btrfs_abort_transaction(trans, ret);
2998 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
2999 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
3003 btrfs_end_transaction(trans);
3005 if (ret || truncated) {
3006 u64 unwritten_start = start;
3009 unwritten_start += logical_len;
3010 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3012 /* Drop the cache for the part of the extent we didn't write. */
3013 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3016 * If the ordered extent had an IOERR or something else went
3017 * wrong we need to return the space for this ordered extent
3018 * back to the allocator. We only free the extent in the
3019 * truncated case if we didn't write out the extent at all.
3021 * If we made it past insert_reserved_file_extent before we
3022 * errored out then we don't need to do this as the accounting
3023 * has already been done.
3025 if ((ret || !logical_len) &&
3026 clear_reserved_extent &&
3027 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3028 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3030 * Discard the range before returning it back to the
3033 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3034 btrfs_discard_extent(fs_info,
3035 ordered_extent->disk_bytenr,
3036 ordered_extent->disk_num_bytes,
3038 btrfs_free_reserved_extent(fs_info,
3039 ordered_extent->disk_bytenr,
3040 ordered_extent->disk_num_bytes, 1);
3045 * This needs to be done to make sure anybody waiting knows we are done
3046 * updating everything for this ordered extent.
3048 btrfs_remove_ordered_extent(inode, ordered_extent);
3051 btrfs_put_ordered_extent(ordered_extent);
3052 /* once for the tree */
3053 btrfs_put_ordered_extent(ordered_extent);
3058 static void finish_ordered_fn(struct btrfs_work *work)
3060 struct btrfs_ordered_extent *ordered_extent;
3061 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3062 btrfs_finish_ordered_io(ordered_extent);
3065 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3066 u64 end, int uptodate)
3068 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3069 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3070 struct btrfs_ordered_extent *ordered_extent = NULL;
3071 struct btrfs_workqueue *wq;
3073 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3075 ClearPagePrivate2(page);
3076 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3077 end - start + 1, uptodate))
3080 if (btrfs_is_free_space_inode(inode))
3081 wq = fs_info->endio_freespace_worker;
3083 wq = fs_info->endio_write_workers;
3085 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
3086 btrfs_queue_work(wq, &ordered_extent->work);
3090 * check_data_csum - verify checksum of one sector of uncompressed data
3092 * @io_bio: btrfs_io_bio which contains the csum
3093 * @bio_offset: offset to the beginning of the bio (in bytes)
3094 * @page: page where is the data to be verified
3095 * @pgoff: offset inside the page
3096 * @start: logical offset in the file
3098 * The length of such check is always one sector size.
3100 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
3101 u32 bio_offset, struct page *page, u32 pgoff,
3104 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3105 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3107 u32 len = fs_info->sectorsize;
3108 const u32 csum_size = fs_info->csum_size;
3109 unsigned int offset_sectors;
3111 u8 csum[BTRFS_CSUM_SIZE];
3113 ASSERT(pgoff + len <= PAGE_SIZE);
3115 offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3116 csum_expected = ((u8 *)io_bio->csum) + offset_sectors * csum_size;
3118 kaddr = kmap_atomic(page);
3119 shash->tfm = fs_info->csum_shash;
3121 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3123 if (memcmp(csum, csum_expected, csum_size))
3126 kunmap_atomic(kaddr);
3129 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3130 io_bio->mirror_num);
3132 btrfs_dev_stat_inc_and_print(io_bio->device,
3133 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3134 memset(kaddr + pgoff, 1, len);
3135 flush_dcache_page(page);
3136 kunmap_atomic(kaddr);
3141 * When reads are done, we need to check csums to verify the data is correct.
3142 * if there's a match, we allow the bio to finish. If not, the code in
3143 * extent_io.c will try to find good copies for us.
3145 * @bio_offset: offset to the beginning of the bio (in bytes)
3146 * @start: file offset of the range start
3147 * @end: file offset of the range end (inclusive)
3149 int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u32 bio_offset,
3150 struct page *page, u64 start, u64 end)
3152 struct inode *inode = page->mapping->host;
3153 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3154 struct btrfs_root *root = BTRFS_I(inode)->root;
3155 const u32 sectorsize = root->fs_info->sectorsize;
3158 if (PageChecked(page)) {
3159 ClearPageChecked(page);
3163 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3166 if (!root->fs_info->csum_root)
3169 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3170 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3171 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3175 ASSERT(page_offset(page) <= start &&
3176 end <= page_offset(page) + PAGE_SIZE - 1);
3177 for (pg_off = offset_in_page(start);
3178 pg_off < offset_in_page(end);
3179 pg_off += sectorsize, bio_offset += sectorsize) {
3182 ret = check_data_csum(inode, io_bio, bio_offset, page, pg_off,
3183 page_offset(page) + pg_off);
3191 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3193 * @inode: The inode we want to perform iput on
3195 * This function uses the generic vfs_inode::i_count to track whether we should
3196 * just decrement it (in case it's > 1) or if this is the last iput then link
3197 * the inode to the delayed iput machinery. Delayed iputs are processed at
3198 * transaction commit time/superblock commit/cleaner kthread.
3200 void btrfs_add_delayed_iput(struct inode *inode)
3202 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3203 struct btrfs_inode *binode = BTRFS_I(inode);
3205 if (atomic_add_unless(&inode->i_count, -1, 1))
3208 atomic_inc(&fs_info->nr_delayed_iputs);
3209 spin_lock(&fs_info->delayed_iput_lock);
3210 ASSERT(list_empty(&binode->delayed_iput));
3211 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3212 spin_unlock(&fs_info->delayed_iput_lock);
3213 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3214 wake_up_process(fs_info->cleaner_kthread);
3217 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3218 struct btrfs_inode *inode)
3220 list_del_init(&inode->delayed_iput);
3221 spin_unlock(&fs_info->delayed_iput_lock);
3222 iput(&inode->vfs_inode);
3223 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3224 wake_up(&fs_info->delayed_iputs_wait);
3225 spin_lock(&fs_info->delayed_iput_lock);
3228 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3229 struct btrfs_inode *inode)
3231 if (!list_empty(&inode->delayed_iput)) {
3232 spin_lock(&fs_info->delayed_iput_lock);
3233 if (!list_empty(&inode->delayed_iput))
3234 run_delayed_iput_locked(fs_info, inode);
3235 spin_unlock(&fs_info->delayed_iput_lock);
3239 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3242 spin_lock(&fs_info->delayed_iput_lock);
3243 while (!list_empty(&fs_info->delayed_iputs)) {
3244 struct btrfs_inode *inode;
3246 inode = list_first_entry(&fs_info->delayed_iputs,
3247 struct btrfs_inode, delayed_iput);
3248 run_delayed_iput_locked(fs_info, inode);
3250 spin_unlock(&fs_info->delayed_iput_lock);
3254 * Wait for flushing all delayed iputs
3256 * @fs_info: the filesystem
3258 * This will wait on any delayed iputs that are currently running with KILLABLE
3259 * set. Once they are all done running we will return, unless we are killed in
3260 * which case we return EINTR. This helps in user operations like fallocate etc
3261 * that might get blocked on the iputs.
3263 * Return EINTR if we were killed, 0 if nothing's pending
3265 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3267 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3268 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3275 * This creates an orphan entry for the given inode in case something goes wrong
3276 * in the middle of an unlink.
3278 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3279 struct btrfs_inode *inode)
3283 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3284 if (ret && ret != -EEXIST) {
3285 btrfs_abort_transaction(trans, ret);
3293 * We have done the delete so we can go ahead and remove the orphan item for
3294 * this particular inode.
3296 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3297 struct btrfs_inode *inode)
3299 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3303 * this cleans up any orphans that may be left on the list from the last use
3306 int btrfs_orphan_cleanup(struct btrfs_root *root)
3308 struct btrfs_fs_info *fs_info = root->fs_info;
3309 struct btrfs_path *path;
3310 struct extent_buffer *leaf;
3311 struct btrfs_key key, found_key;
3312 struct btrfs_trans_handle *trans;
3313 struct inode *inode;
3314 u64 last_objectid = 0;
3315 int ret = 0, nr_unlink = 0;
3317 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3320 path = btrfs_alloc_path();
3325 path->reada = READA_BACK;
3327 key.objectid = BTRFS_ORPHAN_OBJECTID;
3328 key.type = BTRFS_ORPHAN_ITEM_KEY;
3329 key.offset = (u64)-1;
3332 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3337 * if ret == 0 means we found what we were searching for, which
3338 * is weird, but possible, so only screw with path if we didn't
3339 * find the key and see if we have stuff that matches
3343 if (path->slots[0] == 0)
3348 /* pull out the item */
3349 leaf = path->nodes[0];
3350 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3352 /* make sure the item matches what we want */
3353 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3355 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3358 /* release the path since we're done with it */
3359 btrfs_release_path(path);
3362 * this is where we are basically btrfs_lookup, without the
3363 * crossing root thing. we store the inode number in the
3364 * offset of the orphan item.
3367 if (found_key.offset == last_objectid) {
3369 "Error removing orphan entry, stopping orphan cleanup");
3374 last_objectid = found_key.offset;
3376 found_key.objectid = found_key.offset;
3377 found_key.type = BTRFS_INODE_ITEM_KEY;
3378 found_key.offset = 0;
3379 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3380 ret = PTR_ERR_OR_ZERO(inode);
3381 if (ret && ret != -ENOENT)
3384 if (ret == -ENOENT && root == fs_info->tree_root) {
3385 struct btrfs_root *dead_root;
3386 int is_dead_root = 0;
3389 * This is an orphan in the tree root. Currently these
3390 * could come from 2 sources:
3391 * a) a root (snapshot/subvolume) deletion in progress
3392 * b) a free space cache inode
3393 * We need to distinguish those two, as the orphan item
3394 * for a root must not get deleted before the deletion
3395 * of the snapshot/subvolume's tree completes.
3397 * btrfs_find_orphan_roots() ran before us, which has
3398 * found all deleted roots and loaded them into
3399 * fs_info->fs_roots_radix. So here we can find if an
3400 * orphan item corresponds to a deleted root by looking
3401 * up the root from that radix tree.
3404 spin_lock(&fs_info->fs_roots_radix_lock);
3405 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3406 (unsigned long)found_key.objectid);
3407 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3409 spin_unlock(&fs_info->fs_roots_radix_lock);
3412 /* prevent this orphan from being found again */
3413 key.offset = found_key.objectid - 1;
3420 * If we have an inode with links, there are a couple of
3421 * possibilities. Old kernels (before v3.12) used to create an
3422 * orphan item for truncate indicating that there were possibly
3423 * extent items past i_size that needed to be deleted. In v3.12,
3424 * truncate was changed to update i_size in sync with the extent
3425 * items, but the (useless) orphan item was still created. Since
3426 * v4.18, we don't create the orphan item for truncate at all.
3428 * So, this item could mean that we need to do a truncate, but
3429 * only if this filesystem was last used on a pre-v3.12 kernel
3430 * and was not cleanly unmounted. The odds of that are quite
3431 * slim, and it's a pain to do the truncate now, so just delete
3434 * It's also possible that this orphan item was supposed to be
3435 * deleted but wasn't. The inode number may have been reused,
3436 * but either way, we can delete the orphan item.
3438 if (ret == -ENOENT || inode->i_nlink) {
3441 trans = btrfs_start_transaction(root, 1);
3442 if (IS_ERR(trans)) {
3443 ret = PTR_ERR(trans);
3446 btrfs_debug(fs_info, "auto deleting %Lu",
3447 found_key.objectid);
3448 ret = btrfs_del_orphan_item(trans, root,
3449 found_key.objectid);
3450 btrfs_end_transaction(trans);
3458 /* this will do delete_inode and everything for us */
3461 /* release the path since we're done with it */
3462 btrfs_release_path(path);
3464 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3466 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3467 trans = btrfs_join_transaction(root);
3469 btrfs_end_transaction(trans);
3473 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3477 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3478 btrfs_free_path(path);
3483 * very simple check to peek ahead in the leaf looking for xattrs. If we
3484 * don't find any xattrs, we know there can't be any acls.
3486 * slot is the slot the inode is in, objectid is the objectid of the inode
3488 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3489 int slot, u64 objectid,
3490 int *first_xattr_slot)
3492 u32 nritems = btrfs_header_nritems(leaf);
3493 struct btrfs_key found_key;
3494 static u64 xattr_access = 0;
3495 static u64 xattr_default = 0;
3498 if (!xattr_access) {
3499 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3500 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3501 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3502 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3506 *first_xattr_slot = -1;
3507 while (slot < nritems) {
3508 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3510 /* we found a different objectid, there must not be acls */
3511 if (found_key.objectid != objectid)
3514 /* we found an xattr, assume we've got an acl */
3515 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3516 if (*first_xattr_slot == -1)
3517 *first_xattr_slot = slot;
3518 if (found_key.offset == xattr_access ||
3519 found_key.offset == xattr_default)
3524 * we found a key greater than an xattr key, there can't
3525 * be any acls later on
3527 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3534 * it goes inode, inode backrefs, xattrs, extents,
3535 * so if there are a ton of hard links to an inode there can
3536 * be a lot of backrefs. Don't waste time searching too hard,
3537 * this is just an optimization
3542 /* we hit the end of the leaf before we found an xattr or
3543 * something larger than an xattr. We have to assume the inode
3546 if (*first_xattr_slot == -1)
3547 *first_xattr_slot = slot;
3552 * read an inode from the btree into the in-memory inode
3554 static int btrfs_read_locked_inode(struct inode *inode,
3555 struct btrfs_path *in_path)
3557 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3558 struct btrfs_path *path = in_path;
3559 struct extent_buffer *leaf;
3560 struct btrfs_inode_item *inode_item;
3561 struct btrfs_root *root = BTRFS_I(inode)->root;
3562 struct btrfs_key location;
3567 bool filled = false;
3568 int first_xattr_slot;
3570 ret = btrfs_fill_inode(inode, &rdev);
3575 path = btrfs_alloc_path();
3580 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3582 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3584 if (path != in_path)
3585 btrfs_free_path(path);
3589 leaf = path->nodes[0];
3594 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3595 struct btrfs_inode_item);
3596 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3597 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3598 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3599 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3600 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3601 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3602 round_up(i_size_read(inode), fs_info->sectorsize));
3604 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3605 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3607 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3608 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3610 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3611 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3613 BTRFS_I(inode)->i_otime.tv_sec =
3614 btrfs_timespec_sec(leaf, &inode_item->otime);
3615 BTRFS_I(inode)->i_otime.tv_nsec =
3616 btrfs_timespec_nsec(leaf, &inode_item->otime);
3618 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3619 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3620 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3622 inode_set_iversion_queried(inode,
3623 btrfs_inode_sequence(leaf, inode_item));
3624 inode->i_generation = BTRFS_I(inode)->generation;
3626 rdev = btrfs_inode_rdev(leaf, inode_item);
3628 BTRFS_I(inode)->index_cnt = (u64)-1;
3629 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3633 * If we were modified in the current generation and evicted from memory
3634 * and then re-read we need to do a full sync since we don't have any
3635 * idea about which extents were modified before we were evicted from
3638 * This is required for both inode re-read from disk and delayed inode
3639 * in delayed_nodes_tree.
3641 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3642 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3643 &BTRFS_I(inode)->runtime_flags);
3646 * We don't persist the id of the transaction where an unlink operation
3647 * against the inode was last made. So here we assume the inode might
3648 * have been evicted, and therefore the exact value of last_unlink_trans
3649 * lost, and set it to last_trans to avoid metadata inconsistencies
3650 * between the inode and its parent if the inode is fsync'ed and the log
3651 * replayed. For example, in the scenario:
3654 * ln mydir/foo mydir/bar
3657 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3658 * xfs_io -c fsync mydir/foo
3660 * mount fs, triggers fsync log replay
3662 * We must make sure that when we fsync our inode foo we also log its
3663 * parent inode, otherwise after log replay the parent still has the
3664 * dentry with the "bar" name but our inode foo has a link count of 1
3665 * and doesn't have an inode ref with the name "bar" anymore.
3667 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3668 * but it guarantees correctness at the expense of occasional full
3669 * transaction commits on fsync if our inode is a directory, or if our
3670 * inode is not a directory, logging its parent unnecessarily.
3672 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3675 * Same logic as for last_unlink_trans. We don't persist the generation
3676 * of the last transaction where this inode was used for a reflink
3677 * operation, so after eviction and reloading the inode we must be
3678 * pessimistic and assume the last transaction that modified the inode.
3680 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3683 if (inode->i_nlink != 1 ||
3684 path->slots[0] >= btrfs_header_nritems(leaf))
3687 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3688 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3691 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3692 if (location.type == BTRFS_INODE_REF_KEY) {
3693 struct btrfs_inode_ref *ref;
3695 ref = (struct btrfs_inode_ref *)ptr;
3696 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3697 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3698 struct btrfs_inode_extref *extref;
3700 extref = (struct btrfs_inode_extref *)ptr;
3701 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3706 * try to precache a NULL acl entry for files that don't have
3707 * any xattrs or acls
3709 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3710 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3711 if (first_xattr_slot != -1) {
3712 path->slots[0] = first_xattr_slot;
3713 ret = btrfs_load_inode_props(inode, path);
3716 "error loading props for ino %llu (root %llu): %d",
3717 btrfs_ino(BTRFS_I(inode)),
3718 root->root_key.objectid, ret);
3720 if (path != in_path)
3721 btrfs_free_path(path);
3724 cache_no_acl(inode);
3726 switch (inode->i_mode & S_IFMT) {
3728 inode->i_mapping->a_ops = &btrfs_aops;
3729 inode->i_fop = &btrfs_file_operations;
3730 inode->i_op = &btrfs_file_inode_operations;
3733 inode->i_fop = &btrfs_dir_file_operations;
3734 inode->i_op = &btrfs_dir_inode_operations;
3737 inode->i_op = &btrfs_symlink_inode_operations;
3738 inode_nohighmem(inode);
3739 inode->i_mapping->a_ops = &btrfs_aops;
3742 inode->i_op = &btrfs_special_inode_operations;
3743 init_special_inode(inode, inode->i_mode, rdev);
3747 btrfs_sync_inode_flags_to_i_flags(inode);
3752 * given a leaf and an inode, copy the inode fields into the leaf
3754 static void fill_inode_item(struct btrfs_trans_handle *trans,
3755 struct extent_buffer *leaf,
3756 struct btrfs_inode_item *item,
3757 struct inode *inode)
3759 struct btrfs_map_token token;
3761 btrfs_init_map_token(&token, leaf);
3763 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3764 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3765 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3766 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3767 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3769 btrfs_set_token_timespec_sec(&token, &item->atime,
3770 inode->i_atime.tv_sec);
3771 btrfs_set_token_timespec_nsec(&token, &item->atime,
3772 inode->i_atime.tv_nsec);
3774 btrfs_set_token_timespec_sec(&token, &item->mtime,
3775 inode->i_mtime.tv_sec);
3776 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3777 inode->i_mtime.tv_nsec);
3779 btrfs_set_token_timespec_sec(&token, &item->ctime,
3780 inode->i_ctime.tv_sec);
3781 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3782 inode->i_ctime.tv_nsec);
3784 btrfs_set_token_timespec_sec(&token, &item->otime,
3785 BTRFS_I(inode)->i_otime.tv_sec);
3786 btrfs_set_token_timespec_nsec(&token, &item->otime,
3787 BTRFS_I(inode)->i_otime.tv_nsec);
3789 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3790 btrfs_set_token_inode_generation(&token, item,
3791 BTRFS_I(inode)->generation);
3792 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3793 btrfs_set_token_inode_transid(&token, item, trans->transid);
3794 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3795 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3796 btrfs_set_token_inode_block_group(&token, item, 0);
3800 * copy everything in the in-memory inode into the btree.
3802 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3803 struct btrfs_root *root,
3804 struct btrfs_inode *inode)
3806 struct btrfs_inode_item *inode_item;
3807 struct btrfs_path *path;
3808 struct extent_buffer *leaf;
3811 path = btrfs_alloc_path();
3815 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
3822 leaf = path->nodes[0];
3823 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3824 struct btrfs_inode_item);
3826 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
3827 btrfs_mark_buffer_dirty(leaf);
3828 btrfs_set_inode_last_trans(trans, inode);
3831 btrfs_free_path(path);
3836 * copy everything in the in-memory inode into the btree.
3838 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3839 struct btrfs_root *root,
3840 struct btrfs_inode *inode)
3842 struct btrfs_fs_info *fs_info = root->fs_info;
3846 * If the inode is a free space inode, we can deadlock during commit
3847 * if we put it into the delayed code.
3849 * The data relocation inode should also be directly updated
3852 if (!btrfs_is_free_space_inode(inode)
3853 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3854 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3855 btrfs_update_root_times(trans, root);
3857 ret = btrfs_delayed_update_inode(trans, root, inode);
3859 btrfs_set_inode_last_trans(trans, inode);
3863 return btrfs_update_inode_item(trans, root, inode);
3866 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3867 struct btrfs_root *root, struct btrfs_inode *inode)
3871 ret = btrfs_update_inode(trans, root, inode);
3873 return btrfs_update_inode_item(trans, root, inode);
3878 * unlink helper that gets used here in inode.c and in the tree logging
3879 * recovery code. It remove a link in a directory with a given name, and
3880 * also drops the back refs in the inode to the directory
3882 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3883 struct btrfs_root *root,
3884 struct btrfs_inode *dir,
3885 struct btrfs_inode *inode,
3886 const char *name, int name_len)
3888 struct btrfs_fs_info *fs_info = root->fs_info;
3889 struct btrfs_path *path;
3891 struct btrfs_dir_item *di;
3893 u64 ino = btrfs_ino(inode);
3894 u64 dir_ino = btrfs_ino(dir);
3896 path = btrfs_alloc_path();
3902 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3903 name, name_len, -1);
3904 if (IS_ERR_OR_NULL(di)) {
3905 ret = di ? PTR_ERR(di) : -ENOENT;
3908 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3911 btrfs_release_path(path);
3914 * If we don't have dir index, we have to get it by looking up
3915 * the inode ref, since we get the inode ref, remove it directly,
3916 * it is unnecessary to do delayed deletion.
3918 * But if we have dir index, needn't search inode ref to get it.
3919 * Since the inode ref is close to the inode item, it is better
3920 * that we delay to delete it, and just do this deletion when
3921 * we update the inode item.
3923 if (inode->dir_index) {
3924 ret = btrfs_delayed_delete_inode_ref(inode);
3926 index = inode->dir_index;
3931 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3935 "failed to delete reference to %.*s, inode %llu parent %llu",
3936 name_len, name, ino, dir_ino);
3937 btrfs_abort_transaction(trans, ret);
3941 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3943 btrfs_abort_transaction(trans, ret);
3947 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3949 if (ret != 0 && ret != -ENOENT) {
3950 btrfs_abort_transaction(trans, ret);
3954 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3959 btrfs_abort_transaction(trans, ret);
3962 * If we have a pending delayed iput we could end up with the final iput
3963 * being run in btrfs-cleaner context. If we have enough of these built
3964 * up we can end up burning a lot of time in btrfs-cleaner without any
3965 * way to throttle the unlinks. Since we're currently holding a ref on
3966 * the inode we can run the delayed iput here without any issues as the
3967 * final iput won't be done until after we drop the ref we're currently
3970 btrfs_run_delayed_iput(fs_info, inode);
3972 btrfs_free_path(path);
3976 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3977 inode_inc_iversion(&inode->vfs_inode);
3978 inode_inc_iversion(&dir->vfs_inode);
3979 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3980 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3981 ret = btrfs_update_inode(trans, root, dir);
3986 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3987 struct btrfs_root *root,
3988 struct btrfs_inode *dir, struct btrfs_inode *inode,
3989 const char *name, int name_len)
3992 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3994 drop_nlink(&inode->vfs_inode);
3995 ret = btrfs_update_inode(trans, root, inode);
4001 * helper to start transaction for unlink and rmdir.
4003 * unlink and rmdir are special in btrfs, they do not always free space, so
4004 * if we cannot make our reservations the normal way try and see if there is
4005 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4006 * allow the unlink to occur.
4008 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4010 struct btrfs_root *root = BTRFS_I(dir)->root;
4013 * 1 for the possible orphan item
4014 * 1 for the dir item
4015 * 1 for the dir index
4016 * 1 for the inode ref
4019 return btrfs_start_transaction_fallback_global_rsv(root, 5);
4022 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4024 struct btrfs_root *root = BTRFS_I(dir)->root;
4025 struct btrfs_trans_handle *trans;
4026 struct inode *inode = d_inode(dentry);
4029 trans = __unlink_start_trans(dir);
4031 return PTR_ERR(trans);
4033 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4036 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4037 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4038 dentry->d_name.len);
4042 if (inode->i_nlink == 0) {
4043 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4049 btrfs_end_transaction(trans);
4050 btrfs_btree_balance_dirty(root->fs_info);
4054 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4055 struct inode *dir, struct dentry *dentry)
4057 struct btrfs_root *root = BTRFS_I(dir)->root;
4058 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4059 struct btrfs_path *path;
4060 struct extent_buffer *leaf;
4061 struct btrfs_dir_item *di;
4062 struct btrfs_key key;
4063 const char *name = dentry->d_name.name;
4064 int name_len = dentry->d_name.len;
4068 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4070 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4071 objectid = inode->root->root_key.objectid;
4072 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4073 objectid = inode->location.objectid;
4079 path = btrfs_alloc_path();
4083 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4084 name, name_len, -1);
4085 if (IS_ERR_OR_NULL(di)) {
4086 ret = di ? PTR_ERR(di) : -ENOENT;
4090 leaf = path->nodes[0];
4091 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4092 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4093 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4095 btrfs_abort_transaction(trans, ret);
4098 btrfs_release_path(path);
4101 * This is a placeholder inode for a subvolume we didn't have a
4102 * reference to at the time of the snapshot creation. In the meantime
4103 * we could have renamed the real subvol link into our snapshot, so
4104 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
4105 * Instead simply lookup the dir_index_item for this entry so we can
4106 * remove it. Otherwise we know we have a ref to the root and we can
4107 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4109 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4110 di = btrfs_search_dir_index_item(root, path, dir_ino,
4112 if (IS_ERR_OR_NULL(di)) {
4117 btrfs_abort_transaction(trans, ret);
4121 leaf = path->nodes[0];
4122 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4124 btrfs_release_path(path);
4126 ret = btrfs_del_root_ref(trans, objectid,
4127 root->root_key.objectid, dir_ino,
4128 &index, name, name_len);
4130 btrfs_abort_transaction(trans, ret);
4135 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4137 btrfs_abort_transaction(trans, ret);
4141 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4142 inode_inc_iversion(dir);
4143 dir->i_mtime = dir->i_ctime = current_time(dir);
4144 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4146 btrfs_abort_transaction(trans, ret);
4148 btrfs_free_path(path);
4153 * Helper to check if the subvolume references other subvolumes or if it's
4156 static noinline int may_destroy_subvol(struct btrfs_root *root)
4158 struct btrfs_fs_info *fs_info = root->fs_info;
4159 struct btrfs_path *path;
4160 struct btrfs_dir_item *di;
4161 struct btrfs_key key;
4165 path = btrfs_alloc_path();
4169 /* Make sure this root isn't set as the default subvol */
4170 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4171 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4172 dir_id, "default", 7, 0);
4173 if (di && !IS_ERR(di)) {
4174 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4175 if (key.objectid == root->root_key.objectid) {
4178 "deleting default subvolume %llu is not allowed",
4182 btrfs_release_path(path);
4185 key.objectid = root->root_key.objectid;
4186 key.type = BTRFS_ROOT_REF_KEY;
4187 key.offset = (u64)-1;
4189 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4195 if (path->slots[0] > 0) {
4197 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4198 if (key.objectid == root->root_key.objectid &&
4199 key.type == BTRFS_ROOT_REF_KEY)
4203 btrfs_free_path(path);
4207 /* Delete all dentries for inodes belonging to the root */
4208 static void btrfs_prune_dentries(struct btrfs_root *root)
4210 struct btrfs_fs_info *fs_info = root->fs_info;
4211 struct rb_node *node;
4212 struct rb_node *prev;
4213 struct btrfs_inode *entry;
4214 struct inode *inode;
4217 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4218 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4220 spin_lock(&root->inode_lock);
4222 node = root->inode_tree.rb_node;
4226 entry = rb_entry(node, struct btrfs_inode, rb_node);
4228 if (objectid < btrfs_ino(entry))
4229 node = node->rb_left;
4230 else if (objectid > btrfs_ino(entry))
4231 node = node->rb_right;
4237 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4238 if (objectid <= btrfs_ino(entry)) {
4242 prev = rb_next(prev);
4246 entry = rb_entry(node, struct btrfs_inode, rb_node);
4247 objectid = btrfs_ino(entry) + 1;
4248 inode = igrab(&entry->vfs_inode);
4250 spin_unlock(&root->inode_lock);
4251 if (atomic_read(&inode->i_count) > 1)
4252 d_prune_aliases(inode);
4254 * btrfs_drop_inode will have it removed from the inode
4255 * cache when its usage count hits zero.
4259 spin_lock(&root->inode_lock);
4263 if (cond_resched_lock(&root->inode_lock))
4266 node = rb_next(node);
4268 spin_unlock(&root->inode_lock);
4271 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4273 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4274 struct btrfs_root *root = BTRFS_I(dir)->root;
4275 struct inode *inode = d_inode(dentry);
4276 struct btrfs_root *dest = BTRFS_I(inode)->root;
4277 struct btrfs_trans_handle *trans;
4278 struct btrfs_block_rsv block_rsv;
4283 * Don't allow to delete a subvolume with send in progress. This is
4284 * inside the inode lock so the error handling that has to drop the bit
4285 * again is not run concurrently.
4287 spin_lock(&dest->root_item_lock);
4288 if (dest->send_in_progress) {
4289 spin_unlock(&dest->root_item_lock);
4291 "attempt to delete subvolume %llu during send",
4292 dest->root_key.objectid);
4295 root_flags = btrfs_root_flags(&dest->root_item);
4296 btrfs_set_root_flags(&dest->root_item,
4297 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4298 spin_unlock(&dest->root_item_lock);
4300 down_write(&fs_info->subvol_sem);
4302 ret = may_destroy_subvol(dest);
4306 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4308 * One for dir inode,
4309 * two for dir entries,
4310 * two for root ref/backref.
4312 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4316 trans = btrfs_start_transaction(root, 0);
4317 if (IS_ERR(trans)) {
4318 ret = PTR_ERR(trans);
4321 trans->block_rsv = &block_rsv;
4322 trans->bytes_reserved = block_rsv.size;
4324 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4326 ret = btrfs_unlink_subvol(trans, dir, dentry);
4328 btrfs_abort_transaction(trans, ret);
4332 btrfs_record_root_in_trans(trans, dest);
4334 memset(&dest->root_item.drop_progress, 0,
4335 sizeof(dest->root_item.drop_progress));
4336 btrfs_set_root_drop_level(&dest->root_item, 0);
4337 btrfs_set_root_refs(&dest->root_item, 0);
4339 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4340 ret = btrfs_insert_orphan_item(trans,
4342 dest->root_key.objectid);
4344 btrfs_abort_transaction(trans, ret);
4349 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4350 BTRFS_UUID_KEY_SUBVOL,
4351 dest->root_key.objectid);
4352 if (ret && ret != -ENOENT) {
4353 btrfs_abort_transaction(trans, ret);
4356 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4357 ret = btrfs_uuid_tree_remove(trans,
4358 dest->root_item.received_uuid,
4359 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4360 dest->root_key.objectid);
4361 if (ret && ret != -ENOENT) {
4362 btrfs_abort_transaction(trans, ret);
4367 free_anon_bdev(dest->anon_dev);
4370 trans->block_rsv = NULL;
4371 trans->bytes_reserved = 0;
4372 ret = btrfs_end_transaction(trans);
4373 inode->i_flags |= S_DEAD;
4375 btrfs_subvolume_release_metadata(root, &block_rsv);
4377 up_write(&fs_info->subvol_sem);
4379 spin_lock(&dest->root_item_lock);
4380 root_flags = btrfs_root_flags(&dest->root_item);
4381 btrfs_set_root_flags(&dest->root_item,
4382 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4383 spin_unlock(&dest->root_item_lock);
4385 d_invalidate(dentry);
4386 btrfs_prune_dentries(dest);
4387 ASSERT(dest->send_in_progress == 0);
4393 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4395 struct inode *inode = d_inode(dentry);
4397 struct btrfs_root *root = BTRFS_I(dir)->root;
4398 struct btrfs_trans_handle *trans;
4399 u64 last_unlink_trans;
4401 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4403 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4404 return btrfs_delete_subvolume(dir, dentry);
4406 trans = __unlink_start_trans(dir);
4408 return PTR_ERR(trans);
4410 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4411 err = btrfs_unlink_subvol(trans, dir, dentry);
4415 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4419 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4421 /* now the directory is empty */
4422 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4423 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4424 dentry->d_name.len);
4426 btrfs_i_size_write(BTRFS_I(inode), 0);
4428 * Propagate the last_unlink_trans value of the deleted dir to
4429 * its parent directory. This is to prevent an unrecoverable
4430 * log tree in the case we do something like this:
4432 * 2) create snapshot under dir foo
4433 * 3) delete the snapshot
4436 * 6) fsync foo or some file inside foo
4438 if (last_unlink_trans >= trans->transid)
4439 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4442 btrfs_end_transaction(trans);
4443 btrfs_btree_balance_dirty(root->fs_info);
4449 * Return this if we need to call truncate_block for the last bit of the
4452 #define NEED_TRUNCATE_BLOCK 1
4455 * this can truncate away extent items, csum items and directory items.
4456 * It starts at a high offset and removes keys until it can't find
4457 * any higher than new_size
4459 * csum items that cross the new i_size are truncated to the new size
4462 * min_type is the minimum key type to truncate down to. If set to 0, this
4463 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4465 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4466 struct btrfs_root *root,
4467 struct btrfs_inode *inode,
4468 u64 new_size, u32 min_type)
4470 struct btrfs_fs_info *fs_info = root->fs_info;
4471 struct btrfs_path *path;
4472 struct extent_buffer *leaf;
4473 struct btrfs_file_extent_item *fi;
4474 struct btrfs_key key;
4475 struct btrfs_key found_key;
4476 u64 extent_start = 0;
4477 u64 extent_num_bytes = 0;
4478 u64 extent_offset = 0;
4480 u64 last_size = new_size;
4481 u32 found_type = (u8)-1;
4484 int pending_del_nr = 0;
4485 int pending_del_slot = 0;
4486 int extent_type = -1;
4488 u64 ino = btrfs_ino(inode);
4489 u64 bytes_deleted = 0;
4490 bool be_nice = false;
4491 bool should_throttle = false;
4492 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4493 struct extent_state *cached_state = NULL;
4495 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4498 * For non-free space inodes and non-shareable roots, we want to back
4499 * off from time to time. This means all inodes in subvolume roots,
4500 * reloc roots, and data reloc roots.
4502 if (!btrfs_is_free_space_inode(inode) &&
4503 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4506 path = btrfs_alloc_path();
4509 path->reada = READA_BACK;
4511 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4512 lock_extent_bits(&inode->io_tree, lock_start, (u64)-1,
4516 * We want to drop from the next block forward in case this
4517 * new size is not block aligned since we will be keeping the
4518 * last block of the extent just the way it is.
4520 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4521 fs_info->sectorsize),
4526 * This function is also used to drop the items in the log tree before
4527 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4528 * it is used to drop the logged items. So we shouldn't kill the delayed
4531 if (min_type == 0 && root == inode->root)
4532 btrfs_kill_delayed_inode_items(inode);
4535 key.offset = (u64)-1;
4540 * with a 16K leaf size and 128MB extents, you can actually queue
4541 * up a huge file in a single leaf. Most of the time that
4542 * bytes_deleted is > 0, it will be huge by the time we get here
4544 if (be_nice && bytes_deleted > SZ_32M &&
4545 btrfs_should_end_transaction(trans)) {
4550 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4556 /* there are no items in the tree for us to truncate, we're
4559 if (path->slots[0] == 0)
4565 u64 clear_start = 0, clear_len = 0;
4568 leaf = path->nodes[0];
4569 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4570 found_type = found_key.type;
4572 if (found_key.objectid != ino)
4575 if (found_type < min_type)
4578 item_end = found_key.offset;
4579 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4580 fi = btrfs_item_ptr(leaf, path->slots[0],
4581 struct btrfs_file_extent_item);
4582 extent_type = btrfs_file_extent_type(leaf, fi);
4583 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4585 btrfs_file_extent_num_bytes(leaf, fi);
4587 trace_btrfs_truncate_show_fi_regular(
4588 inode, leaf, fi, found_key.offset);
4589 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4590 item_end += btrfs_file_extent_ram_bytes(leaf,
4593 trace_btrfs_truncate_show_fi_inline(
4594 inode, leaf, fi, path->slots[0],
4599 if (found_type > min_type) {
4602 if (item_end < new_size)
4604 if (found_key.offset >= new_size)
4610 /* FIXME, shrink the extent if the ref count is only 1 */
4611 if (found_type != BTRFS_EXTENT_DATA_KEY)
4614 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4617 clear_start = found_key.offset;
4618 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4620 u64 orig_num_bytes =
4621 btrfs_file_extent_num_bytes(leaf, fi);
4622 extent_num_bytes = ALIGN(new_size -
4624 fs_info->sectorsize);
4625 clear_start = ALIGN(new_size, fs_info->sectorsize);
4626 btrfs_set_file_extent_num_bytes(leaf, fi,
4628 num_dec = (orig_num_bytes -
4630 if (test_bit(BTRFS_ROOT_SHAREABLE,
4633 inode_sub_bytes(&inode->vfs_inode,
4635 btrfs_mark_buffer_dirty(leaf);
4638 btrfs_file_extent_disk_num_bytes(leaf,
4640 extent_offset = found_key.offset -
4641 btrfs_file_extent_offset(leaf, fi);
4643 /* FIXME blocksize != 4096 */
4644 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4645 if (extent_start != 0) {
4647 if (test_bit(BTRFS_ROOT_SHAREABLE,
4649 inode_sub_bytes(&inode->vfs_inode,
4653 clear_len = num_dec;
4654 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4656 * we can't truncate inline items that have had
4660 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4661 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4662 btrfs_file_extent_compression(leaf, fi) == 0) {
4663 u32 size = (u32)(new_size - found_key.offset);
4665 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4666 size = btrfs_file_extent_calc_inline_size(size);
4667 btrfs_truncate_item(path, size, 1);
4668 } else if (!del_item) {
4670 * We have to bail so the last_size is set to
4671 * just before this extent.
4673 ret = NEED_TRUNCATE_BLOCK;
4677 * Inline extents are special, we just treat
4678 * them as a full sector worth in the file
4679 * extent tree just for simplicity sake.
4681 clear_len = fs_info->sectorsize;
4684 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4685 inode_sub_bytes(&inode->vfs_inode,
4686 item_end + 1 - new_size);
4690 * We use btrfs_truncate_inode_items() to clean up log trees for
4691 * multiple fsyncs, and in this case we don't want to clear the
4692 * file extent range because it's just the log.
4694 if (root == inode->root) {
4695 ret = btrfs_inode_clear_file_extent_range(inode,
4696 clear_start, clear_len);
4698 btrfs_abort_transaction(trans, ret);
4704 last_size = found_key.offset;
4706 last_size = new_size;
4708 if (!pending_del_nr) {
4709 /* no pending yet, add ourselves */
4710 pending_del_slot = path->slots[0];
4712 } else if (pending_del_nr &&
4713 path->slots[0] + 1 == pending_del_slot) {
4714 /* hop on the pending chunk */
4716 pending_del_slot = path->slots[0];
4723 should_throttle = false;
4726 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4727 struct btrfs_ref ref = { 0 };
4729 bytes_deleted += extent_num_bytes;
4731 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4732 extent_start, extent_num_bytes, 0);
4733 ref.real_root = root->root_key.objectid;
4734 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4735 ino, extent_offset);
4736 ret = btrfs_free_extent(trans, &ref);
4738 btrfs_abort_transaction(trans, ret);
4742 if (btrfs_should_throttle_delayed_refs(trans))
4743 should_throttle = true;
4747 if (found_type == BTRFS_INODE_ITEM_KEY)
4750 if (path->slots[0] == 0 ||
4751 path->slots[0] != pending_del_slot ||
4753 if (pending_del_nr) {
4754 ret = btrfs_del_items(trans, root, path,
4758 btrfs_abort_transaction(trans, ret);
4763 btrfs_release_path(path);
4766 * We can generate a lot of delayed refs, so we need to
4767 * throttle every once and a while and make sure we're
4768 * adding enough space to keep up with the work we are
4769 * generating. Since we hold a transaction here we
4770 * can't flush, and we don't want to FLUSH_LIMIT because
4771 * we could have generated too many delayed refs to
4772 * actually allocate, so just bail if we're short and
4773 * let the normal reservation dance happen higher up.
4775 if (should_throttle) {
4776 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4777 BTRFS_RESERVE_NO_FLUSH);
4789 if (ret >= 0 && pending_del_nr) {
4792 err = btrfs_del_items(trans, root, path, pending_del_slot,
4795 btrfs_abort_transaction(trans, err);
4799 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4800 ASSERT(last_size >= new_size);
4801 if (!ret && last_size > new_size)
4802 last_size = new_size;
4803 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4804 unlock_extent_cached(&inode->io_tree, lock_start, (u64)-1,
4808 btrfs_free_path(path);
4813 * btrfs_truncate_block - read, zero a chunk and write a block
4814 * @inode - inode that we're zeroing
4815 * @from - the offset to start zeroing
4816 * @len - the length to zero, 0 to zero the entire range respective to the
4818 * @front - zero up to the offset instead of from the offset on
4820 * This will find the block for the "from" offset and cow the block and zero the
4821 * part we want to zero. This is used with truncate and hole punching.
4823 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4826 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4827 struct address_space *mapping = inode->vfs_inode.i_mapping;
4828 struct extent_io_tree *io_tree = &inode->io_tree;
4829 struct btrfs_ordered_extent *ordered;
4830 struct extent_state *cached_state = NULL;
4831 struct extent_changeset *data_reserved = NULL;
4833 bool only_release_metadata = false;
4834 u32 blocksize = fs_info->sectorsize;
4835 pgoff_t index = from >> PAGE_SHIFT;
4836 unsigned offset = from & (blocksize - 1);
4838 gfp_t mask = btrfs_alloc_write_mask(mapping);
4839 size_t write_bytes = blocksize;
4844 if (IS_ALIGNED(offset, blocksize) &&
4845 (!len || IS_ALIGNED(len, blocksize)))
4848 block_start = round_down(from, blocksize);
4849 block_end = block_start + blocksize - 1;
4851 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4854 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
4855 /* For nocow case, no need to reserve data space */
4856 only_release_metadata = true;
4861 ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
4863 if (!only_release_metadata)
4864 btrfs_free_reserved_data_space(inode, data_reserved,
4865 block_start, blocksize);
4869 page = find_or_create_page(mapping, index, mask);
4871 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4873 btrfs_delalloc_release_extents(inode, blocksize);
4877 ret = set_page_extent_mapped(page);
4881 if (!PageUptodate(page)) {
4882 ret = btrfs_readpage(NULL, page);
4884 if (page->mapping != mapping) {
4889 if (!PageUptodate(page)) {
4894 wait_on_page_writeback(page);
4896 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4898 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4900 unlock_extent_cached(io_tree, block_start, block_end,
4904 btrfs_start_ordered_extent(ordered, 1);
4905 btrfs_put_ordered_extent(ordered);
4909 clear_extent_bit(&inode->io_tree, block_start, block_end,
4910 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4911 0, 0, &cached_state);
4913 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4916 unlock_extent_cached(io_tree, block_start, block_end,
4921 if (offset != blocksize) {
4923 len = blocksize - offset;
4926 memset(kaddr + (block_start - page_offset(page)),
4929 memset(kaddr + (block_start - page_offset(page)) + offset,
4931 flush_dcache_page(page);
4934 ClearPageChecked(page);
4935 set_page_dirty(page);
4936 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4938 if (only_release_metadata)
4939 set_extent_bit(&inode->io_tree, block_start, block_end,
4940 EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
4944 if (only_release_metadata)
4945 btrfs_delalloc_release_metadata(inode, blocksize, true);
4947 btrfs_delalloc_release_space(inode, data_reserved,
4948 block_start, blocksize, true);
4950 btrfs_delalloc_release_extents(inode, blocksize);
4954 if (only_release_metadata)
4955 btrfs_check_nocow_unlock(inode);
4956 extent_changeset_free(data_reserved);
4960 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4961 u64 offset, u64 len)
4963 struct btrfs_fs_info *fs_info = root->fs_info;
4964 struct btrfs_trans_handle *trans;
4965 struct btrfs_drop_extents_args drop_args = { 0 };
4969 * Still need to make sure the inode looks like it's been updated so
4970 * that any holes get logged if we fsync.
4972 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4973 inode->last_trans = fs_info->generation;
4974 inode->last_sub_trans = root->log_transid;
4975 inode->last_log_commit = root->last_log_commit;
4980 * 1 - for the one we're dropping
4981 * 1 - for the one we're adding
4982 * 1 - for updating the inode.
4984 trans = btrfs_start_transaction(root, 3);
4986 return PTR_ERR(trans);
4988 drop_args.start = offset;
4989 drop_args.end = offset + len;
4990 drop_args.drop_cache = true;
4992 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4994 btrfs_abort_transaction(trans, ret);
4995 btrfs_end_transaction(trans);
4999 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
5000 offset, 0, 0, len, 0, len, 0, 0, 0);
5002 btrfs_abort_transaction(trans, ret);
5004 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5005 btrfs_update_inode(trans, root, inode);
5007 btrfs_end_transaction(trans);
5012 * This function puts in dummy file extents for the area we're creating a hole
5013 * for. So if we are truncating this file to a larger size we need to insert
5014 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5015 * the range between oldsize and size
5017 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5019 struct btrfs_root *root = inode->root;
5020 struct btrfs_fs_info *fs_info = root->fs_info;
5021 struct extent_io_tree *io_tree = &inode->io_tree;
5022 struct extent_map *em = NULL;
5023 struct extent_state *cached_state = NULL;
5024 struct extent_map_tree *em_tree = &inode->extent_tree;
5025 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5026 u64 block_end = ALIGN(size, fs_info->sectorsize);
5033 * If our size started in the middle of a block we need to zero out the
5034 * rest of the block before we expand the i_size, otherwise we could
5035 * expose stale data.
5037 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5041 if (size <= hole_start)
5044 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5046 cur_offset = hole_start;
5048 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5049 block_end - cur_offset);
5055 last_byte = min(extent_map_end(em), block_end);
5056 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5057 hole_size = last_byte - cur_offset;
5059 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5060 struct extent_map *hole_em;
5062 err = maybe_insert_hole(root, inode, cur_offset,
5067 err = btrfs_inode_set_file_extent_range(inode,
5068 cur_offset, hole_size);
5072 btrfs_drop_extent_cache(inode, cur_offset,
5073 cur_offset + hole_size - 1, 0);
5074 hole_em = alloc_extent_map();
5076 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5077 &inode->runtime_flags);
5080 hole_em->start = cur_offset;
5081 hole_em->len = hole_size;
5082 hole_em->orig_start = cur_offset;
5084 hole_em->block_start = EXTENT_MAP_HOLE;
5085 hole_em->block_len = 0;
5086 hole_em->orig_block_len = 0;
5087 hole_em->ram_bytes = hole_size;
5088 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5089 hole_em->generation = fs_info->generation;
5092 write_lock(&em_tree->lock);
5093 err = add_extent_mapping(em_tree, hole_em, 1);
5094 write_unlock(&em_tree->lock);
5097 btrfs_drop_extent_cache(inode, cur_offset,
5101 free_extent_map(hole_em);
5103 err = btrfs_inode_set_file_extent_range(inode,
5104 cur_offset, hole_size);
5109 free_extent_map(em);
5111 cur_offset = last_byte;
5112 if (cur_offset >= block_end)
5115 free_extent_map(em);
5116 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5120 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5122 struct btrfs_root *root = BTRFS_I(inode)->root;
5123 struct btrfs_trans_handle *trans;
5124 loff_t oldsize = i_size_read(inode);
5125 loff_t newsize = attr->ia_size;
5126 int mask = attr->ia_valid;
5130 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5131 * special case where we need to update the times despite not having
5132 * these flags set. For all other operations the VFS set these flags
5133 * explicitly if it wants a timestamp update.
5135 if (newsize != oldsize) {
5136 inode_inc_iversion(inode);
5137 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5138 inode->i_ctime = inode->i_mtime =
5139 current_time(inode);
5142 if (newsize > oldsize) {
5144 * Don't do an expanding truncate while snapshotting is ongoing.
5145 * This is to ensure the snapshot captures a fully consistent
5146 * state of this file - if the snapshot captures this expanding
5147 * truncation, it must capture all writes that happened before
5150 btrfs_drew_write_lock(&root->snapshot_lock);
5151 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5153 btrfs_drew_write_unlock(&root->snapshot_lock);
5157 trans = btrfs_start_transaction(root, 1);
5158 if (IS_ERR(trans)) {
5159 btrfs_drew_write_unlock(&root->snapshot_lock);
5160 return PTR_ERR(trans);
5163 i_size_write(inode, newsize);
5164 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5165 pagecache_isize_extended(inode, oldsize, newsize);
5166 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5167 btrfs_drew_write_unlock(&root->snapshot_lock);
5168 btrfs_end_transaction(trans);
5170 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5172 if (btrfs_is_zoned(fs_info)) {
5173 ret = btrfs_wait_ordered_range(inode,
5174 ALIGN(newsize, fs_info->sectorsize),
5181 * We're truncating a file that used to have good data down to
5182 * zero. Make sure any new writes to the file get on disk
5186 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5187 &BTRFS_I(inode)->runtime_flags);
5189 truncate_setsize(inode, newsize);
5191 inode_dio_wait(inode);
5193 ret = btrfs_truncate(inode, newsize == oldsize);
5194 if (ret && inode->i_nlink) {
5198 * Truncate failed, so fix up the in-memory size. We
5199 * adjusted disk_i_size down as we removed extents, so
5200 * wait for disk_i_size to be stable and then update the
5201 * in-memory size to match.
5203 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5206 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5213 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5216 struct inode *inode = d_inode(dentry);
5217 struct btrfs_root *root = BTRFS_I(inode)->root;
5220 if (btrfs_root_readonly(root))
5223 err = setattr_prepare(&init_user_ns, dentry, attr);
5227 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5228 err = btrfs_setsize(inode, attr);
5233 if (attr->ia_valid) {
5234 setattr_copy(&init_user_ns, inode, attr);
5235 inode_inc_iversion(inode);
5236 err = btrfs_dirty_inode(inode);
5238 if (!err && attr->ia_valid & ATTR_MODE)
5239 err = posix_acl_chmod(&init_user_ns, inode,
5247 * While truncating the inode pages during eviction, we get the VFS calling
5248 * btrfs_invalidatepage() against each page of the inode. This is slow because
5249 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5250 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5251 * extent_state structures over and over, wasting lots of time.
5253 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5254 * those expensive operations on a per page basis and do only the ordered io
5255 * finishing, while we release here the extent_map and extent_state structures,
5256 * without the excessive merging and splitting.
5258 static void evict_inode_truncate_pages(struct inode *inode)
5260 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5261 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5262 struct rb_node *node;
5264 ASSERT(inode->i_state & I_FREEING);
5265 truncate_inode_pages_final(&inode->i_data);
5267 write_lock(&map_tree->lock);
5268 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5269 struct extent_map *em;
5271 node = rb_first_cached(&map_tree->map);
5272 em = rb_entry(node, struct extent_map, rb_node);
5273 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5274 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5275 remove_extent_mapping(map_tree, em);
5276 free_extent_map(em);
5277 if (need_resched()) {
5278 write_unlock(&map_tree->lock);
5280 write_lock(&map_tree->lock);
5283 write_unlock(&map_tree->lock);
5286 * Keep looping until we have no more ranges in the io tree.
5287 * We can have ongoing bios started by readahead that have
5288 * their endio callback (extent_io.c:end_bio_extent_readpage)
5289 * still in progress (unlocked the pages in the bio but did not yet
5290 * unlocked the ranges in the io tree). Therefore this means some
5291 * ranges can still be locked and eviction started because before
5292 * submitting those bios, which are executed by a separate task (work
5293 * queue kthread), inode references (inode->i_count) were not taken
5294 * (which would be dropped in the end io callback of each bio).
5295 * Therefore here we effectively end up waiting for those bios and
5296 * anyone else holding locked ranges without having bumped the inode's
5297 * reference count - if we don't do it, when they access the inode's
5298 * io_tree to unlock a range it may be too late, leading to an
5299 * use-after-free issue.
5301 spin_lock(&io_tree->lock);
5302 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5303 struct extent_state *state;
5304 struct extent_state *cached_state = NULL;
5307 unsigned state_flags;
5309 node = rb_first(&io_tree->state);
5310 state = rb_entry(node, struct extent_state, rb_node);
5311 start = state->start;
5313 state_flags = state->state;
5314 spin_unlock(&io_tree->lock);
5316 lock_extent_bits(io_tree, start, end, &cached_state);
5319 * If still has DELALLOC flag, the extent didn't reach disk,
5320 * and its reserved space won't be freed by delayed_ref.
5321 * So we need to free its reserved space here.
5322 * (Refer to comment in btrfs_invalidatepage, case 2)
5324 * Note, end is the bytenr of last byte, so we need + 1 here.
5326 if (state_flags & EXTENT_DELALLOC)
5327 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5330 clear_extent_bit(io_tree, start, end,
5331 EXTENT_LOCKED | EXTENT_DELALLOC |
5332 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5336 spin_lock(&io_tree->lock);
5338 spin_unlock(&io_tree->lock);
5341 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5342 struct btrfs_block_rsv *rsv)
5344 struct btrfs_fs_info *fs_info = root->fs_info;
5345 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5346 struct btrfs_trans_handle *trans;
5347 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5351 * Eviction should be taking place at some place safe because of our
5352 * delayed iputs. However the normal flushing code will run delayed
5353 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5355 * We reserve the delayed_refs_extra here again because we can't use
5356 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5357 * above. We reserve our extra bit here because we generate a ton of
5358 * delayed refs activity by truncating.
5360 * If we cannot make our reservation we'll attempt to steal from the
5361 * global reserve, because we really want to be able to free up space.
5363 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5364 BTRFS_RESERVE_FLUSH_EVICT);
5367 * Try to steal from the global reserve if there is space for
5370 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5371 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5373 "could not allocate space for delete; will truncate on mount");
5374 return ERR_PTR(-ENOSPC);
5376 delayed_refs_extra = 0;
5379 trans = btrfs_join_transaction(root);
5383 if (delayed_refs_extra) {
5384 trans->block_rsv = &fs_info->trans_block_rsv;
5385 trans->bytes_reserved = delayed_refs_extra;
5386 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5387 delayed_refs_extra, 1);
5392 void btrfs_evict_inode(struct inode *inode)
5394 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5395 struct btrfs_trans_handle *trans;
5396 struct btrfs_root *root = BTRFS_I(inode)->root;
5397 struct btrfs_block_rsv *rsv;
5400 trace_btrfs_inode_evict(inode);
5407 evict_inode_truncate_pages(inode);
5409 if (inode->i_nlink &&
5410 ((btrfs_root_refs(&root->root_item) != 0 &&
5411 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5412 btrfs_is_free_space_inode(BTRFS_I(inode))))
5415 if (is_bad_inode(inode))
5418 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5420 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5423 if (inode->i_nlink > 0) {
5424 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5425 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5429 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5433 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5436 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5439 btrfs_i_size_write(BTRFS_I(inode), 0);
5442 trans = evict_refill_and_join(root, rsv);
5446 trans->block_rsv = rsv;
5448 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
5450 trans->block_rsv = &fs_info->trans_block_rsv;
5451 btrfs_end_transaction(trans);
5452 btrfs_btree_balance_dirty(fs_info);
5453 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5460 * Errors here aren't a big deal, it just means we leave orphan items in
5461 * the tree. They will be cleaned up on the next mount. If the inode
5462 * number gets reused, cleanup deletes the orphan item without doing
5463 * anything, and unlink reuses the existing orphan item.
5465 * If it turns out that we are dropping too many of these, we might want
5466 * to add a mechanism for retrying these after a commit.
5468 trans = evict_refill_and_join(root, rsv);
5469 if (!IS_ERR(trans)) {
5470 trans->block_rsv = rsv;
5471 btrfs_orphan_del(trans, BTRFS_I(inode));
5472 trans->block_rsv = &fs_info->trans_block_rsv;
5473 btrfs_end_transaction(trans);
5477 btrfs_free_block_rsv(fs_info, rsv);
5480 * If we didn't successfully delete, the orphan item will still be in
5481 * the tree and we'll retry on the next mount. Again, we might also want
5482 * to retry these periodically in the future.
5484 btrfs_remove_delayed_node(BTRFS_I(inode));
5489 * Return the key found in the dir entry in the location pointer, fill @type
5490 * with BTRFS_FT_*, and return 0.
5492 * If no dir entries were found, returns -ENOENT.
5493 * If found a corrupted location in dir entry, returns -EUCLEAN.
5495 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5496 struct btrfs_key *location, u8 *type)
5498 const char *name = dentry->d_name.name;
5499 int namelen = dentry->d_name.len;
5500 struct btrfs_dir_item *di;
5501 struct btrfs_path *path;
5502 struct btrfs_root *root = BTRFS_I(dir)->root;
5505 path = btrfs_alloc_path();
5509 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5511 if (IS_ERR_OR_NULL(di)) {
5512 ret = di ? PTR_ERR(di) : -ENOENT;
5516 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5517 if (location->type != BTRFS_INODE_ITEM_KEY &&
5518 location->type != BTRFS_ROOT_ITEM_KEY) {
5520 btrfs_warn(root->fs_info,
5521 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5522 __func__, name, btrfs_ino(BTRFS_I(dir)),
5523 location->objectid, location->type, location->offset);
5526 *type = btrfs_dir_type(path->nodes[0], di);
5528 btrfs_free_path(path);
5533 * when we hit a tree root in a directory, the btrfs part of the inode
5534 * needs to be changed to reflect the root directory of the tree root. This
5535 * is kind of like crossing a mount point.
5537 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5539 struct dentry *dentry,
5540 struct btrfs_key *location,
5541 struct btrfs_root **sub_root)
5543 struct btrfs_path *path;
5544 struct btrfs_root *new_root;
5545 struct btrfs_root_ref *ref;
5546 struct extent_buffer *leaf;
5547 struct btrfs_key key;
5551 path = btrfs_alloc_path();
5558 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5559 key.type = BTRFS_ROOT_REF_KEY;
5560 key.offset = location->objectid;
5562 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5569 leaf = path->nodes[0];
5570 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5571 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5572 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5575 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5576 (unsigned long)(ref + 1),
5577 dentry->d_name.len);
5581 btrfs_release_path(path);
5583 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5584 if (IS_ERR(new_root)) {
5585 err = PTR_ERR(new_root);
5589 *sub_root = new_root;
5590 location->objectid = btrfs_root_dirid(&new_root->root_item);
5591 location->type = BTRFS_INODE_ITEM_KEY;
5592 location->offset = 0;
5595 btrfs_free_path(path);
5599 static void inode_tree_add(struct inode *inode)
5601 struct btrfs_root *root = BTRFS_I(inode)->root;
5602 struct btrfs_inode *entry;
5604 struct rb_node *parent;
5605 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5606 u64 ino = btrfs_ino(BTRFS_I(inode));
5608 if (inode_unhashed(inode))
5611 spin_lock(&root->inode_lock);
5612 p = &root->inode_tree.rb_node;
5615 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5617 if (ino < btrfs_ino(entry))
5618 p = &parent->rb_left;
5619 else if (ino > btrfs_ino(entry))
5620 p = &parent->rb_right;
5622 WARN_ON(!(entry->vfs_inode.i_state &
5623 (I_WILL_FREE | I_FREEING)));
5624 rb_replace_node(parent, new, &root->inode_tree);
5625 RB_CLEAR_NODE(parent);
5626 spin_unlock(&root->inode_lock);
5630 rb_link_node(new, parent, p);
5631 rb_insert_color(new, &root->inode_tree);
5632 spin_unlock(&root->inode_lock);
5635 static void inode_tree_del(struct btrfs_inode *inode)
5637 struct btrfs_root *root = inode->root;
5640 spin_lock(&root->inode_lock);
5641 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5642 rb_erase(&inode->rb_node, &root->inode_tree);
5643 RB_CLEAR_NODE(&inode->rb_node);
5644 empty = RB_EMPTY_ROOT(&root->inode_tree);
5646 spin_unlock(&root->inode_lock);
5648 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5649 spin_lock(&root->inode_lock);
5650 empty = RB_EMPTY_ROOT(&root->inode_tree);
5651 spin_unlock(&root->inode_lock);
5653 btrfs_add_dead_root(root);
5658 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5660 struct btrfs_iget_args *args = p;
5662 inode->i_ino = args->ino;
5663 BTRFS_I(inode)->location.objectid = args->ino;
5664 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5665 BTRFS_I(inode)->location.offset = 0;
5666 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5667 BUG_ON(args->root && !BTRFS_I(inode)->root);
5671 static int btrfs_find_actor(struct inode *inode, void *opaque)
5673 struct btrfs_iget_args *args = opaque;
5675 return args->ino == BTRFS_I(inode)->location.objectid &&
5676 args->root == BTRFS_I(inode)->root;
5679 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5680 struct btrfs_root *root)
5682 struct inode *inode;
5683 struct btrfs_iget_args args;
5684 unsigned long hashval = btrfs_inode_hash(ino, root);
5689 inode = iget5_locked(s, hashval, btrfs_find_actor,
5690 btrfs_init_locked_inode,
5696 * Get an inode object given its inode number and corresponding root.
5697 * Path can be preallocated to prevent recursing back to iget through
5698 * allocator. NULL is also valid but may require an additional allocation
5701 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5702 struct btrfs_root *root, struct btrfs_path *path)
5704 struct inode *inode;
5706 inode = btrfs_iget_locked(s, ino, root);
5708 return ERR_PTR(-ENOMEM);
5710 if (inode->i_state & I_NEW) {
5713 ret = btrfs_read_locked_inode(inode, path);
5715 inode_tree_add(inode);
5716 unlock_new_inode(inode);
5720 * ret > 0 can come from btrfs_search_slot called by
5721 * btrfs_read_locked_inode, this means the inode item
5726 inode = ERR_PTR(ret);
5733 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5735 return btrfs_iget_path(s, ino, root, NULL);
5738 static struct inode *new_simple_dir(struct super_block *s,
5739 struct btrfs_key *key,
5740 struct btrfs_root *root)
5742 struct inode *inode = new_inode(s);
5745 return ERR_PTR(-ENOMEM);
5747 BTRFS_I(inode)->root = btrfs_grab_root(root);
5748 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5749 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5751 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5753 * We only need lookup, the rest is read-only and there's no inode
5754 * associated with the dentry
5756 inode->i_op = &simple_dir_inode_operations;
5757 inode->i_opflags &= ~IOP_XATTR;
5758 inode->i_fop = &simple_dir_operations;
5759 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5760 inode->i_mtime = current_time(inode);
5761 inode->i_atime = inode->i_mtime;
5762 inode->i_ctime = inode->i_mtime;
5763 BTRFS_I(inode)->i_otime = inode->i_mtime;
5768 static inline u8 btrfs_inode_type(struct inode *inode)
5771 * Compile-time asserts that generic FT_* types still match
5774 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5775 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5776 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5777 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5778 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5779 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5780 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5781 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5783 return fs_umode_to_ftype(inode->i_mode);
5786 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5788 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5789 struct inode *inode;
5790 struct btrfs_root *root = BTRFS_I(dir)->root;
5791 struct btrfs_root *sub_root = root;
5792 struct btrfs_key location;
5796 if (dentry->d_name.len > BTRFS_NAME_LEN)
5797 return ERR_PTR(-ENAMETOOLONG);
5799 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5801 return ERR_PTR(ret);
5803 if (location.type == BTRFS_INODE_ITEM_KEY) {
5804 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5808 /* Do extra check against inode mode with di_type */
5809 if (btrfs_inode_type(inode) != di_type) {
5811 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5812 inode->i_mode, btrfs_inode_type(inode),
5815 return ERR_PTR(-EUCLEAN);
5820 ret = fixup_tree_root_location(fs_info, dir, dentry,
5821 &location, &sub_root);
5824 inode = ERR_PTR(ret);
5826 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5828 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5830 if (root != sub_root)
5831 btrfs_put_root(sub_root);
5833 if (!IS_ERR(inode) && root != sub_root) {
5834 down_read(&fs_info->cleanup_work_sem);
5835 if (!sb_rdonly(inode->i_sb))
5836 ret = btrfs_orphan_cleanup(sub_root);
5837 up_read(&fs_info->cleanup_work_sem);
5840 inode = ERR_PTR(ret);
5847 static int btrfs_dentry_delete(const struct dentry *dentry)
5849 struct btrfs_root *root;
5850 struct inode *inode = d_inode(dentry);
5852 if (!inode && !IS_ROOT(dentry))
5853 inode = d_inode(dentry->d_parent);
5856 root = BTRFS_I(inode)->root;
5857 if (btrfs_root_refs(&root->root_item) == 0)
5860 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5866 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5869 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5871 if (inode == ERR_PTR(-ENOENT))
5873 return d_splice_alias(inode, dentry);
5877 * All this infrastructure exists because dir_emit can fault, and we are holding
5878 * the tree lock when doing readdir. For now just allocate a buffer and copy
5879 * our information into that, and then dir_emit from the buffer. This is
5880 * similar to what NFS does, only we don't keep the buffer around in pagecache
5881 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5882 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5885 static int btrfs_opendir(struct inode *inode, struct file *file)
5887 struct btrfs_file_private *private;
5889 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5892 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5893 if (!private->filldir_buf) {
5897 file->private_data = private;
5908 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5911 struct dir_entry *entry = addr;
5912 char *name = (char *)(entry + 1);
5914 ctx->pos = get_unaligned(&entry->offset);
5915 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5916 get_unaligned(&entry->ino),
5917 get_unaligned(&entry->type)))
5919 addr += sizeof(struct dir_entry) +
5920 get_unaligned(&entry->name_len);
5926 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5928 struct inode *inode = file_inode(file);
5929 struct btrfs_root *root = BTRFS_I(inode)->root;
5930 struct btrfs_file_private *private = file->private_data;
5931 struct btrfs_dir_item *di;
5932 struct btrfs_key key;
5933 struct btrfs_key found_key;
5934 struct btrfs_path *path;
5936 struct list_head ins_list;
5937 struct list_head del_list;
5939 struct extent_buffer *leaf;
5946 struct btrfs_key location;
5948 if (!dir_emit_dots(file, ctx))
5951 path = btrfs_alloc_path();
5955 addr = private->filldir_buf;
5956 path->reada = READA_FORWARD;
5958 INIT_LIST_HEAD(&ins_list);
5959 INIT_LIST_HEAD(&del_list);
5960 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5963 key.type = BTRFS_DIR_INDEX_KEY;
5964 key.offset = ctx->pos;
5965 key.objectid = btrfs_ino(BTRFS_I(inode));
5967 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5972 struct dir_entry *entry;
5974 leaf = path->nodes[0];
5975 slot = path->slots[0];
5976 if (slot >= btrfs_header_nritems(leaf)) {
5977 ret = btrfs_next_leaf(root, path);
5985 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5987 if (found_key.objectid != key.objectid)
5989 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5991 if (found_key.offset < ctx->pos)
5993 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5995 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5996 name_len = btrfs_dir_name_len(leaf, di);
5997 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5999 btrfs_release_path(path);
6000 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6003 addr = private->filldir_buf;
6010 put_unaligned(name_len, &entry->name_len);
6011 name_ptr = (char *)(entry + 1);
6012 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6014 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6016 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6017 put_unaligned(location.objectid, &entry->ino);
6018 put_unaligned(found_key.offset, &entry->offset);
6020 addr += sizeof(struct dir_entry) + name_len;
6021 total_len += sizeof(struct dir_entry) + name_len;
6025 btrfs_release_path(path);
6027 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6031 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6036 * Stop new entries from being returned after we return the last
6039 * New directory entries are assigned a strictly increasing
6040 * offset. This means that new entries created during readdir
6041 * are *guaranteed* to be seen in the future by that readdir.
6042 * This has broken buggy programs which operate on names as
6043 * they're returned by readdir. Until we re-use freed offsets
6044 * we have this hack to stop new entries from being returned
6045 * under the assumption that they'll never reach this huge
6048 * This is being careful not to overflow 32bit loff_t unless the
6049 * last entry requires it because doing so has broken 32bit apps
6052 if (ctx->pos >= INT_MAX)
6053 ctx->pos = LLONG_MAX;
6060 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6061 btrfs_free_path(path);
6066 * This is somewhat expensive, updating the tree every time the
6067 * inode changes. But, it is most likely to find the inode in cache.
6068 * FIXME, needs more benchmarking...there are no reasons other than performance
6069 * to keep or drop this code.
6071 static int btrfs_dirty_inode(struct inode *inode)
6073 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6074 struct btrfs_root *root = BTRFS_I(inode)->root;
6075 struct btrfs_trans_handle *trans;
6078 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6081 trans = btrfs_join_transaction(root);
6083 return PTR_ERR(trans);
6085 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6086 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6087 /* whoops, lets try again with the full transaction */
6088 btrfs_end_transaction(trans);
6089 trans = btrfs_start_transaction(root, 1);
6091 return PTR_ERR(trans);
6093 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6095 btrfs_end_transaction(trans);
6096 if (BTRFS_I(inode)->delayed_node)
6097 btrfs_balance_delayed_items(fs_info);
6103 * This is a copy of file_update_time. We need this so we can return error on
6104 * ENOSPC for updating the inode in the case of file write and mmap writes.
6106 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6109 struct btrfs_root *root = BTRFS_I(inode)->root;
6110 bool dirty = flags & ~S_VERSION;
6112 if (btrfs_root_readonly(root))
6115 if (flags & S_VERSION)
6116 dirty |= inode_maybe_inc_iversion(inode, dirty);
6117 if (flags & S_CTIME)
6118 inode->i_ctime = *now;
6119 if (flags & S_MTIME)
6120 inode->i_mtime = *now;
6121 if (flags & S_ATIME)
6122 inode->i_atime = *now;
6123 return dirty ? btrfs_dirty_inode(inode) : 0;
6127 * find the highest existing sequence number in a directory
6128 * and then set the in-memory index_cnt variable to reflect
6129 * free sequence numbers
6131 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6133 struct btrfs_root *root = inode->root;
6134 struct btrfs_key key, found_key;
6135 struct btrfs_path *path;
6136 struct extent_buffer *leaf;
6139 key.objectid = btrfs_ino(inode);
6140 key.type = BTRFS_DIR_INDEX_KEY;
6141 key.offset = (u64)-1;
6143 path = btrfs_alloc_path();
6147 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6150 /* FIXME: we should be able to handle this */
6156 * MAGIC NUMBER EXPLANATION:
6157 * since we search a directory based on f_pos we have to start at 2
6158 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6159 * else has to start at 2
6161 if (path->slots[0] == 0) {
6162 inode->index_cnt = 2;
6168 leaf = path->nodes[0];
6169 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6171 if (found_key.objectid != btrfs_ino(inode) ||
6172 found_key.type != BTRFS_DIR_INDEX_KEY) {
6173 inode->index_cnt = 2;
6177 inode->index_cnt = found_key.offset + 1;
6179 btrfs_free_path(path);
6184 * helper to find a free sequence number in a given directory. This current
6185 * code is very simple, later versions will do smarter things in the btree
6187 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6191 if (dir->index_cnt == (u64)-1) {
6192 ret = btrfs_inode_delayed_dir_index_count(dir);
6194 ret = btrfs_set_inode_index_count(dir);
6200 *index = dir->index_cnt;
6206 static int btrfs_insert_inode_locked(struct inode *inode)
6208 struct btrfs_iget_args args;
6210 args.ino = BTRFS_I(inode)->location.objectid;
6211 args.root = BTRFS_I(inode)->root;
6213 return insert_inode_locked4(inode,
6214 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6215 btrfs_find_actor, &args);
6219 * Inherit flags from the parent inode.
6221 * Currently only the compression flags and the cow flags are inherited.
6223 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6230 flags = BTRFS_I(dir)->flags;
6232 if (flags & BTRFS_INODE_NOCOMPRESS) {
6233 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6234 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6235 } else if (flags & BTRFS_INODE_COMPRESS) {
6236 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6237 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6240 if (flags & BTRFS_INODE_NODATACOW) {
6241 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6242 if (S_ISREG(inode->i_mode))
6243 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6246 btrfs_sync_inode_flags_to_i_flags(inode);
6249 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6250 struct btrfs_root *root,
6252 const char *name, int name_len,
6253 u64 ref_objectid, u64 objectid,
6254 umode_t mode, u64 *index)
6256 struct btrfs_fs_info *fs_info = root->fs_info;
6257 struct inode *inode;
6258 struct btrfs_inode_item *inode_item;
6259 struct btrfs_key *location;
6260 struct btrfs_path *path;
6261 struct btrfs_inode_ref *ref;
6262 struct btrfs_key key[2];
6264 int nitems = name ? 2 : 1;
6266 unsigned int nofs_flag;
6269 path = btrfs_alloc_path();
6271 return ERR_PTR(-ENOMEM);
6273 nofs_flag = memalloc_nofs_save();
6274 inode = new_inode(fs_info->sb);
6275 memalloc_nofs_restore(nofs_flag);
6277 btrfs_free_path(path);
6278 return ERR_PTR(-ENOMEM);
6282 * O_TMPFILE, set link count to 0, so that after this point,
6283 * we fill in an inode item with the correct link count.
6286 set_nlink(inode, 0);
6289 * we have to initialize this early, so we can reclaim the inode
6290 * number if we fail afterwards in this function.
6292 inode->i_ino = objectid;
6295 trace_btrfs_inode_request(dir);
6297 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6299 btrfs_free_path(path);
6301 return ERR_PTR(ret);
6307 * index_cnt is ignored for everything but a dir,
6308 * btrfs_set_inode_index_count has an explanation for the magic
6311 BTRFS_I(inode)->index_cnt = 2;
6312 BTRFS_I(inode)->dir_index = *index;
6313 BTRFS_I(inode)->root = btrfs_grab_root(root);
6314 BTRFS_I(inode)->generation = trans->transid;
6315 inode->i_generation = BTRFS_I(inode)->generation;
6318 * We could have gotten an inode number from somebody who was fsynced
6319 * and then removed in this same transaction, so let's just set full
6320 * sync since it will be a full sync anyway and this will blow away the
6321 * old info in the log.
6323 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6325 key[0].objectid = objectid;
6326 key[0].type = BTRFS_INODE_ITEM_KEY;
6329 sizes[0] = sizeof(struct btrfs_inode_item);
6333 * Start new inodes with an inode_ref. This is slightly more
6334 * efficient for small numbers of hard links since they will
6335 * be packed into one item. Extended refs will kick in if we
6336 * add more hard links than can fit in the ref item.
6338 key[1].objectid = objectid;
6339 key[1].type = BTRFS_INODE_REF_KEY;
6340 key[1].offset = ref_objectid;
6342 sizes[1] = name_len + sizeof(*ref);
6345 location = &BTRFS_I(inode)->location;
6346 location->objectid = objectid;
6347 location->offset = 0;
6348 location->type = BTRFS_INODE_ITEM_KEY;
6350 ret = btrfs_insert_inode_locked(inode);
6356 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6360 inode_init_owner(&init_user_ns, inode, dir, mode);
6361 inode_set_bytes(inode, 0);
6363 inode->i_mtime = current_time(inode);
6364 inode->i_atime = inode->i_mtime;
6365 inode->i_ctime = inode->i_mtime;
6366 BTRFS_I(inode)->i_otime = inode->i_mtime;
6368 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6369 struct btrfs_inode_item);
6370 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6371 sizeof(*inode_item));
6372 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6375 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6376 struct btrfs_inode_ref);
6377 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6378 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6379 ptr = (unsigned long)(ref + 1);
6380 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6383 btrfs_mark_buffer_dirty(path->nodes[0]);
6384 btrfs_free_path(path);
6386 btrfs_inherit_iflags(inode, dir);
6388 if (S_ISREG(mode)) {
6389 if (btrfs_test_opt(fs_info, NODATASUM))
6390 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6391 if (btrfs_test_opt(fs_info, NODATACOW))
6392 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6393 BTRFS_INODE_NODATASUM;
6396 inode_tree_add(inode);
6398 trace_btrfs_inode_new(inode);
6399 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6401 btrfs_update_root_times(trans, root);
6403 ret = btrfs_inode_inherit_props(trans, inode, dir);
6406 "error inheriting props for ino %llu (root %llu): %d",
6407 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6412 discard_new_inode(inode);
6415 BTRFS_I(dir)->index_cnt--;
6416 btrfs_free_path(path);
6417 return ERR_PTR(ret);
6421 * utility function to add 'inode' into 'parent_inode' with
6422 * a give name and a given sequence number.
6423 * if 'add_backref' is true, also insert a backref from the
6424 * inode to the parent directory.
6426 int btrfs_add_link(struct btrfs_trans_handle *trans,
6427 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6428 const char *name, int name_len, int add_backref, u64 index)
6431 struct btrfs_key key;
6432 struct btrfs_root *root = parent_inode->root;
6433 u64 ino = btrfs_ino(inode);
6434 u64 parent_ino = btrfs_ino(parent_inode);
6436 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6437 memcpy(&key, &inode->root->root_key, sizeof(key));
6440 key.type = BTRFS_INODE_ITEM_KEY;
6444 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6445 ret = btrfs_add_root_ref(trans, key.objectid,
6446 root->root_key.objectid, parent_ino,
6447 index, name, name_len);
6448 } else if (add_backref) {
6449 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6453 /* Nothing to clean up yet */
6457 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6458 btrfs_inode_type(&inode->vfs_inode), index);
6459 if (ret == -EEXIST || ret == -EOVERFLOW)
6462 btrfs_abort_transaction(trans, ret);
6466 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6468 inode_inc_iversion(&parent_inode->vfs_inode);
6470 * If we are replaying a log tree, we do not want to update the mtime
6471 * and ctime of the parent directory with the current time, since the
6472 * log replay procedure is responsible for setting them to their correct
6473 * values (the ones it had when the fsync was done).
6475 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6476 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6478 parent_inode->vfs_inode.i_mtime = now;
6479 parent_inode->vfs_inode.i_ctime = now;
6481 ret = btrfs_update_inode(trans, root, parent_inode);
6483 btrfs_abort_transaction(trans, ret);
6487 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6490 err = btrfs_del_root_ref(trans, key.objectid,
6491 root->root_key.objectid, parent_ino,
6492 &local_index, name, name_len);
6494 btrfs_abort_transaction(trans, err);
6495 } else if (add_backref) {
6499 err = btrfs_del_inode_ref(trans, root, name, name_len,
6500 ino, parent_ino, &local_index);
6502 btrfs_abort_transaction(trans, err);
6505 /* Return the original error code */
6509 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6510 struct btrfs_inode *dir, struct dentry *dentry,
6511 struct btrfs_inode *inode, int backref, u64 index)
6513 int err = btrfs_add_link(trans, dir, inode,
6514 dentry->d_name.name, dentry->d_name.len,
6521 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6522 struct dentry *dentry, umode_t mode, dev_t rdev)
6524 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6525 struct btrfs_trans_handle *trans;
6526 struct btrfs_root *root = BTRFS_I(dir)->root;
6527 struct inode *inode = NULL;
6533 * 2 for inode item and ref
6535 * 1 for xattr if selinux is on
6537 trans = btrfs_start_transaction(root, 5);
6539 return PTR_ERR(trans);
6541 err = btrfs_get_free_objectid(root, &objectid);
6545 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6546 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6548 if (IS_ERR(inode)) {
6549 err = PTR_ERR(inode);
6555 * If the active LSM wants to access the inode during
6556 * d_instantiate it needs these. Smack checks to see
6557 * if the filesystem supports xattrs by looking at the
6560 inode->i_op = &btrfs_special_inode_operations;
6561 init_special_inode(inode, inode->i_mode, rdev);
6563 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6567 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6572 btrfs_update_inode(trans, root, BTRFS_I(inode));
6573 d_instantiate_new(dentry, inode);
6576 btrfs_end_transaction(trans);
6577 btrfs_btree_balance_dirty(fs_info);
6579 inode_dec_link_count(inode);
6580 discard_new_inode(inode);
6585 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6586 struct dentry *dentry, umode_t mode, bool excl)
6588 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6589 struct btrfs_trans_handle *trans;
6590 struct btrfs_root *root = BTRFS_I(dir)->root;
6591 struct inode *inode = NULL;
6597 * 2 for inode item and ref
6599 * 1 for xattr if selinux is on
6601 trans = btrfs_start_transaction(root, 5);
6603 return PTR_ERR(trans);
6605 err = btrfs_get_free_objectid(root, &objectid);
6609 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6610 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6612 if (IS_ERR(inode)) {
6613 err = PTR_ERR(inode);
6618 * If the active LSM wants to access the inode during
6619 * d_instantiate it needs these. Smack checks to see
6620 * if the filesystem supports xattrs by looking at the
6623 inode->i_fop = &btrfs_file_operations;
6624 inode->i_op = &btrfs_file_inode_operations;
6625 inode->i_mapping->a_ops = &btrfs_aops;
6627 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6631 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6635 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6640 d_instantiate_new(dentry, inode);
6643 btrfs_end_transaction(trans);
6645 inode_dec_link_count(inode);
6646 discard_new_inode(inode);
6648 btrfs_btree_balance_dirty(fs_info);
6652 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6653 struct dentry *dentry)
6655 struct btrfs_trans_handle *trans = NULL;
6656 struct btrfs_root *root = BTRFS_I(dir)->root;
6657 struct inode *inode = d_inode(old_dentry);
6658 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6663 /* do not allow sys_link's with other subvols of the same device */
6664 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6667 if (inode->i_nlink >= BTRFS_LINK_MAX)
6670 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6675 * 2 items for inode and inode ref
6676 * 2 items for dir items
6677 * 1 item for parent inode
6678 * 1 item for orphan item deletion if O_TMPFILE
6680 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6681 if (IS_ERR(trans)) {
6682 err = PTR_ERR(trans);
6687 /* There are several dir indexes for this inode, clear the cache. */
6688 BTRFS_I(inode)->dir_index = 0ULL;
6690 inode_inc_iversion(inode);
6691 inode->i_ctime = current_time(inode);
6693 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6695 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6701 struct dentry *parent = dentry->d_parent;
6703 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6706 if (inode->i_nlink == 1) {
6708 * If new hard link count is 1, it's a file created
6709 * with open(2) O_TMPFILE flag.
6711 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6715 d_instantiate(dentry, inode);
6716 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6721 btrfs_end_transaction(trans);
6723 inode_dec_link_count(inode);
6726 btrfs_btree_balance_dirty(fs_info);
6730 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6731 struct dentry *dentry, umode_t mode)
6733 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6734 struct inode *inode = NULL;
6735 struct btrfs_trans_handle *trans;
6736 struct btrfs_root *root = BTRFS_I(dir)->root;
6742 * 2 items for inode and ref
6743 * 2 items for dir items
6744 * 1 for xattr if selinux is on
6746 trans = btrfs_start_transaction(root, 5);
6748 return PTR_ERR(trans);
6750 err = btrfs_get_free_objectid(root, &objectid);
6754 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6755 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6756 S_IFDIR | mode, &index);
6757 if (IS_ERR(inode)) {
6758 err = PTR_ERR(inode);
6763 /* these must be set before we unlock the inode */
6764 inode->i_op = &btrfs_dir_inode_operations;
6765 inode->i_fop = &btrfs_dir_file_operations;
6767 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6771 btrfs_i_size_write(BTRFS_I(inode), 0);
6772 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6776 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6777 dentry->d_name.name,
6778 dentry->d_name.len, 0, index);
6782 d_instantiate_new(dentry, inode);
6785 btrfs_end_transaction(trans);
6787 inode_dec_link_count(inode);
6788 discard_new_inode(inode);
6790 btrfs_btree_balance_dirty(fs_info);
6794 static noinline int uncompress_inline(struct btrfs_path *path,
6796 size_t pg_offset, u64 extent_offset,
6797 struct btrfs_file_extent_item *item)
6800 struct extent_buffer *leaf = path->nodes[0];
6803 unsigned long inline_size;
6807 WARN_ON(pg_offset != 0);
6808 compress_type = btrfs_file_extent_compression(leaf, item);
6809 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6810 inline_size = btrfs_file_extent_inline_item_len(leaf,
6811 btrfs_item_nr(path->slots[0]));
6812 tmp = kmalloc(inline_size, GFP_NOFS);
6815 ptr = btrfs_file_extent_inline_start(item);
6817 read_extent_buffer(leaf, tmp, ptr, inline_size);
6819 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6820 ret = btrfs_decompress(compress_type, tmp, page,
6821 extent_offset, inline_size, max_size);
6824 * decompression code contains a memset to fill in any space between the end
6825 * of the uncompressed data and the end of max_size in case the decompressed
6826 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6827 * the end of an inline extent and the beginning of the next block, so we
6828 * cover that region here.
6831 if (max_size + pg_offset < PAGE_SIZE) {
6832 char *map = kmap(page);
6833 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6841 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6842 * @inode: file to search in
6843 * @page: page to read extent data into if the extent is inline
6844 * @pg_offset: offset into @page to copy to
6845 * @start: file offset
6846 * @len: length of range starting at @start
6848 * This returns the first &struct extent_map which overlaps with the given
6849 * range, reading it from the B-tree and caching it if necessary. Note that
6850 * there may be more extents which overlap the given range after the returned
6853 * If @page is not NULL and the extent is inline, this also reads the extent
6854 * data directly into the page and marks the extent up to date in the io_tree.
6856 * Return: ERR_PTR on error, non-NULL extent_map on success.
6858 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6859 struct page *page, size_t pg_offset,
6862 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6864 u64 extent_start = 0;
6866 u64 objectid = btrfs_ino(inode);
6867 int extent_type = -1;
6868 struct btrfs_path *path = NULL;
6869 struct btrfs_root *root = inode->root;
6870 struct btrfs_file_extent_item *item;
6871 struct extent_buffer *leaf;
6872 struct btrfs_key found_key;
6873 struct extent_map *em = NULL;
6874 struct extent_map_tree *em_tree = &inode->extent_tree;
6875 struct extent_io_tree *io_tree = &inode->io_tree;
6877 read_lock(&em_tree->lock);
6878 em = lookup_extent_mapping(em_tree, start, len);
6879 read_unlock(&em_tree->lock);
6882 if (em->start > start || em->start + em->len <= start)
6883 free_extent_map(em);
6884 else if (em->block_start == EXTENT_MAP_INLINE && page)
6885 free_extent_map(em);
6889 em = alloc_extent_map();
6894 em->start = EXTENT_MAP_HOLE;
6895 em->orig_start = EXTENT_MAP_HOLE;
6897 em->block_len = (u64)-1;
6899 path = btrfs_alloc_path();
6905 /* Chances are we'll be called again, so go ahead and do readahead */
6906 path->reada = READA_FORWARD;
6909 * The same explanation in load_free_space_cache applies here as well,
6910 * we only read when we're loading the free space cache, and at that
6911 * point the commit_root has everything we need.
6913 if (btrfs_is_free_space_inode(inode)) {
6914 path->search_commit_root = 1;
6915 path->skip_locking = 1;
6918 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6921 } else if (ret > 0) {
6922 if (path->slots[0] == 0)
6928 leaf = path->nodes[0];
6929 item = btrfs_item_ptr(leaf, path->slots[0],
6930 struct btrfs_file_extent_item);
6931 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6932 if (found_key.objectid != objectid ||
6933 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6935 * If we backup past the first extent we want to move forward
6936 * and see if there is an extent in front of us, otherwise we'll
6937 * say there is a hole for our whole search range which can
6944 extent_type = btrfs_file_extent_type(leaf, item);
6945 extent_start = found_key.offset;
6946 extent_end = btrfs_file_extent_end(path);
6947 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6948 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6949 /* Only regular file could have regular/prealloc extent */
6950 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6953 "regular/prealloc extent found for non-regular inode %llu",
6957 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6959 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6960 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6965 if (start >= extent_end) {
6967 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6968 ret = btrfs_next_leaf(root, path);
6974 leaf = path->nodes[0];
6976 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6977 if (found_key.objectid != objectid ||
6978 found_key.type != BTRFS_EXTENT_DATA_KEY)
6980 if (start + len <= found_key.offset)
6982 if (start > found_key.offset)
6985 /* New extent overlaps with existing one */
6987 em->orig_start = start;
6988 em->len = found_key.offset - start;
6989 em->block_start = EXTENT_MAP_HOLE;
6993 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6995 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6996 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6998 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7002 size_t extent_offset;
7008 size = btrfs_file_extent_ram_bytes(leaf, item);
7009 extent_offset = page_offset(page) + pg_offset - extent_start;
7010 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7011 size - extent_offset);
7012 em->start = extent_start + extent_offset;
7013 em->len = ALIGN(copy_size, fs_info->sectorsize);
7014 em->orig_block_len = em->len;
7015 em->orig_start = em->start;
7016 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7018 if (!PageUptodate(page)) {
7019 if (btrfs_file_extent_compression(leaf, item) !=
7020 BTRFS_COMPRESS_NONE) {
7021 ret = uncompress_inline(path, page, pg_offset,
7022 extent_offset, item);
7026 map = kmap_local_page(page);
7027 read_extent_buffer(leaf, map + pg_offset, ptr,
7029 if (pg_offset + copy_size < PAGE_SIZE) {
7030 memset(map + pg_offset + copy_size, 0,
7031 PAGE_SIZE - pg_offset -
7036 flush_dcache_page(page);
7038 set_extent_uptodate(io_tree, em->start,
7039 extent_map_end(em) - 1, NULL, GFP_NOFS);
7044 em->orig_start = start;
7046 em->block_start = EXTENT_MAP_HOLE;
7049 btrfs_release_path(path);
7050 if (em->start > start || extent_map_end(em) <= start) {
7052 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7053 em->start, em->len, start, len);
7058 write_lock(&em_tree->lock);
7059 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7060 write_unlock(&em_tree->lock);
7062 btrfs_free_path(path);
7064 trace_btrfs_get_extent(root, inode, em);
7067 free_extent_map(em);
7068 return ERR_PTR(ret);
7073 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7076 struct extent_map *em;
7077 struct extent_map *hole_em = NULL;
7078 u64 delalloc_start = start;
7084 em = btrfs_get_extent(inode, NULL, 0, start, len);
7088 * If our em maps to:
7090 * - a pre-alloc extent,
7091 * there might actually be delalloc bytes behind it.
7093 if (em->block_start != EXTENT_MAP_HOLE &&
7094 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7099 /* check to see if we've wrapped (len == -1 or similar) */
7108 /* ok, we didn't find anything, lets look for delalloc */
7109 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7110 end, len, EXTENT_DELALLOC, 1);
7111 delalloc_end = delalloc_start + delalloc_len;
7112 if (delalloc_end < delalloc_start)
7113 delalloc_end = (u64)-1;
7116 * We didn't find anything useful, return the original results from
7119 if (delalloc_start > end || delalloc_end <= start) {
7126 * Adjust the delalloc_start to make sure it doesn't go backwards from
7127 * the start they passed in
7129 delalloc_start = max(start, delalloc_start);
7130 delalloc_len = delalloc_end - delalloc_start;
7132 if (delalloc_len > 0) {
7135 const u64 hole_end = extent_map_end(hole_em);
7137 em = alloc_extent_map();
7145 * When btrfs_get_extent can't find anything it returns one
7148 * Make sure what it found really fits our range, and adjust to
7149 * make sure it is based on the start from the caller
7151 if (hole_end <= start || hole_em->start > end) {
7152 free_extent_map(hole_em);
7155 hole_start = max(hole_em->start, start);
7156 hole_len = hole_end - hole_start;
7159 if (hole_em && delalloc_start > hole_start) {
7161 * Our hole starts before our delalloc, so we have to
7162 * return just the parts of the hole that go until the
7165 em->len = min(hole_len, delalloc_start - hole_start);
7166 em->start = hole_start;
7167 em->orig_start = hole_start;
7169 * Don't adjust block start at all, it is fixed at
7172 em->block_start = hole_em->block_start;
7173 em->block_len = hole_len;
7174 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7175 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7178 * Hole is out of passed range or it starts after
7181 em->start = delalloc_start;
7182 em->len = delalloc_len;
7183 em->orig_start = delalloc_start;
7184 em->block_start = EXTENT_MAP_DELALLOC;
7185 em->block_len = delalloc_len;
7192 free_extent_map(hole_em);
7194 free_extent_map(em);
7195 return ERR_PTR(err);
7200 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7203 const u64 orig_start,
7204 const u64 block_start,
7205 const u64 block_len,
7206 const u64 orig_block_len,
7207 const u64 ram_bytes,
7210 struct extent_map *em = NULL;
7213 if (type != BTRFS_ORDERED_NOCOW) {
7214 em = create_io_em(inode, start, len, orig_start, block_start,
7215 block_len, orig_block_len, ram_bytes,
7216 BTRFS_COMPRESS_NONE, /* compress_type */
7221 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7225 free_extent_map(em);
7226 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7235 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7238 struct btrfs_root *root = inode->root;
7239 struct btrfs_fs_info *fs_info = root->fs_info;
7240 struct extent_map *em;
7241 struct btrfs_key ins;
7245 alloc_hint = get_extent_allocation_hint(inode, start, len);
7246 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7247 0, alloc_hint, &ins, 1, 1);
7249 return ERR_PTR(ret);
7251 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7252 ins.objectid, ins.offset, ins.offset,
7253 ins.offset, BTRFS_ORDERED_REGULAR);
7254 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7256 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7262 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7264 struct btrfs_block_group *block_group;
7265 bool readonly = false;
7267 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7268 if (!block_group || block_group->ro)
7271 btrfs_put_block_group(block_group);
7276 * Check if we can do nocow write into the range [@offset, @offset + @len)
7278 * @offset: File offset
7279 * @len: The length to write, will be updated to the nocow writeable
7281 * @orig_start: (optional) Return the original file offset of the file extent
7282 * @orig_len: (optional) Return the original on-disk length of the file extent
7283 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7284 * @strict: if true, omit optimizations that might force us into unnecessary
7285 * cow. e.g., don't trust generation number.
7288 * >0 and update @len if we can do nocow write
7289 * 0 if we can't do nocow write
7290 * <0 if error happened
7292 * NOTE: This only checks the file extents, caller is responsible to wait for
7293 * any ordered extents.
7295 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7296 u64 *orig_start, u64 *orig_block_len,
7297 u64 *ram_bytes, bool strict)
7299 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7300 struct btrfs_path *path;
7302 struct extent_buffer *leaf;
7303 struct btrfs_root *root = BTRFS_I(inode)->root;
7304 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7305 struct btrfs_file_extent_item *fi;
7306 struct btrfs_key key;
7313 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7315 path = btrfs_alloc_path();
7319 ret = btrfs_lookup_file_extent(NULL, root, path,
7320 btrfs_ino(BTRFS_I(inode)), offset, 0);
7324 slot = path->slots[0];
7327 /* can't find the item, must cow */
7334 leaf = path->nodes[0];
7335 btrfs_item_key_to_cpu(leaf, &key, slot);
7336 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7337 key.type != BTRFS_EXTENT_DATA_KEY) {
7338 /* not our file or wrong item type, must cow */
7342 if (key.offset > offset) {
7343 /* Wrong offset, must cow */
7347 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7348 found_type = btrfs_file_extent_type(leaf, fi);
7349 if (found_type != BTRFS_FILE_EXTENT_REG &&
7350 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7351 /* not a regular extent, must cow */
7355 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7358 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7359 if (extent_end <= offset)
7362 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7363 if (disk_bytenr == 0)
7366 if (btrfs_file_extent_compression(leaf, fi) ||
7367 btrfs_file_extent_encryption(leaf, fi) ||
7368 btrfs_file_extent_other_encoding(leaf, fi))
7372 * Do the same check as in btrfs_cross_ref_exist but without the
7373 * unnecessary search.
7376 (btrfs_file_extent_generation(leaf, fi) <=
7377 btrfs_root_last_snapshot(&root->root_item)))
7380 backref_offset = btrfs_file_extent_offset(leaf, fi);
7383 *orig_start = key.offset - backref_offset;
7384 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7385 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7388 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7391 num_bytes = min(offset + *len, extent_end) - offset;
7392 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7395 range_end = round_up(offset + num_bytes,
7396 root->fs_info->sectorsize) - 1;
7397 ret = test_range_bit(io_tree, offset, range_end,
7398 EXTENT_DELALLOC, 0, NULL);
7405 btrfs_release_path(path);
7408 * look for other files referencing this extent, if we
7409 * find any we must cow
7412 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7413 key.offset - backref_offset, disk_bytenr,
7421 * adjust disk_bytenr and num_bytes to cover just the bytes
7422 * in this extent we are about to write. If there
7423 * are any csums in that range we have to cow in order
7424 * to keep the csums correct
7426 disk_bytenr += backref_offset;
7427 disk_bytenr += offset - key.offset;
7428 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7431 * all of the above have passed, it is safe to overwrite this extent
7437 btrfs_free_path(path);
7441 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7442 struct extent_state **cached_state, bool writing)
7444 struct btrfs_ordered_extent *ordered;
7448 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7451 * We're concerned with the entire range that we're going to be
7452 * doing DIO to, so we need to make sure there's no ordered
7453 * extents in this range.
7455 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7456 lockend - lockstart + 1);
7459 * We need to make sure there are no buffered pages in this
7460 * range either, we could have raced between the invalidate in
7461 * generic_file_direct_write and locking the extent. The
7462 * invalidate needs to happen so that reads after a write do not
7466 (!writing || !filemap_range_has_page(inode->i_mapping,
7467 lockstart, lockend)))
7470 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7475 * If we are doing a DIO read and the ordered extent we
7476 * found is for a buffered write, we can not wait for it
7477 * to complete and retry, because if we do so we can
7478 * deadlock with concurrent buffered writes on page
7479 * locks. This happens only if our DIO read covers more
7480 * than one extent map, if at this point has already
7481 * created an ordered extent for a previous extent map
7482 * and locked its range in the inode's io tree, and a
7483 * concurrent write against that previous extent map's
7484 * range and this range started (we unlock the ranges
7485 * in the io tree only when the bios complete and
7486 * buffered writes always lock pages before attempting
7487 * to lock range in the io tree).
7490 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7491 btrfs_start_ordered_extent(ordered, 1);
7494 btrfs_put_ordered_extent(ordered);
7497 * We could trigger writeback for this range (and wait
7498 * for it to complete) and then invalidate the pages for
7499 * this range (through invalidate_inode_pages2_range()),
7500 * but that can lead us to a deadlock with a concurrent
7501 * call to readahead (a buffered read or a defrag call
7502 * triggered a readahead) on a page lock due to an
7503 * ordered dio extent we created before but did not have
7504 * yet a corresponding bio submitted (whence it can not
7505 * complete), which makes readahead wait for that
7506 * ordered extent to complete while holding a lock on
7521 /* The callers of this must take lock_extent() */
7522 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7523 u64 len, u64 orig_start, u64 block_start,
7524 u64 block_len, u64 orig_block_len,
7525 u64 ram_bytes, int compress_type,
7528 struct extent_map_tree *em_tree;
7529 struct extent_map *em;
7532 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7533 type == BTRFS_ORDERED_COMPRESSED ||
7534 type == BTRFS_ORDERED_NOCOW ||
7535 type == BTRFS_ORDERED_REGULAR);
7537 em_tree = &inode->extent_tree;
7538 em = alloc_extent_map();
7540 return ERR_PTR(-ENOMEM);
7543 em->orig_start = orig_start;
7545 em->block_len = block_len;
7546 em->block_start = block_start;
7547 em->orig_block_len = orig_block_len;
7548 em->ram_bytes = ram_bytes;
7549 em->generation = -1;
7550 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7551 if (type == BTRFS_ORDERED_PREALLOC) {
7552 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7553 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7554 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7555 em->compress_type = compress_type;
7559 btrfs_drop_extent_cache(inode, em->start,
7560 em->start + em->len - 1, 0);
7561 write_lock(&em_tree->lock);
7562 ret = add_extent_mapping(em_tree, em, 1);
7563 write_unlock(&em_tree->lock);
7565 * The caller has taken lock_extent(), who could race with us
7568 } while (ret == -EEXIST);
7571 free_extent_map(em);
7572 return ERR_PTR(ret);
7575 /* em got 2 refs now, callers needs to do free_extent_map once. */
7580 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7581 struct inode *inode,
7582 struct btrfs_dio_data *dio_data,
7585 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7586 struct extent_map *em = *map;
7590 * We don't allocate a new extent in the following cases
7592 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7594 * 2) The extent is marked as PREALLOC. We're good to go here and can
7595 * just use the extent.
7598 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7599 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7600 em->block_start != EXTENT_MAP_HOLE)) {
7602 u64 block_start, orig_start, orig_block_len, ram_bytes;
7604 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7605 type = BTRFS_ORDERED_PREALLOC;
7607 type = BTRFS_ORDERED_NOCOW;
7608 len = min(len, em->len - (start - em->start));
7609 block_start = em->block_start + (start - em->start);
7611 if (can_nocow_extent(inode, start, &len, &orig_start,
7612 &orig_block_len, &ram_bytes, false) == 1 &&
7613 btrfs_inc_nocow_writers(fs_info, block_start)) {
7614 struct extent_map *em2;
7616 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7617 orig_start, block_start,
7618 len, orig_block_len,
7620 btrfs_dec_nocow_writers(fs_info, block_start);
7621 if (type == BTRFS_ORDERED_PREALLOC) {
7622 free_extent_map(em);
7626 if (em2 && IS_ERR(em2)) {
7631 * For inode marked NODATACOW or extent marked PREALLOC,
7632 * use the existing or preallocated extent, so does not
7633 * need to adjust btrfs_space_info's bytes_may_use.
7635 btrfs_free_reserved_data_space_noquota(fs_info, len);
7640 /* this will cow the extent */
7641 free_extent_map(em);
7642 *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7648 len = min(len, em->len - (start - em->start));
7652 * Need to update the i_size under the extent lock so buffered
7653 * readers will get the updated i_size when we unlock.
7655 if (start + len > i_size_read(inode))
7656 i_size_write(inode, start + len);
7658 dio_data->reserve -= len;
7663 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7664 loff_t length, unsigned int flags, struct iomap *iomap,
7665 struct iomap *srcmap)
7667 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7668 struct extent_map *em;
7669 struct extent_state *cached_state = NULL;
7670 struct btrfs_dio_data *dio_data = NULL;
7671 u64 lockstart, lockend;
7672 const bool write = !!(flags & IOMAP_WRITE);
7675 bool unlock_extents = false;
7678 len = min_t(u64, len, fs_info->sectorsize);
7681 lockend = start + len - 1;
7684 * The generic stuff only does filemap_write_and_wait_range, which
7685 * isn't enough if we've written compressed pages to this area, so we
7686 * need to flush the dirty pages again to make absolutely sure that any
7687 * outstanding dirty pages are on disk.
7689 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7690 &BTRFS_I(inode)->runtime_flags)) {
7691 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7692 start + length - 1);
7697 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7701 dio_data->length = length;
7703 dio_data->reserve = round_up(length, fs_info->sectorsize);
7704 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7705 &dio_data->data_reserved,
7706 start, dio_data->reserve);
7708 extent_changeset_free(dio_data->data_reserved);
7713 iomap->private = dio_data;
7717 * If this errors out it's because we couldn't invalidate pagecache for
7718 * this range and we need to fallback to buffered.
7720 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7725 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7732 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7733 * io. INLINE is special, and we could probably kludge it in here, but
7734 * it's still buffered so for safety lets just fall back to the generic
7737 * For COMPRESSED we _have_ to read the entire extent in so we can
7738 * decompress it, so there will be buffering required no matter what we
7739 * do, so go ahead and fallback to buffered.
7741 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7742 * to buffered IO. Don't blame me, this is the price we pay for using
7745 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7746 em->block_start == EXTENT_MAP_INLINE) {
7747 free_extent_map(em);
7752 len = min(len, em->len - (start - em->start));
7754 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7758 unlock_extents = true;
7759 /* Recalc len in case the new em is smaller than requested */
7760 len = min(len, em->len - (start - em->start));
7763 * We need to unlock only the end area that we aren't using.
7764 * The rest is going to be unlocked by the endio routine.
7766 lockstart = start + len;
7767 if (lockstart < lockend)
7768 unlock_extents = true;
7772 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7773 lockstart, lockend, &cached_state);
7775 free_extent_state(cached_state);
7778 * Translate extent map information to iomap.
7779 * We trim the extents (and move the addr) even though iomap code does
7780 * that, since we have locked only the parts we are performing I/O in.
7782 if ((em->block_start == EXTENT_MAP_HOLE) ||
7783 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7784 iomap->addr = IOMAP_NULL_ADDR;
7785 iomap->type = IOMAP_HOLE;
7787 iomap->addr = em->block_start + (start - em->start);
7788 iomap->type = IOMAP_MAPPED;
7790 iomap->offset = start;
7791 iomap->bdev = fs_info->fs_devices->latest_bdev;
7792 iomap->length = len;
7794 if (write && btrfs_use_zone_append(BTRFS_I(inode), em))
7795 iomap->flags |= IOMAP_F_ZONE_APPEND;
7797 free_extent_map(em);
7802 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7806 btrfs_delalloc_release_space(BTRFS_I(inode),
7807 dio_data->data_reserved, start,
7808 dio_data->reserve, true);
7809 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7810 extent_changeset_free(dio_data->data_reserved);
7816 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7817 ssize_t written, unsigned int flags, struct iomap *iomap)
7820 struct btrfs_dio_data *dio_data = iomap->private;
7821 size_t submitted = dio_data->submitted;
7822 const bool write = !!(flags & IOMAP_WRITE);
7824 if (!write && (iomap->type == IOMAP_HOLE)) {
7825 /* If reading from a hole, unlock and return */
7826 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7830 if (submitted < length) {
7832 length -= submitted;
7834 __endio_write_update_ordered(BTRFS_I(inode), pos,
7837 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7843 if (dio_data->reserve)
7844 btrfs_delalloc_release_space(BTRFS_I(inode),
7845 dio_data->data_reserved, pos,
7846 dio_data->reserve, true);
7847 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7848 extent_changeset_free(dio_data->data_reserved);
7852 iomap->private = NULL;
7857 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7860 * This implies a barrier so that stores to dio_bio->bi_status before
7861 * this and loads of dio_bio->bi_status after this are fully ordered.
7863 if (!refcount_dec_and_test(&dip->refs))
7866 if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
7867 __endio_write_update_ordered(BTRFS_I(dip->inode),
7868 dip->logical_offset,
7870 !dip->dio_bio->bi_status);
7872 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7873 dip->logical_offset,
7874 dip->logical_offset + dip->bytes - 1);
7877 bio_endio(dip->dio_bio);
7881 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7883 unsigned long bio_flags)
7885 struct btrfs_dio_private *dip = bio->bi_private;
7886 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7889 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7891 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7895 refcount_inc(&dip->refs);
7896 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7898 refcount_dec(&dip->refs);
7902 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7903 struct btrfs_io_bio *io_bio,
7904 const bool uptodate)
7906 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7907 const u32 sectorsize = fs_info->sectorsize;
7908 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7909 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7910 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7911 struct bio_vec bvec;
7912 struct bvec_iter iter;
7913 u64 start = io_bio->logical;
7915 blk_status_t err = BLK_STS_OK;
7917 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7918 unsigned int i, nr_sectors, pgoff;
7920 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7921 pgoff = bvec.bv_offset;
7922 for (i = 0; i < nr_sectors; i++) {
7923 ASSERT(pgoff < PAGE_SIZE);
7925 (!csum || !check_data_csum(inode, io_bio,
7926 bio_offset, bvec.bv_page,
7928 clean_io_failure(fs_info, failure_tree, io_tree,
7929 start, bvec.bv_page,
7930 btrfs_ino(BTRFS_I(inode)),
7933 blk_status_t status;
7935 ASSERT((start - io_bio->logical) < UINT_MAX);
7936 status = btrfs_submit_read_repair(inode,
7938 start - io_bio->logical,
7939 bvec.bv_page, pgoff,
7941 start + sectorsize - 1,
7943 submit_dio_repair_bio);
7947 start += sectorsize;
7948 ASSERT(bio_offset + sectorsize > bio_offset);
7949 bio_offset += sectorsize;
7950 pgoff += sectorsize;
7956 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7957 const u64 offset, const u64 bytes,
7958 const bool uptodate)
7960 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7961 struct btrfs_ordered_extent *ordered = NULL;
7962 struct btrfs_workqueue *wq;
7963 u64 ordered_offset = offset;
7964 u64 ordered_bytes = bytes;
7967 if (btrfs_is_free_space_inode(inode))
7968 wq = fs_info->endio_freespace_worker;
7970 wq = fs_info->endio_write_workers;
7972 while (ordered_offset < offset + bytes) {
7973 last_offset = ordered_offset;
7974 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7978 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7980 btrfs_queue_work(wq, &ordered->work);
7983 /* No ordered extent found in the range, exit */
7984 if (ordered_offset == last_offset)
7987 * Our bio might span multiple ordered extents. In this case
7988 * we keep going until we have accounted the whole dio.
7990 if (ordered_offset < offset + bytes) {
7991 ordered_bytes = offset + bytes - ordered_offset;
7997 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7999 u64 dio_file_offset)
8001 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, 1);
8004 static void btrfs_end_dio_bio(struct bio *bio)
8006 struct btrfs_dio_private *dip = bio->bi_private;
8007 blk_status_t err = bio->bi_status;
8010 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8011 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8012 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8013 bio->bi_opf, bio->bi_iter.bi_sector,
8014 bio->bi_iter.bi_size, err);
8016 if (bio_op(bio) == REQ_OP_READ) {
8017 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
8022 dip->dio_bio->bi_status = err;
8024 btrfs_record_physical_zoned(dip->inode, dip->logical_offset, bio);
8027 btrfs_dio_private_put(dip);
8030 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8031 struct inode *inode, u64 file_offset, int async_submit)
8033 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8034 struct btrfs_dio_private *dip = bio->bi_private;
8035 bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
8038 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8040 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8043 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8048 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8051 if (write && async_submit) {
8052 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
8053 btrfs_submit_bio_start_direct_io);
8057 * If we aren't doing async submit, calculate the csum of the
8060 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
8066 csum_offset = file_offset - dip->logical_offset;
8067 csum_offset >>= fs_info->sectorsize_bits;
8068 csum_offset *= fs_info->csum_size;
8069 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
8072 ret = btrfs_map_bio(fs_info, bio, 0);
8078 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
8079 * or ordered extents whether or not we submit any bios.
8081 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
8082 struct inode *inode,
8085 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8086 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8088 struct btrfs_dio_private *dip;
8090 dip_size = sizeof(*dip);
8091 if (!write && csum) {
8092 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8095 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
8096 dip_size += fs_info->csum_size * nblocks;
8099 dip = kzalloc(dip_size, GFP_NOFS);
8104 dip->logical_offset = file_offset;
8105 dip->bytes = dio_bio->bi_iter.bi_size;
8106 dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
8107 dip->dio_bio = dio_bio;
8108 refcount_set(&dip->refs, 1);
8112 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
8113 struct bio *dio_bio, loff_t file_offset)
8115 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8116 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8117 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8118 BTRFS_BLOCK_GROUP_RAID56_MASK);
8119 struct btrfs_dio_private *dip;
8122 int async_submit = 0;
8124 int clone_offset = 0;
8128 blk_status_t status;
8129 struct btrfs_io_geometry geom;
8130 struct btrfs_dio_data *dio_data = iomap->private;
8131 struct extent_map *em = NULL;
8133 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
8136 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8137 file_offset + dio_bio->bi_iter.bi_size - 1);
8139 dio_bio->bi_status = BLK_STS_RESOURCE;
8141 return BLK_QC_T_NONE;
8146 * Load the csums up front to reduce csum tree searches and
8147 * contention when submitting bios.
8149 * If we have csums disabled this will do nothing.
8151 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8152 if (status != BLK_STS_OK)
8156 start_sector = dio_bio->bi_iter.bi_sector;
8157 submit_len = dio_bio->bi_iter.bi_size;
8160 logical = start_sector << 9;
8161 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8163 status = errno_to_blk_status(PTR_ERR(em));
8167 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8168 logical, submit_len, &geom);
8170 status = errno_to_blk_status(ret);
8173 ASSERT(geom.len <= INT_MAX);
8175 clone_len = min_t(int, submit_len, geom.len);
8178 * This will never fail as it's passing GPF_NOFS and
8179 * the allocation is backed by btrfs_bioset.
8181 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8182 bio->bi_private = dip;
8183 bio->bi_end_io = btrfs_end_dio_bio;
8184 btrfs_io_bio(bio)->logical = file_offset;
8186 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8187 status = extract_ordered_extent(BTRFS_I(inode), bio,
8195 ASSERT(submit_len >= clone_len);
8196 submit_len -= clone_len;
8199 * Increase the count before we submit the bio so we know
8200 * the end IO handler won't happen before we increase the
8201 * count. Otherwise, the dip might get freed before we're
8202 * done setting it up.
8204 * We transfer the initial reference to the last bio, so we
8205 * don't need to increment the reference count for the last one.
8207 if (submit_len > 0) {
8208 refcount_inc(&dip->refs);
8210 * If we are submitting more than one bio, submit them
8211 * all asynchronously. The exception is RAID 5 or 6, as
8212 * asynchronous checksums make it difficult to collect
8213 * full stripe writes.
8219 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8224 refcount_dec(&dip->refs);
8228 dio_data->submitted += clone_len;
8229 clone_offset += clone_len;
8230 start_sector += clone_len >> 9;
8231 file_offset += clone_len;
8233 free_extent_map(em);
8234 } while (submit_len > 0);
8235 return BLK_QC_T_NONE;
8238 free_extent_map(em);
8240 dip->dio_bio->bi_status = status;
8241 btrfs_dio_private_put(dip);
8243 return BLK_QC_T_NONE;
8246 const struct iomap_ops btrfs_dio_iomap_ops = {
8247 .iomap_begin = btrfs_dio_iomap_begin,
8248 .iomap_end = btrfs_dio_iomap_end,
8251 const struct iomap_dio_ops btrfs_dio_ops = {
8252 .submit_io = btrfs_submit_direct,
8255 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8260 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8264 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8267 int btrfs_readpage(struct file *file, struct page *page)
8269 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8270 u64 start = page_offset(page);
8271 u64 end = start + PAGE_SIZE - 1;
8272 unsigned long bio_flags = 0;
8273 struct bio *bio = NULL;
8276 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8278 ret = btrfs_do_readpage(page, NULL, &bio, &bio_flags, 0, NULL);
8280 ret = submit_one_bio(bio, 0, bio_flags);
8284 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8286 struct inode *inode = page->mapping->host;
8289 if (current->flags & PF_MEMALLOC) {
8290 redirty_page_for_writepage(wbc, page);
8296 * If we are under memory pressure we will call this directly from the
8297 * VM, we need to make sure we have the inode referenced for the ordered
8298 * extent. If not just return like we didn't do anything.
8300 if (!igrab(inode)) {
8301 redirty_page_for_writepage(wbc, page);
8302 return AOP_WRITEPAGE_ACTIVATE;
8304 ret = extent_write_full_page(page, wbc);
8305 btrfs_add_delayed_iput(inode);
8309 static int btrfs_writepages(struct address_space *mapping,
8310 struct writeback_control *wbc)
8312 return extent_writepages(mapping, wbc);
8315 static void btrfs_readahead(struct readahead_control *rac)
8317 extent_readahead(rac);
8320 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8322 int ret = try_release_extent_mapping(page, gfp_flags);
8324 clear_page_extent_mapped(page);
8328 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8330 if (PageWriteback(page) || PageDirty(page))
8332 return __btrfs_releasepage(page, gfp_flags);
8335 #ifdef CONFIG_MIGRATION
8336 static int btrfs_migratepage(struct address_space *mapping,
8337 struct page *newpage, struct page *page,
8338 enum migrate_mode mode)
8342 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8343 if (ret != MIGRATEPAGE_SUCCESS)
8346 if (page_has_private(page))
8347 attach_page_private(newpage, detach_page_private(page));
8349 if (PagePrivate2(page)) {
8350 ClearPagePrivate2(page);
8351 SetPagePrivate2(newpage);
8354 if (mode != MIGRATE_SYNC_NO_COPY)
8355 migrate_page_copy(newpage, page);
8357 migrate_page_states(newpage, page);
8358 return MIGRATEPAGE_SUCCESS;
8362 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8363 unsigned int length)
8365 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8366 struct extent_io_tree *tree = &inode->io_tree;
8367 struct btrfs_ordered_extent *ordered;
8368 struct extent_state *cached_state = NULL;
8369 u64 page_start = page_offset(page);
8370 u64 page_end = page_start + PAGE_SIZE - 1;
8373 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8374 bool found_ordered = false;
8375 bool completed_ordered = false;
8378 * we have the page locked, so new writeback can't start,
8379 * and the dirty bit won't be cleared while we are here.
8381 * Wait for IO on this page so that we can safely clear
8382 * the PagePrivate2 bit and do ordered accounting
8384 wait_on_page_writeback(page);
8387 btrfs_releasepage(page, GFP_NOFS);
8391 if (!inode_evicting)
8392 lock_extent_bits(tree, page_start, page_end, &cached_state);
8396 ordered = btrfs_lookup_ordered_range(inode, start, page_end - start + 1);
8398 found_ordered = true;
8400 ordered->file_offset + ordered->num_bytes - 1);
8402 * IO on this page will never be started, so we need to account
8403 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8404 * here, must leave that up for the ordered extent completion.
8406 if (!inode_evicting)
8407 clear_extent_bit(tree, start, end,
8409 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8410 EXTENT_DEFRAG, 1, 0, &cached_state);
8412 * whoever cleared the private bit is responsible
8413 * for the finish_ordered_io
8415 if (TestClearPagePrivate2(page)) {
8416 spin_lock_irq(&inode->ordered_tree.lock);
8417 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8418 ordered->truncated_len = min(ordered->truncated_len,
8419 start - ordered->file_offset);
8420 spin_unlock_irq(&inode->ordered_tree.lock);
8422 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8424 end - start + 1, 1)) {
8425 btrfs_finish_ordered_io(ordered);
8426 completed_ordered = true;
8429 btrfs_put_ordered_extent(ordered);
8430 if (!inode_evicting) {
8431 cached_state = NULL;
8432 lock_extent_bits(tree, start, end,
8437 if (start < page_end)
8442 * Qgroup reserved space handler
8443 * Page here will be either
8444 * 1) Already written to disk or ordered extent already submitted
8445 * Then its QGROUP_RESERVED bit in io_tree is already cleaned.
8446 * Qgroup will be handled by its qgroup_record then.
8447 * btrfs_qgroup_free_data() call will do nothing here.
8449 * 2) Not written to disk yet
8450 * Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED
8451 * bit of its io_tree, and free the qgroup reserved data space.
8452 * Since the IO will never happen for this page.
8454 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8455 if (!inode_evicting) {
8459 * If there's an ordered extent for this range and we have not
8460 * finished it ourselves, we must leave EXTENT_DELALLOC_NEW set
8461 * in the range for the ordered extent completion. We must also
8462 * not delete the range, otherwise we would lose that bit (and
8463 * any other bits set in the range). Make sure EXTENT_UPTODATE
8464 * is cleared if we don't delete, otherwise it can lead to
8465 * corruptions if the i_size is extented later.
8467 if (found_ordered && !completed_ordered)
8469 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8470 EXTENT_DELALLOC | EXTENT_UPTODATE |
8471 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8472 delete, &cached_state);
8474 __btrfs_releasepage(page, GFP_NOFS);
8477 ClearPageChecked(page);
8478 clear_page_extent_mapped(page);
8482 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8483 * called from a page fault handler when a page is first dirtied. Hence we must
8484 * be careful to check for EOF conditions here. We set the page up correctly
8485 * for a written page which means we get ENOSPC checking when writing into
8486 * holes and correct delalloc and unwritten extent mapping on filesystems that
8487 * support these features.
8489 * We are not allowed to take the i_mutex here so we have to play games to
8490 * protect against truncate races as the page could now be beyond EOF. Because
8491 * truncate_setsize() writes the inode size before removing pages, once we have
8492 * the page lock we can determine safely if the page is beyond EOF. If it is not
8493 * beyond EOF, then the page is guaranteed safe against truncation until we
8496 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8498 struct page *page = vmf->page;
8499 struct inode *inode = file_inode(vmf->vma->vm_file);
8500 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8501 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8502 struct btrfs_ordered_extent *ordered;
8503 struct extent_state *cached_state = NULL;
8504 struct extent_changeset *data_reserved = NULL;
8506 unsigned long zero_start;
8516 reserved_space = PAGE_SIZE;
8518 sb_start_pagefault(inode->i_sb);
8519 page_start = page_offset(page);
8520 page_end = page_start + PAGE_SIZE - 1;
8524 * Reserving delalloc space after obtaining the page lock can lead to
8525 * deadlock. For example, if a dirty page is locked by this function
8526 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8527 * dirty page write out, then the btrfs_writepage() function could
8528 * end up waiting indefinitely to get a lock on the page currently
8529 * being processed by btrfs_page_mkwrite() function.
8531 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8532 page_start, reserved_space);
8534 ret2 = file_update_time(vmf->vma->vm_file);
8538 ret = vmf_error(ret2);
8544 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8546 down_read(&BTRFS_I(inode)->i_mmap_lock);
8548 size = i_size_read(inode);
8550 if ((page->mapping != inode->i_mapping) ||
8551 (page_start >= size)) {
8552 /* page got truncated out from underneath us */
8555 wait_on_page_writeback(page);
8557 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8558 ret2 = set_page_extent_mapped(page);
8560 ret = vmf_error(ret2);
8561 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8566 * we can't set the delalloc bits if there are pending ordered
8567 * extents. Drop our locks and wait for them to finish
8569 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8572 unlock_extent_cached(io_tree, page_start, page_end,
8575 up_read(&BTRFS_I(inode)->i_mmap_lock);
8576 btrfs_start_ordered_extent(ordered, 1);
8577 btrfs_put_ordered_extent(ordered);
8581 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8582 reserved_space = round_up(size - page_start,
8583 fs_info->sectorsize);
8584 if (reserved_space < PAGE_SIZE) {
8585 end = page_start + reserved_space - 1;
8586 btrfs_delalloc_release_space(BTRFS_I(inode),
8587 data_reserved, page_start,
8588 PAGE_SIZE - reserved_space, true);
8593 * page_mkwrite gets called when the page is firstly dirtied after it's
8594 * faulted in, but write(2) could also dirty a page and set delalloc
8595 * bits, thus in this case for space account reason, we still need to
8596 * clear any delalloc bits within this page range since we have to
8597 * reserve data&meta space before lock_page() (see above comments).
8599 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8600 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8601 EXTENT_DEFRAG, 0, 0, &cached_state);
8603 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8606 unlock_extent_cached(io_tree, page_start, page_end,
8608 ret = VM_FAULT_SIGBUS;
8612 /* page is wholly or partially inside EOF */
8613 if (page_start + PAGE_SIZE > size)
8614 zero_start = offset_in_page(size);
8616 zero_start = PAGE_SIZE;
8618 if (zero_start != PAGE_SIZE) {
8620 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8621 flush_dcache_page(page);
8624 ClearPageChecked(page);
8625 set_page_dirty(page);
8626 SetPageUptodate(page);
8628 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8630 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8631 up_read(&BTRFS_I(inode)->i_mmap_lock);
8633 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8634 sb_end_pagefault(inode->i_sb);
8635 extent_changeset_free(data_reserved);
8636 return VM_FAULT_LOCKED;
8640 up_read(&BTRFS_I(inode)->i_mmap_lock);
8642 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8643 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8644 reserved_space, (ret != 0));
8646 sb_end_pagefault(inode->i_sb);
8647 extent_changeset_free(data_reserved);
8651 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8653 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8654 struct btrfs_root *root = BTRFS_I(inode)->root;
8655 struct btrfs_block_rsv *rsv;
8657 struct btrfs_trans_handle *trans;
8658 u64 mask = fs_info->sectorsize - 1;
8659 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8661 if (!skip_writeback) {
8662 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8669 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8670 * things going on here:
8672 * 1) We need to reserve space to update our inode.
8674 * 2) We need to have something to cache all the space that is going to
8675 * be free'd up by the truncate operation, but also have some slack
8676 * space reserved in case it uses space during the truncate (thank you
8677 * very much snapshotting).
8679 * And we need these to be separate. The fact is we can use a lot of
8680 * space doing the truncate, and we have no earthly idea how much space
8681 * we will use, so we need the truncate reservation to be separate so it
8682 * doesn't end up using space reserved for updating the inode. We also
8683 * need to be able to stop the transaction and start a new one, which
8684 * means we need to be able to update the inode several times, and we
8685 * have no idea of knowing how many times that will be, so we can't just
8686 * reserve 1 item for the entirety of the operation, so that has to be
8687 * done separately as well.
8689 * So that leaves us with
8691 * 1) rsv - for the truncate reservation, which we will steal from the
8692 * transaction reservation.
8693 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8694 * updating the inode.
8696 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8699 rsv->size = min_size;
8703 * 1 for the truncate slack space
8704 * 1 for updating the inode.
8706 trans = btrfs_start_transaction(root, 2);
8707 if (IS_ERR(trans)) {
8708 ret = PTR_ERR(trans);
8712 /* Migrate the slack space for the truncate to our reserve */
8713 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8718 * So if we truncate and then write and fsync we normally would just
8719 * write the extents that changed, which is a problem if we need to
8720 * first truncate that entire inode. So set this flag so we write out
8721 * all of the extents in the inode to the sync log so we're completely
8724 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8725 trans->block_rsv = rsv;
8728 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
8730 BTRFS_EXTENT_DATA_KEY);
8731 trans->block_rsv = &fs_info->trans_block_rsv;
8732 if (ret != -ENOSPC && ret != -EAGAIN)
8735 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8739 btrfs_end_transaction(trans);
8740 btrfs_btree_balance_dirty(fs_info);
8742 trans = btrfs_start_transaction(root, 2);
8743 if (IS_ERR(trans)) {
8744 ret = PTR_ERR(trans);
8749 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8750 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8751 rsv, min_size, false);
8752 BUG_ON(ret); /* shouldn't happen */
8753 trans->block_rsv = rsv;
8757 * We can't call btrfs_truncate_block inside a trans handle as we could
8758 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8759 * we've truncated everything except the last little bit, and can do
8760 * btrfs_truncate_block and then update the disk_i_size.
8762 if (ret == NEED_TRUNCATE_BLOCK) {
8763 btrfs_end_transaction(trans);
8764 btrfs_btree_balance_dirty(fs_info);
8766 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8769 trans = btrfs_start_transaction(root, 1);
8770 if (IS_ERR(trans)) {
8771 ret = PTR_ERR(trans);
8774 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8780 trans->block_rsv = &fs_info->trans_block_rsv;
8781 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8785 ret2 = btrfs_end_transaction(trans);
8788 btrfs_btree_balance_dirty(fs_info);
8791 btrfs_free_block_rsv(fs_info, rsv);
8797 * create a new subvolume directory/inode (helper for the ioctl).
8799 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8800 struct btrfs_root *new_root,
8801 struct btrfs_root *parent_root)
8803 struct inode *inode;
8808 err = btrfs_get_free_objectid(new_root, &ino);
8812 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, ino, ino,
8813 S_IFDIR | (~current_umask() & S_IRWXUGO),
8816 return PTR_ERR(inode);
8817 inode->i_op = &btrfs_dir_inode_operations;
8818 inode->i_fop = &btrfs_dir_file_operations;
8820 set_nlink(inode, 1);
8821 btrfs_i_size_write(BTRFS_I(inode), 0);
8822 unlock_new_inode(inode);
8824 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8826 btrfs_err(new_root->fs_info,
8827 "error inheriting subvolume %llu properties: %d",
8828 new_root->root_key.objectid, err);
8830 err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
8836 struct inode *btrfs_alloc_inode(struct super_block *sb)
8838 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8839 struct btrfs_inode *ei;
8840 struct inode *inode;
8842 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8849 ei->last_sub_trans = 0;
8850 ei->logged_trans = 0;
8851 ei->delalloc_bytes = 0;
8852 ei->new_delalloc_bytes = 0;
8853 ei->defrag_bytes = 0;
8854 ei->disk_i_size = 0;
8857 ei->index_cnt = (u64)-1;
8859 ei->last_unlink_trans = 0;
8860 ei->last_reflink_trans = 0;
8861 ei->last_log_commit = 0;
8863 spin_lock_init(&ei->lock);
8864 ei->outstanding_extents = 0;
8865 if (sb->s_magic != BTRFS_TEST_MAGIC)
8866 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8867 BTRFS_BLOCK_RSV_DELALLOC);
8868 ei->runtime_flags = 0;
8869 ei->prop_compress = BTRFS_COMPRESS_NONE;
8870 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8872 ei->delayed_node = NULL;
8874 ei->i_otime.tv_sec = 0;
8875 ei->i_otime.tv_nsec = 0;
8877 inode = &ei->vfs_inode;
8878 extent_map_tree_init(&ei->extent_tree);
8879 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8880 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8881 IO_TREE_INODE_IO_FAILURE, inode);
8882 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8883 IO_TREE_INODE_FILE_EXTENT, inode);
8884 ei->io_tree.track_uptodate = true;
8885 ei->io_failure_tree.track_uptodate = true;
8886 atomic_set(&ei->sync_writers, 0);
8887 mutex_init(&ei->log_mutex);
8888 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8889 INIT_LIST_HEAD(&ei->delalloc_inodes);
8890 INIT_LIST_HEAD(&ei->delayed_iput);
8891 RB_CLEAR_NODE(&ei->rb_node);
8892 init_rwsem(&ei->i_mmap_lock);
8897 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8898 void btrfs_test_destroy_inode(struct inode *inode)
8900 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8901 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8905 void btrfs_free_inode(struct inode *inode)
8907 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8910 void btrfs_destroy_inode(struct inode *vfs_inode)
8912 struct btrfs_ordered_extent *ordered;
8913 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8914 struct btrfs_root *root = inode->root;
8916 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8917 WARN_ON(vfs_inode->i_data.nrpages);
8918 WARN_ON(inode->block_rsv.reserved);
8919 WARN_ON(inode->block_rsv.size);
8920 WARN_ON(inode->outstanding_extents);
8921 WARN_ON(inode->delalloc_bytes);
8922 WARN_ON(inode->new_delalloc_bytes);
8923 WARN_ON(inode->csum_bytes);
8924 WARN_ON(inode->defrag_bytes);
8927 * This can happen where we create an inode, but somebody else also
8928 * created the same inode and we need to destroy the one we already
8935 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8939 btrfs_err(root->fs_info,
8940 "found ordered extent %llu %llu on inode cleanup",
8941 ordered->file_offset, ordered->num_bytes);
8942 btrfs_remove_ordered_extent(inode, ordered);
8943 btrfs_put_ordered_extent(ordered);
8944 btrfs_put_ordered_extent(ordered);
8947 btrfs_qgroup_check_reserved_leak(inode);
8948 inode_tree_del(inode);
8949 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8950 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8951 btrfs_put_root(inode->root);
8954 int btrfs_drop_inode(struct inode *inode)
8956 struct btrfs_root *root = BTRFS_I(inode)->root;
8961 /* the snap/subvol tree is on deleting */
8962 if (btrfs_root_refs(&root->root_item) == 0)
8965 return generic_drop_inode(inode);
8968 static void init_once(void *foo)
8970 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8972 inode_init_once(&ei->vfs_inode);
8975 void __cold btrfs_destroy_cachep(void)
8978 * Make sure all delayed rcu free inodes are flushed before we
8982 kmem_cache_destroy(btrfs_inode_cachep);
8983 kmem_cache_destroy(btrfs_trans_handle_cachep);
8984 kmem_cache_destroy(btrfs_path_cachep);
8985 kmem_cache_destroy(btrfs_free_space_cachep);
8986 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8989 int __init btrfs_init_cachep(void)
8991 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8992 sizeof(struct btrfs_inode), 0,
8993 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8995 if (!btrfs_inode_cachep)
8998 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8999 sizeof(struct btrfs_trans_handle), 0,
9000 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9001 if (!btrfs_trans_handle_cachep)
9004 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9005 sizeof(struct btrfs_path), 0,
9006 SLAB_MEM_SPREAD, NULL);
9007 if (!btrfs_path_cachep)
9010 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9011 sizeof(struct btrfs_free_space), 0,
9012 SLAB_MEM_SPREAD, NULL);
9013 if (!btrfs_free_space_cachep)
9016 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9017 PAGE_SIZE, PAGE_SIZE,
9018 SLAB_MEM_SPREAD, NULL);
9019 if (!btrfs_free_space_bitmap_cachep)
9024 btrfs_destroy_cachep();
9028 static int btrfs_getattr(struct user_namespace *mnt_userns,
9029 const struct path *path, struct kstat *stat,
9030 u32 request_mask, unsigned int flags)
9034 struct inode *inode = d_inode(path->dentry);
9035 u32 blocksize = inode->i_sb->s_blocksize;
9036 u32 bi_flags = BTRFS_I(inode)->flags;
9038 stat->result_mask |= STATX_BTIME;
9039 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9040 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9041 if (bi_flags & BTRFS_INODE_APPEND)
9042 stat->attributes |= STATX_ATTR_APPEND;
9043 if (bi_flags & BTRFS_INODE_COMPRESS)
9044 stat->attributes |= STATX_ATTR_COMPRESSED;
9045 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9046 stat->attributes |= STATX_ATTR_IMMUTABLE;
9047 if (bi_flags & BTRFS_INODE_NODUMP)
9048 stat->attributes |= STATX_ATTR_NODUMP;
9050 stat->attributes_mask |= (STATX_ATTR_APPEND |
9051 STATX_ATTR_COMPRESSED |
9052 STATX_ATTR_IMMUTABLE |
9055 generic_fillattr(&init_user_ns, inode, stat);
9056 stat->dev = BTRFS_I(inode)->root->anon_dev;
9058 spin_lock(&BTRFS_I(inode)->lock);
9059 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9060 inode_bytes = inode_get_bytes(inode);
9061 spin_unlock(&BTRFS_I(inode)->lock);
9062 stat->blocks = (ALIGN(inode_bytes, blocksize) +
9063 ALIGN(delalloc_bytes, blocksize)) >> 9;
9067 static int btrfs_rename_exchange(struct inode *old_dir,
9068 struct dentry *old_dentry,
9069 struct inode *new_dir,
9070 struct dentry *new_dentry)
9072 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9073 struct btrfs_trans_handle *trans;
9074 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9075 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9076 struct inode *new_inode = new_dentry->d_inode;
9077 struct inode *old_inode = old_dentry->d_inode;
9078 struct timespec64 ctime = current_time(old_inode);
9079 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9080 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9085 bool root_log_pinned = false;
9086 bool dest_log_pinned = false;
9088 /* we only allow rename subvolume link between subvolumes */
9089 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9092 /* close the race window with snapshot create/destroy ioctl */
9093 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9094 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9095 down_read(&fs_info->subvol_sem);
9098 * We want to reserve the absolute worst case amount of items. So if
9099 * both inodes are subvols and we need to unlink them then that would
9100 * require 4 item modifications, but if they are both normal inodes it
9101 * would require 5 item modifications, so we'll assume their normal
9102 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9103 * should cover the worst case number of items we'll modify.
9105 trans = btrfs_start_transaction(root, 12);
9106 if (IS_ERR(trans)) {
9107 ret = PTR_ERR(trans);
9112 btrfs_record_root_in_trans(trans, dest);
9115 * We need to find a free sequence number both in the source and
9116 * in the destination directory for the exchange.
9118 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9121 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9125 BTRFS_I(old_inode)->dir_index = 0ULL;
9126 BTRFS_I(new_inode)->dir_index = 0ULL;
9128 /* Reference for the source. */
9129 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9130 /* force full log commit if subvolume involved. */
9131 btrfs_set_log_full_commit(trans);
9133 btrfs_pin_log_trans(root);
9134 root_log_pinned = true;
9135 ret = btrfs_insert_inode_ref(trans, dest,
9136 new_dentry->d_name.name,
9137 new_dentry->d_name.len,
9139 btrfs_ino(BTRFS_I(new_dir)),
9145 /* And now for the dest. */
9146 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9147 /* force full log commit if subvolume involved. */
9148 btrfs_set_log_full_commit(trans);
9150 btrfs_pin_log_trans(dest);
9151 dest_log_pinned = true;
9152 ret = btrfs_insert_inode_ref(trans, root,
9153 old_dentry->d_name.name,
9154 old_dentry->d_name.len,
9156 btrfs_ino(BTRFS_I(old_dir)),
9162 /* Update inode version and ctime/mtime. */
9163 inode_inc_iversion(old_dir);
9164 inode_inc_iversion(new_dir);
9165 inode_inc_iversion(old_inode);
9166 inode_inc_iversion(new_inode);
9167 old_dir->i_ctime = old_dir->i_mtime = ctime;
9168 new_dir->i_ctime = new_dir->i_mtime = ctime;
9169 old_inode->i_ctime = ctime;
9170 new_inode->i_ctime = ctime;
9172 if (old_dentry->d_parent != new_dentry->d_parent) {
9173 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9174 BTRFS_I(old_inode), 1);
9175 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9176 BTRFS_I(new_inode), 1);
9179 /* src is a subvolume */
9180 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9181 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9182 } else { /* src is an inode */
9183 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9184 BTRFS_I(old_dentry->d_inode),
9185 old_dentry->d_name.name,
9186 old_dentry->d_name.len);
9188 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9191 btrfs_abort_transaction(trans, ret);
9195 /* dest is a subvolume */
9196 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9197 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9198 } else { /* dest is an inode */
9199 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9200 BTRFS_I(new_dentry->d_inode),
9201 new_dentry->d_name.name,
9202 new_dentry->d_name.len);
9204 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9207 btrfs_abort_transaction(trans, ret);
9211 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9212 new_dentry->d_name.name,
9213 new_dentry->d_name.len, 0, old_idx);
9215 btrfs_abort_transaction(trans, ret);
9219 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9220 old_dentry->d_name.name,
9221 old_dentry->d_name.len, 0, new_idx);
9223 btrfs_abort_transaction(trans, ret);
9227 if (old_inode->i_nlink == 1)
9228 BTRFS_I(old_inode)->dir_index = old_idx;
9229 if (new_inode->i_nlink == 1)
9230 BTRFS_I(new_inode)->dir_index = new_idx;
9232 if (root_log_pinned) {
9233 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9234 new_dentry->d_parent);
9235 btrfs_end_log_trans(root);
9236 root_log_pinned = false;
9238 if (dest_log_pinned) {
9239 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9240 old_dentry->d_parent);
9241 btrfs_end_log_trans(dest);
9242 dest_log_pinned = false;
9246 * If we have pinned a log and an error happened, we unpin tasks
9247 * trying to sync the log and force them to fallback to a transaction
9248 * commit if the log currently contains any of the inodes involved in
9249 * this rename operation (to ensure we do not persist a log with an
9250 * inconsistent state for any of these inodes or leading to any
9251 * inconsistencies when replayed). If the transaction was aborted, the
9252 * abortion reason is propagated to userspace when attempting to commit
9253 * the transaction. If the log does not contain any of these inodes, we
9254 * allow the tasks to sync it.
9256 if (ret && (root_log_pinned || dest_log_pinned)) {
9257 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9258 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9259 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9261 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9262 btrfs_set_log_full_commit(trans);
9264 if (root_log_pinned) {
9265 btrfs_end_log_trans(root);
9266 root_log_pinned = false;
9268 if (dest_log_pinned) {
9269 btrfs_end_log_trans(dest);
9270 dest_log_pinned = false;
9273 ret2 = btrfs_end_transaction(trans);
9274 ret = ret ? ret : ret2;
9276 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9277 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9278 up_read(&fs_info->subvol_sem);
9283 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9284 struct btrfs_root *root,
9286 struct dentry *dentry)
9289 struct inode *inode;
9293 ret = btrfs_get_free_objectid(root, &objectid);
9297 inode = btrfs_new_inode(trans, root, dir,
9298 dentry->d_name.name,
9300 btrfs_ino(BTRFS_I(dir)),
9302 S_IFCHR | WHITEOUT_MODE,
9305 if (IS_ERR(inode)) {
9306 ret = PTR_ERR(inode);
9310 inode->i_op = &btrfs_special_inode_operations;
9311 init_special_inode(inode, inode->i_mode,
9314 ret = btrfs_init_inode_security(trans, inode, dir,
9319 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9320 BTRFS_I(inode), 0, index);
9324 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9326 unlock_new_inode(inode);
9328 inode_dec_link_count(inode);
9334 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9335 struct inode *new_dir, struct dentry *new_dentry,
9338 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9339 struct btrfs_trans_handle *trans;
9340 unsigned int trans_num_items;
9341 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9342 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9343 struct inode *new_inode = d_inode(new_dentry);
9344 struct inode *old_inode = d_inode(old_dentry);
9348 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9349 bool log_pinned = false;
9351 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9354 /* we only allow rename subvolume link between subvolumes */
9355 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9358 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9359 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9362 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9363 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9367 /* check for collisions, even if the name isn't there */
9368 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9369 new_dentry->d_name.name,
9370 new_dentry->d_name.len);
9373 if (ret == -EEXIST) {
9375 * eexist without a new_inode */
9376 if (WARN_ON(!new_inode)) {
9380 /* maybe -EOVERFLOW */
9387 * we're using rename to replace one file with another. Start IO on it
9388 * now so we don't add too much work to the end of the transaction
9390 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9391 filemap_flush(old_inode->i_mapping);
9393 /* close the racy window with snapshot create/destroy ioctl */
9394 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9395 down_read(&fs_info->subvol_sem);
9397 * We want to reserve the absolute worst case amount of items. So if
9398 * both inodes are subvols and we need to unlink them then that would
9399 * require 4 item modifications, but if they are both normal inodes it
9400 * would require 5 item modifications, so we'll assume they are normal
9401 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9402 * should cover the worst case number of items we'll modify.
9403 * If our rename has the whiteout flag, we need more 5 units for the
9404 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9405 * when selinux is enabled).
9407 trans_num_items = 11;
9408 if (flags & RENAME_WHITEOUT)
9409 trans_num_items += 5;
9410 trans = btrfs_start_transaction(root, trans_num_items);
9411 if (IS_ERR(trans)) {
9412 ret = PTR_ERR(trans);
9417 btrfs_record_root_in_trans(trans, dest);
9419 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9423 BTRFS_I(old_inode)->dir_index = 0ULL;
9424 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9425 /* force full log commit if subvolume involved. */
9426 btrfs_set_log_full_commit(trans);
9428 btrfs_pin_log_trans(root);
9430 ret = btrfs_insert_inode_ref(trans, dest,
9431 new_dentry->d_name.name,
9432 new_dentry->d_name.len,
9434 btrfs_ino(BTRFS_I(new_dir)), index);
9439 inode_inc_iversion(old_dir);
9440 inode_inc_iversion(new_dir);
9441 inode_inc_iversion(old_inode);
9442 old_dir->i_ctime = old_dir->i_mtime =
9443 new_dir->i_ctime = new_dir->i_mtime =
9444 old_inode->i_ctime = current_time(old_dir);
9446 if (old_dentry->d_parent != new_dentry->d_parent)
9447 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9448 BTRFS_I(old_inode), 1);
9450 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9451 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9453 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9454 BTRFS_I(d_inode(old_dentry)),
9455 old_dentry->d_name.name,
9456 old_dentry->d_name.len);
9458 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9461 btrfs_abort_transaction(trans, ret);
9466 inode_inc_iversion(new_inode);
9467 new_inode->i_ctime = current_time(new_inode);
9468 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9469 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9470 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9471 BUG_ON(new_inode->i_nlink == 0);
9473 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9474 BTRFS_I(d_inode(new_dentry)),
9475 new_dentry->d_name.name,
9476 new_dentry->d_name.len);
9478 if (!ret && new_inode->i_nlink == 0)
9479 ret = btrfs_orphan_add(trans,
9480 BTRFS_I(d_inode(new_dentry)));
9482 btrfs_abort_transaction(trans, ret);
9487 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9488 new_dentry->d_name.name,
9489 new_dentry->d_name.len, 0, index);
9491 btrfs_abort_transaction(trans, ret);
9495 if (old_inode->i_nlink == 1)
9496 BTRFS_I(old_inode)->dir_index = index;
9499 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9500 new_dentry->d_parent);
9501 btrfs_end_log_trans(root);
9505 if (flags & RENAME_WHITEOUT) {
9506 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9510 btrfs_abort_transaction(trans, ret);
9516 * If we have pinned the log and an error happened, we unpin tasks
9517 * trying to sync the log and force them to fallback to a transaction
9518 * commit if the log currently contains any of the inodes involved in
9519 * this rename operation (to ensure we do not persist a log with an
9520 * inconsistent state for any of these inodes or leading to any
9521 * inconsistencies when replayed). If the transaction was aborted, the
9522 * abortion reason is propagated to userspace when attempting to commit
9523 * the transaction. If the log does not contain any of these inodes, we
9524 * allow the tasks to sync it.
9526 if (ret && log_pinned) {
9527 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9528 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9529 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9531 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9532 btrfs_set_log_full_commit(trans);
9534 btrfs_end_log_trans(root);
9537 ret2 = btrfs_end_transaction(trans);
9538 ret = ret ? ret : ret2;
9540 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9541 up_read(&fs_info->subvol_sem);
9546 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9547 struct dentry *old_dentry, struct inode *new_dir,
9548 struct dentry *new_dentry, unsigned int flags)
9550 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9553 if (flags & RENAME_EXCHANGE)
9554 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9557 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9560 struct btrfs_delalloc_work {
9561 struct inode *inode;
9562 struct completion completion;
9563 struct list_head list;
9564 struct btrfs_work work;
9567 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9569 struct btrfs_delalloc_work *delalloc_work;
9570 struct inode *inode;
9572 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9574 inode = delalloc_work->inode;
9575 filemap_flush(inode->i_mapping);
9576 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9577 &BTRFS_I(inode)->runtime_flags))
9578 filemap_flush(inode->i_mapping);
9581 complete(&delalloc_work->completion);
9584 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9586 struct btrfs_delalloc_work *work;
9588 work = kmalloc(sizeof(*work), GFP_NOFS);
9592 init_completion(&work->completion);
9593 INIT_LIST_HEAD(&work->list);
9594 work->inode = inode;
9595 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9601 * some fairly slow code that needs optimization. This walks the list
9602 * of all the inodes with pending delalloc and forces them to disk.
9604 static int start_delalloc_inodes(struct btrfs_root *root,
9605 struct writeback_control *wbc, bool snapshot,
9606 bool in_reclaim_context)
9608 struct btrfs_inode *binode;
9609 struct inode *inode;
9610 struct btrfs_delalloc_work *work, *next;
9611 struct list_head works;
9612 struct list_head splice;
9614 bool full_flush = wbc->nr_to_write == LONG_MAX;
9616 INIT_LIST_HEAD(&works);
9617 INIT_LIST_HEAD(&splice);
9619 mutex_lock(&root->delalloc_mutex);
9620 spin_lock(&root->delalloc_lock);
9621 list_splice_init(&root->delalloc_inodes, &splice);
9622 while (!list_empty(&splice)) {
9623 binode = list_entry(splice.next, struct btrfs_inode,
9626 list_move_tail(&binode->delalloc_inodes,
9627 &root->delalloc_inodes);
9629 if (in_reclaim_context &&
9630 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9633 inode = igrab(&binode->vfs_inode);
9635 cond_resched_lock(&root->delalloc_lock);
9638 spin_unlock(&root->delalloc_lock);
9641 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9642 &binode->runtime_flags);
9644 work = btrfs_alloc_delalloc_work(inode);
9650 list_add_tail(&work->list, &works);
9651 btrfs_queue_work(root->fs_info->flush_workers,
9654 ret = sync_inode(inode, wbc);
9656 test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9657 &BTRFS_I(inode)->runtime_flags))
9658 ret = sync_inode(inode, wbc);
9659 btrfs_add_delayed_iput(inode);
9660 if (ret || wbc->nr_to_write <= 0)
9664 spin_lock(&root->delalloc_lock);
9666 spin_unlock(&root->delalloc_lock);
9669 list_for_each_entry_safe(work, next, &works, list) {
9670 list_del_init(&work->list);
9671 wait_for_completion(&work->completion);
9675 if (!list_empty(&splice)) {
9676 spin_lock(&root->delalloc_lock);
9677 list_splice_tail(&splice, &root->delalloc_inodes);
9678 spin_unlock(&root->delalloc_lock);
9680 mutex_unlock(&root->delalloc_mutex);
9684 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9686 struct writeback_control wbc = {
9687 .nr_to_write = LONG_MAX,
9688 .sync_mode = WB_SYNC_NONE,
9690 .range_end = LLONG_MAX,
9692 struct btrfs_fs_info *fs_info = root->fs_info;
9694 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9697 return start_delalloc_inodes(root, &wbc, true, false);
9700 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9701 bool in_reclaim_context)
9703 struct writeback_control wbc = {
9705 .sync_mode = WB_SYNC_NONE,
9707 .range_end = LLONG_MAX,
9709 struct btrfs_root *root;
9710 struct list_head splice;
9713 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9716 INIT_LIST_HEAD(&splice);
9718 mutex_lock(&fs_info->delalloc_root_mutex);
9719 spin_lock(&fs_info->delalloc_root_lock);
9720 list_splice_init(&fs_info->delalloc_roots, &splice);
9721 while (!list_empty(&splice)) {
9723 * Reset nr_to_write here so we know that we're doing a full
9727 wbc.nr_to_write = LONG_MAX;
9729 root = list_first_entry(&splice, struct btrfs_root,
9731 root = btrfs_grab_root(root);
9733 list_move_tail(&root->delalloc_root,
9734 &fs_info->delalloc_roots);
9735 spin_unlock(&fs_info->delalloc_root_lock);
9737 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9738 btrfs_put_root(root);
9739 if (ret < 0 || wbc.nr_to_write <= 0)
9741 spin_lock(&fs_info->delalloc_root_lock);
9743 spin_unlock(&fs_info->delalloc_root_lock);
9747 if (!list_empty(&splice)) {
9748 spin_lock(&fs_info->delalloc_root_lock);
9749 list_splice_tail(&splice, &fs_info->delalloc_roots);
9750 spin_unlock(&fs_info->delalloc_root_lock);
9752 mutex_unlock(&fs_info->delalloc_root_mutex);
9756 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9757 struct dentry *dentry, const char *symname)
9759 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9760 struct btrfs_trans_handle *trans;
9761 struct btrfs_root *root = BTRFS_I(dir)->root;
9762 struct btrfs_path *path;
9763 struct btrfs_key key;
9764 struct inode *inode = NULL;
9771 struct btrfs_file_extent_item *ei;
9772 struct extent_buffer *leaf;
9774 name_len = strlen(symname);
9775 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9776 return -ENAMETOOLONG;
9779 * 2 items for inode item and ref
9780 * 2 items for dir items
9781 * 1 item for updating parent inode item
9782 * 1 item for the inline extent item
9783 * 1 item for xattr if selinux is on
9785 trans = btrfs_start_transaction(root, 7);
9787 return PTR_ERR(trans);
9789 err = btrfs_get_free_objectid(root, &objectid);
9793 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9794 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9795 objectid, S_IFLNK|S_IRWXUGO, &index);
9796 if (IS_ERR(inode)) {
9797 err = PTR_ERR(inode);
9803 * If the active LSM wants to access the inode during
9804 * d_instantiate it needs these. Smack checks to see
9805 * if the filesystem supports xattrs by looking at the
9808 inode->i_fop = &btrfs_file_operations;
9809 inode->i_op = &btrfs_file_inode_operations;
9810 inode->i_mapping->a_ops = &btrfs_aops;
9812 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9816 path = btrfs_alloc_path();
9821 key.objectid = btrfs_ino(BTRFS_I(inode));
9823 key.type = BTRFS_EXTENT_DATA_KEY;
9824 datasize = btrfs_file_extent_calc_inline_size(name_len);
9825 err = btrfs_insert_empty_item(trans, root, path, &key,
9828 btrfs_free_path(path);
9831 leaf = path->nodes[0];
9832 ei = btrfs_item_ptr(leaf, path->slots[0],
9833 struct btrfs_file_extent_item);
9834 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9835 btrfs_set_file_extent_type(leaf, ei,
9836 BTRFS_FILE_EXTENT_INLINE);
9837 btrfs_set_file_extent_encryption(leaf, ei, 0);
9838 btrfs_set_file_extent_compression(leaf, ei, 0);
9839 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9840 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9842 ptr = btrfs_file_extent_inline_start(ei);
9843 write_extent_buffer(leaf, symname, ptr, name_len);
9844 btrfs_mark_buffer_dirty(leaf);
9845 btrfs_free_path(path);
9847 inode->i_op = &btrfs_symlink_inode_operations;
9848 inode_nohighmem(inode);
9849 inode_set_bytes(inode, name_len);
9850 btrfs_i_size_write(BTRFS_I(inode), name_len);
9851 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
9853 * Last step, add directory indexes for our symlink inode. This is the
9854 * last step to avoid extra cleanup of these indexes if an error happens
9858 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9859 BTRFS_I(inode), 0, index);
9863 d_instantiate_new(dentry, inode);
9866 btrfs_end_transaction(trans);
9868 inode_dec_link_count(inode);
9869 discard_new_inode(inode);
9871 btrfs_btree_balance_dirty(fs_info);
9875 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9876 struct btrfs_trans_handle *trans_in,
9877 struct btrfs_inode *inode,
9878 struct btrfs_key *ins,
9881 struct btrfs_file_extent_item stack_fi;
9882 struct btrfs_replace_extent_info extent_info;
9883 struct btrfs_trans_handle *trans = trans_in;
9884 struct btrfs_path *path;
9885 u64 start = ins->objectid;
9886 u64 len = ins->offset;
9887 int qgroup_released;
9890 memset(&stack_fi, 0, sizeof(stack_fi));
9892 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9893 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9894 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9895 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9896 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9897 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9898 /* Encryption and other encoding is reserved and all 0 */
9900 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9901 if (qgroup_released < 0)
9902 return ERR_PTR(qgroup_released);
9905 ret = insert_reserved_file_extent(trans, inode,
9906 file_offset, &stack_fi,
9907 true, qgroup_released);
9913 extent_info.disk_offset = start;
9914 extent_info.disk_len = len;
9915 extent_info.data_offset = 0;
9916 extent_info.data_len = len;
9917 extent_info.file_offset = file_offset;
9918 extent_info.extent_buf = (char *)&stack_fi;
9919 extent_info.is_new_extent = true;
9920 extent_info.qgroup_reserved = qgroup_released;
9921 extent_info.insertions = 0;
9923 path = btrfs_alloc_path();
9929 ret = btrfs_replace_file_extents(inode, path, file_offset,
9930 file_offset + len - 1, &extent_info,
9932 btrfs_free_path(path);
9939 * We have released qgroup data range at the beginning of the function,
9940 * and normally qgroup_released bytes will be freed when committing
9942 * But if we error out early, we have to free what we have released
9943 * or we leak qgroup data reservation.
9945 btrfs_qgroup_free_refroot(inode->root->fs_info,
9946 inode->root->root_key.objectid, qgroup_released,
9947 BTRFS_QGROUP_RSV_DATA);
9948 return ERR_PTR(ret);
9951 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9952 u64 start, u64 num_bytes, u64 min_size,
9953 loff_t actual_len, u64 *alloc_hint,
9954 struct btrfs_trans_handle *trans)
9956 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9957 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9958 struct extent_map *em;
9959 struct btrfs_root *root = BTRFS_I(inode)->root;
9960 struct btrfs_key ins;
9961 u64 cur_offset = start;
9962 u64 clear_offset = start;
9965 u64 last_alloc = (u64)-1;
9967 bool own_trans = true;
9968 u64 end = start + num_bytes - 1;
9972 while (num_bytes > 0) {
9973 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9974 cur_bytes = max(cur_bytes, min_size);
9976 * If we are severely fragmented we could end up with really
9977 * small allocations, so if the allocator is returning small
9978 * chunks lets make its job easier by only searching for those
9981 cur_bytes = min(cur_bytes, last_alloc);
9982 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9983 min_size, 0, *alloc_hint, &ins, 1, 0);
9988 * We've reserved this space, and thus converted it from
9989 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9990 * from here on out we will only need to clear our reservation
9991 * for the remaining unreserved area, so advance our
9992 * clear_offset by our extent size.
9994 clear_offset += ins.offset;
9996 last_alloc = ins.offset;
9997 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
10000 * Now that we inserted the prealloc extent we can finally
10001 * decrement the number of reservations in the block group.
10002 * If we did it before, we could race with relocation and have
10003 * relocation miss the reserved extent, making it fail later.
10005 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10006 if (IS_ERR(trans)) {
10007 ret = PTR_ERR(trans);
10008 btrfs_free_reserved_extent(fs_info, ins.objectid,
10013 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10014 cur_offset + ins.offset -1, 0);
10016 em = alloc_extent_map();
10018 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10019 &BTRFS_I(inode)->runtime_flags);
10023 em->start = cur_offset;
10024 em->orig_start = cur_offset;
10025 em->len = ins.offset;
10026 em->block_start = ins.objectid;
10027 em->block_len = ins.offset;
10028 em->orig_block_len = ins.offset;
10029 em->ram_bytes = ins.offset;
10030 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10031 em->generation = trans->transid;
10034 write_lock(&em_tree->lock);
10035 ret = add_extent_mapping(em_tree, em, 1);
10036 write_unlock(&em_tree->lock);
10037 if (ret != -EEXIST)
10039 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10040 cur_offset + ins.offset - 1,
10043 free_extent_map(em);
10045 num_bytes -= ins.offset;
10046 cur_offset += ins.offset;
10047 *alloc_hint = ins.objectid + ins.offset;
10049 inode_inc_iversion(inode);
10050 inode->i_ctime = current_time(inode);
10051 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10052 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10053 (actual_len > inode->i_size) &&
10054 (cur_offset > inode->i_size)) {
10055 if (cur_offset > actual_len)
10056 i_size = actual_len;
10058 i_size = cur_offset;
10059 i_size_write(inode, i_size);
10060 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10063 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10066 btrfs_abort_transaction(trans, ret);
10068 btrfs_end_transaction(trans);
10073 btrfs_end_transaction(trans);
10077 if (clear_offset < end)
10078 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10079 end - clear_offset + 1);
10083 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10084 u64 start, u64 num_bytes, u64 min_size,
10085 loff_t actual_len, u64 *alloc_hint)
10087 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10088 min_size, actual_len, alloc_hint,
10092 int btrfs_prealloc_file_range_trans(struct inode *inode,
10093 struct btrfs_trans_handle *trans, int mode,
10094 u64 start, u64 num_bytes, u64 min_size,
10095 loff_t actual_len, u64 *alloc_hint)
10097 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10098 min_size, actual_len, alloc_hint, trans);
10101 static int btrfs_set_page_dirty(struct page *page)
10103 return __set_page_dirty_nobuffers(page);
10106 static int btrfs_permission(struct user_namespace *mnt_userns,
10107 struct inode *inode, int mask)
10109 struct btrfs_root *root = BTRFS_I(inode)->root;
10110 umode_t mode = inode->i_mode;
10112 if (mask & MAY_WRITE &&
10113 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10114 if (btrfs_root_readonly(root))
10116 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10119 return generic_permission(&init_user_ns, inode, mask);
10122 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10123 struct dentry *dentry, umode_t mode)
10125 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10126 struct btrfs_trans_handle *trans;
10127 struct btrfs_root *root = BTRFS_I(dir)->root;
10128 struct inode *inode = NULL;
10134 * 5 units required for adding orphan entry
10136 trans = btrfs_start_transaction(root, 5);
10138 return PTR_ERR(trans);
10140 ret = btrfs_get_free_objectid(root, &objectid);
10144 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10145 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10146 if (IS_ERR(inode)) {
10147 ret = PTR_ERR(inode);
10152 inode->i_fop = &btrfs_file_operations;
10153 inode->i_op = &btrfs_file_inode_operations;
10155 inode->i_mapping->a_ops = &btrfs_aops;
10157 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10161 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10164 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10169 * We set number of links to 0 in btrfs_new_inode(), and here we set
10170 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10173 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10175 set_nlink(inode, 1);
10176 d_tmpfile(dentry, inode);
10177 unlock_new_inode(inode);
10178 mark_inode_dirty(inode);
10180 btrfs_end_transaction(trans);
10182 discard_new_inode(inode);
10183 btrfs_btree_balance_dirty(fs_info);
10187 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10189 struct inode *inode = tree->private_data;
10190 unsigned long index = start >> PAGE_SHIFT;
10191 unsigned long end_index = end >> PAGE_SHIFT;
10194 while (index <= end_index) {
10195 page = find_get_page(inode->i_mapping, index);
10196 ASSERT(page); /* Pages should be in the extent_io_tree */
10197 set_page_writeback(page);
10205 * Add an entry indicating a block group or device which is pinned by a
10206 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10207 * negative errno on failure.
10209 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10210 bool is_block_group)
10212 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10213 struct btrfs_swapfile_pin *sp, *entry;
10214 struct rb_node **p;
10215 struct rb_node *parent = NULL;
10217 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10222 sp->is_block_group = is_block_group;
10223 sp->bg_extent_count = 1;
10225 spin_lock(&fs_info->swapfile_pins_lock);
10226 p = &fs_info->swapfile_pins.rb_node;
10229 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10230 if (sp->ptr < entry->ptr ||
10231 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10232 p = &(*p)->rb_left;
10233 } else if (sp->ptr > entry->ptr ||
10234 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10235 p = &(*p)->rb_right;
10237 if (is_block_group)
10238 entry->bg_extent_count++;
10239 spin_unlock(&fs_info->swapfile_pins_lock);
10244 rb_link_node(&sp->node, parent, p);
10245 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10246 spin_unlock(&fs_info->swapfile_pins_lock);
10250 /* Free all of the entries pinned by this swapfile. */
10251 static void btrfs_free_swapfile_pins(struct inode *inode)
10253 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10254 struct btrfs_swapfile_pin *sp;
10255 struct rb_node *node, *next;
10257 spin_lock(&fs_info->swapfile_pins_lock);
10258 node = rb_first(&fs_info->swapfile_pins);
10260 next = rb_next(node);
10261 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10262 if (sp->inode == inode) {
10263 rb_erase(&sp->node, &fs_info->swapfile_pins);
10264 if (sp->is_block_group) {
10265 btrfs_dec_block_group_swap_extents(sp->ptr,
10266 sp->bg_extent_count);
10267 btrfs_put_block_group(sp->ptr);
10273 spin_unlock(&fs_info->swapfile_pins_lock);
10276 struct btrfs_swap_info {
10282 unsigned long nr_pages;
10286 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10287 struct btrfs_swap_info *bsi)
10289 unsigned long nr_pages;
10290 u64 first_ppage, first_ppage_reported, next_ppage;
10293 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10294 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10295 PAGE_SIZE) >> PAGE_SHIFT;
10297 if (first_ppage >= next_ppage)
10299 nr_pages = next_ppage - first_ppage;
10301 first_ppage_reported = first_ppage;
10302 if (bsi->start == 0)
10303 first_ppage_reported++;
10304 if (bsi->lowest_ppage > first_ppage_reported)
10305 bsi->lowest_ppage = first_ppage_reported;
10306 if (bsi->highest_ppage < (next_ppage - 1))
10307 bsi->highest_ppage = next_ppage - 1;
10309 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10312 bsi->nr_extents += ret;
10313 bsi->nr_pages += nr_pages;
10317 static void btrfs_swap_deactivate(struct file *file)
10319 struct inode *inode = file_inode(file);
10321 btrfs_free_swapfile_pins(inode);
10322 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10325 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10328 struct inode *inode = file_inode(file);
10329 struct btrfs_root *root = BTRFS_I(inode)->root;
10330 struct btrfs_fs_info *fs_info = root->fs_info;
10331 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10332 struct extent_state *cached_state = NULL;
10333 struct extent_map *em = NULL;
10334 struct btrfs_device *device = NULL;
10335 struct btrfs_swap_info bsi = {
10336 .lowest_ppage = (sector_t)-1ULL,
10343 * If the swap file was just created, make sure delalloc is done. If the
10344 * file changes again after this, the user is doing something stupid and
10345 * we don't really care.
10347 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10352 * The inode is locked, so these flags won't change after we check them.
10354 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10355 btrfs_warn(fs_info, "swapfile must not be compressed");
10358 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10359 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10362 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10363 btrfs_warn(fs_info, "swapfile must not be checksummed");
10368 * Balance or device remove/replace/resize can move stuff around from
10369 * under us. The exclop protection makes sure they aren't running/won't
10370 * run concurrently while we are mapping the swap extents, and
10371 * fs_info->swapfile_pins prevents them from running while the swap
10372 * file is active and moving the extents. Note that this also prevents
10373 * a concurrent device add which isn't actually necessary, but it's not
10374 * really worth the trouble to allow it.
10376 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10377 btrfs_warn(fs_info,
10378 "cannot activate swapfile while exclusive operation is running");
10383 * Prevent snapshot creation while we are activating the swap file.
10384 * We do not want to race with snapshot creation. If snapshot creation
10385 * already started before we bumped nr_swapfiles from 0 to 1 and
10386 * completes before the first write into the swap file after it is
10387 * activated, than that write would fallback to COW.
10389 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10390 btrfs_exclop_finish(fs_info);
10391 btrfs_warn(fs_info,
10392 "cannot activate swapfile because snapshot creation is in progress");
10396 * Snapshots can create extents which require COW even if NODATACOW is
10397 * set. We use this counter to prevent snapshots. We must increment it
10398 * before walking the extents because we don't want a concurrent
10399 * snapshot to run after we've already checked the extents.
10401 atomic_inc(&root->nr_swapfiles);
10403 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10405 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10407 while (start < isize) {
10408 u64 logical_block_start, physical_block_start;
10409 struct btrfs_block_group *bg;
10410 u64 len = isize - start;
10412 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10418 if (em->block_start == EXTENT_MAP_HOLE) {
10419 btrfs_warn(fs_info, "swapfile must not have holes");
10423 if (em->block_start == EXTENT_MAP_INLINE) {
10425 * It's unlikely we'll ever actually find ourselves
10426 * here, as a file small enough to fit inline won't be
10427 * big enough to store more than the swap header, but in
10428 * case something changes in the future, let's catch it
10429 * here rather than later.
10431 btrfs_warn(fs_info, "swapfile must not be inline");
10435 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10436 btrfs_warn(fs_info, "swapfile must not be compressed");
10441 logical_block_start = em->block_start + (start - em->start);
10442 len = min(len, em->len - (start - em->start));
10443 free_extent_map(em);
10446 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10452 btrfs_warn(fs_info,
10453 "swapfile must not be copy-on-write");
10458 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10464 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10465 btrfs_warn(fs_info,
10466 "swapfile must have single data profile");
10471 if (device == NULL) {
10472 device = em->map_lookup->stripes[0].dev;
10473 ret = btrfs_add_swapfile_pin(inode, device, false);
10478 } else if (device != em->map_lookup->stripes[0].dev) {
10479 btrfs_warn(fs_info, "swapfile must be on one device");
10484 physical_block_start = (em->map_lookup->stripes[0].physical +
10485 (logical_block_start - em->start));
10486 len = min(len, em->len - (logical_block_start - em->start));
10487 free_extent_map(em);
10490 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10492 btrfs_warn(fs_info,
10493 "could not find block group containing swapfile");
10498 if (!btrfs_inc_block_group_swap_extents(bg)) {
10499 btrfs_warn(fs_info,
10500 "block group for swapfile at %llu is read-only%s",
10502 atomic_read(&fs_info->scrubs_running) ?
10503 " (scrub running)" : "");
10504 btrfs_put_block_group(bg);
10509 ret = btrfs_add_swapfile_pin(inode, bg, true);
10511 btrfs_put_block_group(bg);
10518 if (bsi.block_len &&
10519 bsi.block_start + bsi.block_len == physical_block_start) {
10520 bsi.block_len += len;
10522 if (bsi.block_len) {
10523 ret = btrfs_add_swap_extent(sis, &bsi);
10528 bsi.block_start = physical_block_start;
10529 bsi.block_len = len;
10536 ret = btrfs_add_swap_extent(sis, &bsi);
10539 if (!IS_ERR_OR_NULL(em))
10540 free_extent_map(em);
10542 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10545 btrfs_swap_deactivate(file);
10547 btrfs_drew_write_unlock(&root->snapshot_lock);
10549 btrfs_exclop_finish(fs_info);
10555 sis->bdev = device->bdev;
10556 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10557 sis->max = bsi.nr_pages;
10558 sis->pages = bsi.nr_pages - 1;
10559 sis->highest_bit = bsi.nr_pages - 1;
10560 return bsi.nr_extents;
10563 static void btrfs_swap_deactivate(struct file *file)
10567 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10570 return -EOPNOTSUPP;
10575 * Update the number of bytes used in the VFS' inode. When we replace extents in
10576 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10577 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10578 * always get a correct value.
10580 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10581 const u64 add_bytes,
10582 const u64 del_bytes)
10584 if (add_bytes == del_bytes)
10587 spin_lock(&inode->lock);
10589 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10591 inode_add_bytes(&inode->vfs_inode, add_bytes);
10592 spin_unlock(&inode->lock);
10595 static const struct inode_operations btrfs_dir_inode_operations = {
10596 .getattr = btrfs_getattr,
10597 .lookup = btrfs_lookup,
10598 .create = btrfs_create,
10599 .unlink = btrfs_unlink,
10600 .link = btrfs_link,
10601 .mkdir = btrfs_mkdir,
10602 .rmdir = btrfs_rmdir,
10603 .rename = btrfs_rename2,
10604 .symlink = btrfs_symlink,
10605 .setattr = btrfs_setattr,
10606 .mknod = btrfs_mknod,
10607 .listxattr = btrfs_listxattr,
10608 .permission = btrfs_permission,
10609 .get_acl = btrfs_get_acl,
10610 .set_acl = btrfs_set_acl,
10611 .update_time = btrfs_update_time,
10612 .tmpfile = btrfs_tmpfile,
10615 static const struct file_operations btrfs_dir_file_operations = {
10616 .llseek = generic_file_llseek,
10617 .read = generic_read_dir,
10618 .iterate_shared = btrfs_real_readdir,
10619 .open = btrfs_opendir,
10620 .unlocked_ioctl = btrfs_ioctl,
10621 #ifdef CONFIG_COMPAT
10622 .compat_ioctl = btrfs_compat_ioctl,
10624 .release = btrfs_release_file,
10625 .fsync = btrfs_sync_file,
10629 * btrfs doesn't support the bmap operation because swapfiles
10630 * use bmap to make a mapping of extents in the file. They assume
10631 * these extents won't change over the life of the file and they
10632 * use the bmap result to do IO directly to the drive.
10634 * the btrfs bmap call would return logical addresses that aren't
10635 * suitable for IO and they also will change frequently as COW
10636 * operations happen. So, swapfile + btrfs == corruption.
10638 * For now we're avoiding this by dropping bmap.
10640 static const struct address_space_operations btrfs_aops = {
10641 .readpage = btrfs_readpage,
10642 .writepage = btrfs_writepage,
10643 .writepages = btrfs_writepages,
10644 .readahead = btrfs_readahead,
10645 .direct_IO = noop_direct_IO,
10646 .invalidatepage = btrfs_invalidatepage,
10647 .releasepage = btrfs_releasepage,
10648 #ifdef CONFIG_MIGRATION
10649 .migratepage = btrfs_migratepage,
10651 .set_page_dirty = btrfs_set_page_dirty,
10652 .error_remove_page = generic_error_remove_page,
10653 .swap_activate = btrfs_swap_activate,
10654 .swap_deactivate = btrfs_swap_deactivate,
10657 static const struct inode_operations btrfs_file_inode_operations = {
10658 .getattr = btrfs_getattr,
10659 .setattr = btrfs_setattr,
10660 .listxattr = btrfs_listxattr,
10661 .permission = btrfs_permission,
10662 .fiemap = btrfs_fiemap,
10663 .get_acl = btrfs_get_acl,
10664 .set_acl = btrfs_set_acl,
10665 .update_time = btrfs_update_time,
10667 static const struct inode_operations btrfs_special_inode_operations = {
10668 .getattr = btrfs_getattr,
10669 .setattr = btrfs_setattr,
10670 .permission = btrfs_permission,
10671 .listxattr = btrfs_listxattr,
10672 .get_acl = btrfs_get_acl,
10673 .set_acl = btrfs_set_acl,
10674 .update_time = btrfs_update_time,
10676 static const struct inode_operations btrfs_symlink_inode_operations = {
10677 .get_link = page_get_link,
10678 .getattr = btrfs_getattr,
10679 .setattr = btrfs_setattr,
10680 .permission = btrfs_permission,
10681 .listxattr = btrfs_listxattr,
10682 .update_time = btrfs_update_time,
10685 const struct dentry_operations btrfs_dentry_operations = {
10686 .d_delete = btrfs_dentry_delete,