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
106 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
108 if (ilock_flags & BTRFS_ILOCK_SHARED) {
109 if (ilock_flags & BTRFS_ILOCK_TRY) {
110 if (!inode_trylock_shared(inode))
115 inode_lock_shared(inode);
117 if (ilock_flags & BTRFS_ILOCK_TRY) {
118 if (!inode_trylock(inode))
129 * btrfs_inode_unlock - unock inode i_rwsem
131 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
132 * to decide whether the lock acquired is shared or exclusive.
134 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
136 if (ilock_flags & BTRFS_ILOCK_SHARED)
137 inode_unlock_shared(inode);
143 * Cleanup all submitted ordered extents in specified range to handle errors
144 * from the btrfs_run_delalloc_range() callback.
146 * NOTE: caller must ensure that when an error happens, it can not call
147 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
148 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
149 * to be released, which we want to happen only when finishing the ordered
150 * extent (btrfs_finish_ordered_io()).
152 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
153 struct page *locked_page,
154 u64 offset, u64 bytes)
156 unsigned long index = offset >> PAGE_SHIFT;
157 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
158 u64 page_start = page_offset(locked_page);
159 u64 page_end = page_start + PAGE_SIZE - 1;
163 while (index <= end_index) {
164 page = find_get_page(inode->vfs_inode.i_mapping, index);
168 ClearPagePrivate2(page);
173 * In case this page belongs to the delalloc range being instantiated
174 * then skip it, since the first page of a range is going to be
175 * properly cleaned up by the caller of run_delalloc_range
177 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
182 return __endio_write_update_ordered(inode, offset, bytes, false);
185 static int btrfs_dirty_inode(struct inode *inode);
187 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
188 struct inode *inode, struct inode *dir,
189 const struct qstr *qstr)
193 err = btrfs_init_acl(trans, inode, dir);
195 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
200 * this does all the hard work for inserting an inline extent into
201 * the btree. The caller should have done a btrfs_drop_extents so that
202 * no overlapping inline items exist in the btree
204 static int insert_inline_extent(struct btrfs_trans_handle *trans,
205 struct btrfs_path *path, bool extent_inserted,
206 struct btrfs_root *root, struct inode *inode,
207 u64 start, size_t size, size_t compressed_size,
209 struct page **compressed_pages)
211 struct extent_buffer *leaf;
212 struct page *page = NULL;
215 struct btrfs_file_extent_item *ei;
217 size_t cur_size = size;
218 unsigned long offset;
220 ASSERT((compressed_size > 0 && compressed_pages) ||
221 (compressed_size == 0 && !compressed_pages));
223 if (compressed_size && compressed_pages)
224 cur_size = compressed_size;
226 if (!extent_inserted) {
227 struct btrfs_key key;
230 key.objectid = btrfs_ino(BTRFS_I(inode));
232 key.type = BTRFS_EXTENT_DATA_KEY;
234 datasize = btrfs_file_extent_calc_inline_size(cur_size);
235 ret = btrfs_insert_empty_item(trans, root, path, &key,
240 leaf = path->nodes[0];
241 ei = btrfs_item_ptr(leaf, path->slots[0],
242 struct btrfs_file_extent_item);
243 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
244 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
245 btrfs_set_file_extent_encryption(leaf, ei, 0);
246 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
247 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
248 ptr = btrfs_file_extent_inline_start(ei);
250 if (compress_type != BTRFS_COMPRESS_NONE) {
253 while (compressed_size > 0) {
254 cpage = compressed_pages[i];
255 cur_size = min_t(unsigned long, compressed_size,
258 kaddr = kmap_atomic(cpage);
259 write_extent_buffer(leaf, kaddr, ptr, cur_size);
260 kunmap_atomic(kaddr);
264 compressed_size -= cur_size;
266 btrfs_set_file_extent_compression(leaf, ei,
269 page = find_get_page(inode->i_mapping,
270 start >> PAGE_SHIFT);
271 btrfs_set_file_extent_compression(leaf, ei, 0);
272 kaddr = kmap_atomic(page);
273 offset = offset_in_page(start);
274 write_extent_buffer(leaf, kaddr + offset, ptr, size);
275 kunmap_atomic(kaddr);
278 btrfs_mark_buffer_dirty(leaf);
279 btrfs_release_path(path);
282 * We align size to sectorsize for inline extents just for simplicity
285 size = ALIGN(size, root->fs_info->sectorsize);
286 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
291 * we're an inline extent, so nobody can
292 * extend the file past i_size without locking
293 * a page we already have locked.
295 * We must do any isize and inode updates
296 * before we unlock the pages. Otherwise we
297 * could end up racing with unlink.
299 BTRFS_I(inode)->disk_i_size = inode->i_size;
306 * conditionally insert an inline extent into the file. This
307 * does the checks required to make sure the data is small enough
308 * to fit as an inline extent.
310 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
311 u64 end, size_t compressed_size,
313 struct page **compressed_pages)
315 struct btrfs_drop_extents_args drop_args = { 0 };
316 struct btrfs_root *root = inode->root;
317 struct btrfs_fs_info *fs_info = root->fs_info;
318 struct btrfs_trans_handle *trans;
319 u64 isize = i_size_read(&inode->vfs_inode);
320 u64 actual_end = min(end + 1, isize);
321 u64 inline_len = actual_end - start;
322 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
323 u64 data_len = inline_len;
325 struct btrfs_path *path;
328 data_len = compressed_size;
331 actual_end > fs_info->sectorsize ||
332 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
334 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
336 data_len > fs_info->max_inline) {
340 path = btrfs_alloc_path();
344 trans = btrfs_join_transaction(root);
346 btrfs_free_path(path);
347 return PTR_ERR(trans);
349 trans->block_rsv = &inode->block_rsv;
351 drop_args.path = path;
352 drop_args.start = start;
353 drop_args.end = aligned_end;
354 drop_args.drop_cache = true;
355 drop_args.replace_extent = true;
357 if (compressed_size && compressed_pages)
358 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
361 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
364 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
366 btrfs_abort_transaction(trans, ret);
370 if (isize > actual_end)
371 inline_len = min_t(u64, isize, actual_end);
372 ret = insert_inline_extent(trans, path, drop_args.extent_inserted,
373 root, &inode->vfs_inode, start,
374 inline_len, compressed_size,
375 compress_type, compressed_pages);
376 if (ret && ret != -ENOSPC) {
377 btrfs_abort_transaction(trans, ret);
379 } else if (ret == -ENOSPC) {
384 btrfs_update_inode_bytes(inode, inline_len, drop_args.bytes_found);
385 ret = btrfs_update_inode(trans, root, inode);
386 if (ret && ret != -ENOSPC) {
387 btrfs_abort_transaction(trans, ret);
389 } else if (ret == -ENOSPC) {
394 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
397 * Don't forget to free the reserved space, as for inlined extent
398 * it won't count as data extent, free them directly here.
399 * And at reserve time, it's always aligned to page size, so
400 * just free one page here.
402 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
403 btrfs_free_path(path);
404 btrfs_end_transaction(trans);
408 struct async_extent {
413 unsigned long nr_pages;
415 struct list_head list;
420 struct page *locked_page;
423 unsigned int write_flags;
424 struct list_head extents;
425 struct cgroup_subsys_state *blkcg_css;
426 struct btrfs_work work;
431 /* Number of chunks in flight; must be first in the structure */
433 struct async_chunk chunks[];
436 static noinline int add_async_extent(struct async_chunk *cow,
437 u64 start, u64 ram_size,
440 unsigned long nr_pages,
443 struct async_extent *async_extent;
445 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
446 BUG_ON(!async_extent); /* -ENOMEM */
447 async_extent->start = start;
448 async_extent->ram_size = ram_size;
449 async_extent->compressed_size = compressed_size;
450 async_extent->pages = pages;
451 async_extent->nr_pages = nr_pages;
452 async_extent->compress_type = compress_type;
453 list_add_tail(&async_extent->list, &cow->extents);
458 * Check if the inode has flags compatible with compression
460 static inline bool inode_can_compress(struct btrfs_inode *inode)
462 if (inode->flags & BTRFS_INODE_NODATACOW ||
463 inode->flags & BTRFS_INODE_NODATASUM)
469 * Check if the inode needs to be submitted to compression, based on mount
470 * options, defragmentation, properties or heuristics.
472 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
475 struct btrfs_fs_info *fs_info = inode->root->fs_info;
477 if (!inode_can_compress(inode)) {
478 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
479 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
484 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
487 if (inode->defrag_compress)
489 /* bad compression ratios */
490 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
492 if (btrfs_test_opt(fs_info, COMPRESS) ||
493 inode->flags & BTRFS_INODE_COMPRESS ||
494 inode->prop_compress)
495 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
499 static inline void inode_should_defrag(struct btrfs_inode *inode,
500 u64 start, u64 end, u64 num_bytes, u64 small_write)
502 /* If this is a small write inside eof, kick off a defrag */
503 if (num_bytes < small_write &&
504 (start > 0 || end + 1 < inode->disk_i_size))
505 btrfs_add_inode_defrag(NULL, inode);
509 * we create compressed extents in two phases. The first
510 * phase compresses a range of pages that have already been
511 * locked (both pages and state bits are locked).
513 * This is done inside an ordered work queue, and the compression
514 * is spread across many cpus. The actual IO submission is step
515 * two, and the ordered work queue takes care of making sure that
516 * happens in the same order things were put onto the queue by
517 * writepages and friends.
519 * If this code finds it can't get good compression, it puts an
520 * entry onto the work queue to write the uncompressed bytes. This
521 * makes sure that both compressed inodes and uncompressed inodes
522 * are written in the same order that the flusher thread sent them
525 static noinline int compress_file_range(struct async_chunk *async_chunk)
527 struct inode *inode = async_chunk->inode;
528 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
529 u64 blocksize = fs_info->sectorsize;
530 u64 start = async_chunk->start;
531 u64 end = async_chunk->end;
535 struct page **pages = NULL;
536 unsigned long nr_pages;
537 unsigned long total_compressed = 0;
538 unsigned long total_in = 0;
541 int compress_type = fs_info->compress_type;
542 int compressed_extents = 0;
545 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
549 * We need to save i_size before now because it could change in between
550 * us evaluating the size and assigning it. This is because we lock and
551 * unlock the page in truncate and fallocate, and then modify the i_size
554 * The barriers are to emulate READ_ONCE, remove that once i_size_read
558 i_size = i_size_read(inode);
560 actual_end = min_t(u64, i_size, end + 1);
563 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
564 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
565 nr_pages = min_t(unsigned long, nr_pages,
566 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
569 * we don't want to send crud past the end of i_size through
570 * compression, that's just a waste of CPU time. So, if the
571 * end of the file is before the start of our current
572 * requested range of bytes, we bail out to the uncompressed
573 * cleanup code that can deal with all of this.
575 * It isn't really the fastest way to fix things, but this is a
576 * very uncommon corner.
578 if (actual_end <= start)
579 goto cleanup_and_bail_uncompressed;
581 total_compressed = actual_end - start;
584 * skip compression for a small file range(<=blocksize) that
585 * isn't an inline extent, since it doesn't save disk space at all.
587 if (total_compressed <= blocksize &&
588 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
589 goto cleanup_and_bail_uncompressed;
591 total_compressed = min_t(unsigned long, total_compressed,
592 BTRFS_MAX_UNCOMPRESSED);
597 * we do compression for mount -o compress and when the
598 * inode has not been flagged as nocompress. This flag can
599 * change at any time if we discover bad compression ratios.
601 if (inode_need_compress(BTRFS_I(inode), start, end)) {
603 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
605 /* just bail out to the uncompressed code */
610 if (BTRFS_I(inode)->defrag_compress)
611 compress_type = BTRFS_I(inode)->defrag_compress;
612 else if (BTRFS_I(inode)->prop_compress)
613 compress_type = BTRFS_I(inode)->prop_compress;
616 * we need to call clear_page_dirty_for_io on each
617 * page in the range. Otherwise applications with the file
618 * mmap'd can wander in and change the page contents while
619 * we are compressing them.
621 * If the compression fails for any reason, we set the pages
622 * dirty again later on.
624 * Note that the remaining part is redirtied, the start pointer
625 * has moved, the end is the original one.
628 extent_range_clear_dirty_for_io(inode, start, end);
632 /* Compression level is applied here and only here */
633 ret = btrfs_compress_pages(
634 compress_type | (fs_info->compress_level << 4),
635 inode->i_mapping, start,
642 unsigned long offset = offset_in_page(total_compressed);
643 struct page *page = pages[nr_pages - 1];
646 /* zero the tail end of the last page, we might be
647 * sending it down to disk
650 kaddr = kmap_atomic(page);
651 memset(kaddr + offset, 0,
653 kunmap_atomic(kaddr);
660 /* lets try to make an inline extent */
661 if (ret || total_in < actual_end) {
662 /* we didn't compress the entire range, try
663 * to make an uncompressed inline extent.
665 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
666 0, BTRFS_COMPRESS_NONE,
669 /* try making a compressed inline extent */
670 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
672 compress_type, pages);
675 unsigned long clear_flags = EXTENT_DELALLOC |
676 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
677 EXTENT_DO_ACCOUNTING;
678 unsigned long page_error_op;
680 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
683 * inline extent creation worked or returned error,
684 * we don't need to create any more async work items.
685 * Unlock and free up our temp pages.
687 * We use DO_ACCOUNTING here because we need the
688 * delalloc_release_metadata to be done _after_ we drop
689 * our outstanding extent for clearing delalloc for this
692 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
696 PAGE_START_WRITEBACK |
701 * Ensure we only free the compressed pages if we have
702 * them allocated, as we can still reach here with
703 * inode_need_compress() == false.
706 for (i = 0; i < nr_pages; i++) {
707 WARN_ON(pages[i]->mapping);
718 * we aren't doing an inline extent round the compressed size
719 * up to a block size boundary so the allocator does sane
722 total_compressed = ALIGN(total_compressed, blocksize);
725 * one last check to make sure the compression is really a
726 * win, compare the page count read with the blocks on disk,
727 * compression must free at least one sector size
729 total_in = ALIGN(total_in, PAGE_SIZE);
730 if (total_compressed + blocksize <= total_in) {
731 compressed_extents++;
734 * The async work queues will take care of doing actual
735 * allocation on disk for these compressed pages, and
736 * will submit them to the elevator.
738 add_async_extent(async_chunk, start, total_in,
739 total_compressed, pages, nr_pages,
742 if (start + total_in < end) {
748 return compressed_extents;
753 * the compression code ran but failed to make things smaller,
754 * free any pages it allocated and our page pointer array
756 for (i = 0; i < nr_pages; i++) {
757 WARN_ON(pages[i]->mapping);
762 total_compressed = 0;
765 /* flag the file so we don't compress in the future */
766 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
767 !(BTRFS_I(inode)->prop_compress)) {
768 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
771 cleanup_and_bail_uncompressed:
773 * No compression, but we still need to write the pages in the file
774 * we've been given so far. redirty the locked page if it corresponds
775 * to our extent and set things up for the async work queue to run
776 * cow_file_range to do the normal delalloc dance.
778 if (async_chunk->locked_page &&
779 (page_offset(async_chunk->locked_page) >= start &&
780 page_offset(async_chunk->locked_page)) <= end) {
781 __set_page_dirty_nobuffers(async_chunk->locked_page);
782 /* unlocked later on in the async handlers */
786 extent_range_redirty_for_io(inode, start, end);
787 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
788 BTRFS_COMPRESS_NONE);
789 compressed_extents++;
791 return compressed_extents;
794 static void free_async_extent_pages(struct async_extent *async_extent)
798 if (!async_extent->pages)
801 for (i = 0; i < async_extent->nr_pages; i++) {
802 WARN_ON(async_extent->pages[i]->mapping);
803 put_page(async_extent->pages[i]);
805 kfree(async_extent->pages);
806 async_extent->nr_pages = 0;
807 async_extent->pages = NULL;
811 * phase two of compressed writeback. This is the ordered portion
812 * of the code, which only gets called in the order the work was
813 * queued. We walk all the async extents created by compress_file_range
814 * and send them down to the disk.
816 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
818 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
819 struct btrfs_fs_info *fs_info = inode->root->fs_info;
820 struct async_extent *async_extent;
822 struct btrfs_key ins;
823 struct extent_map *em;
824 struct btrfs_root *root = inode->root;
825 struct extent_io_tree *io_tree = &inode->io_tree;
829 while (!list_empty(&async_chunk->extents)) {
830 async_extent = list_entry(async_chunk->extents.next,
831 struct async_extent, list);
832 list_del(&async_extent->list);
835 lock_extent(io_tree, async_extent->start,
836 async_extent->start + async_extent->ram_size - 1);
837 /* did the compression code fall back to uncompressed IO? */
838 if (!async_extent->pages) {
839 int page_started = 0;
840 unsigned long nr_written = 0;
842 /* allocate blocks */
843 ret = cow_file_range(inode, async_chunk->locked_page,
845 async_extent->start +
846 async_extent->ram_size - 1,
847 &page_started, &nr_written, 0);
852 * if page_started, cow_file_range inserted an
853 * inline extent and took care of all the unlocking
854 * and IO for us. Otherwise, we need to submit
855 * all those pages down to the drive.
857 if (!page_started && !ret)
858 extent_write_locked_range(&inode->vfs_inode,
860 async_extent->start +
861 async_extent->ram_size - 1,
863 else if (ret && async_chunk->locked_page)
864 unlock_page(async_chunk->locked_page);
870 ret = btrfs_reserve_extent(root, async_extent->ram_size,
871 async_extent->compressed_size,
872 async_extent->compressed_size,
873 0, alloc_hint, &ins, 1, 1);
875 free_async_extent_pages(async_extent);
877 if (ret == -ENOSPC) {
878 unlock_extent(io_tree, async_extent->start,
879 async_extent->start +
880 async_extent->ram_size - 1);
883 * we need to redirty the pages if we decide to
884 * fallback to uncompressed IO, otherwise we
885 * will not submit these pages down to lower
888 extent_range_redirty_for_io(&inode->vfs_inode,
890 async_extent->start +
891 async_extent->ram_size - 1);
898 * here we're doing allocation and writeback of the
901 em = create_io_em(inode, async_extent->start,
902 async_extent->ram_size, /* len */
903 async_extent->start, /* orig_start */
904 ins.objectid, /* block_start */
905 ins.offset, /* block_len */
906 ins.offset, /* orig_block_len */
907 async_extent->ram_size, /* ram_bytes */
908 async_extent->compress_type,
909 BTRFS_ORDERED_COMPRESSED);
911 /* ret value is not necessary due to void function */
912 goto out_free_reserve;
915 ret = btrfs_add_ordered_extent_compress(inode,
918 async_extent->ram_size,
920 async_extent->compress_type);
922 btrfs_drop_extent_cache(inode, async_extent->start,
923 async_extent->start +
924 async_extent->ram_size - 1, 0);
925 goto out_free_reserve;
927 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
930 * clear dirty, set writeback and unlock the pages.
932 extent_clear_unlock_delalloc(inode, async_extent->start,
933 async_extent->start +
934 async_extent->ram_size - 1,
935 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
936 PAGE_UNLOCK | PAGE_START_WRITEBACK);
937 if (btrfs_submit_compressed_write(inode, async_extent->start,
938 async_extent->ram_size,
940 ins.offset, async_extent->pages,
941 async_extent->nr_pages,
942 async_chunk->write_flags,
943 async_chunk->blkcg_css)) {
944 struct page *p = async_extent->pages[0];
945 const u64 start = async_extent->start;
946 const u64 end = start + async_extent->ram_size - 1;
948 p->mapping = inode->vfs_inode.i_mapping;
949 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
952 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
955 free_async_extent_pages(async_extent);
957 alloc_hint = ins.objectid + ins.offset;
963 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
964 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
966 extent_clear_unlock_delalloc(inode, async_extent->start,
967 async_extent->start +
968 async_extent->ram_size - 1,
969 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
970 EXTENT_DELALLOC_NEW |
971 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
972 PAGE_UNLOCK | PAGE_START_WRITEBACK |
973 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
974 free_async_extent_pages(async_extent);
979 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
982 struct extent_map_tree *em_tree = &inode->extent_tree;
983 struct extent_map *em;
986 read_lock(&em_tree->lock);
987 em = search_extent_mapping(em_tree, start, num_bytes);
990 * if block start isn't an actual block number then find the
991 * first block in this inode and use that as a hint. If that
992 * block is also bogus then just don't worry about it.
994 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
996 em = search_extent_mapping(em_tree, 0, 0);
997 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
998 alloc_hint = em->block_start;
1000 free_extent_map(em);
1002 alloc_hint = em->block_start;
1003 free_extent_map(em);
1006 read_unlock(&em_tree->lock);
1012 * when extent_io.c finds a delayed allocation range in the file,
1013 * the call backs end up in this code. The basic idea is to
1014 * allocate extents on disk for the range, and create ordered data structs
1015 * in ram to track those extents.
1017 * locked_page is the page that writepage had locked already. We use
1018 * it to make sure we don't do extra locks or unlocks.
1020 * *page_started is set to one if we unlock locked_page and do everything
1021 * required to start IO on it. It may be clean and already done with
1022 * IO when we return.
1024 static noinline int cow_file_range(struct btrfs_inode *inode,
1025 struct page *locked_page,
1026 u64 start, u64 end, int *page_started,
1027 unsigned long *nr_written, int unlock)
1029 struct btrfs_root *root = inode->root;
1030 struct btrfs_fs_info *fs_info = root->fs_info;
1033 unsigned long ram_size;
1034 u64 cur_alloc_size = 0;
1036 u64 blocksize = fs_info->sectorsize;
1037 struct btrfs_key ins;
1038 struct extent_map *em;
1039 unsigned clear_bits;
1040 unsigned long page_ops;
1041 bool extent_reserved = false;
1044 if (btrfs_is_free_space_inode(inode)) {
1050 num_bytes = ALIGN(end - start + 1, blocksize);
1051 num_bytes = max(blocksize, num_bytes);
1052 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1054 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1057 /* lets try to make an inline extent */
1058 ret = cow_file_range_inline(inode, start, end, 0,
1059 BTRFS_COMPRESS_NONE, NULL);
1062 * We use DO_ACCOUNTING here because we need the
1063 * delalloc_release_metadata to be run _after_ we drop
1064 * our outstanding extent for clearing delalloc for this
1067 extent_clear_unlock_delalloc(inode, start, end, NULL,
1068 EXTENT_LOCKED | EXTENT_DELALLOC |
1069 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1070 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1071 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1072 *nr_written = *nr_written +
1073 (end - start + PAGE_SIZE) / PAGE_SIZE;
1076 } else if (ret < 0) {
1081 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1082 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1085 * Relocation relies on the relocated extents to have exactly the same
1086 * size as the original extents. Normally writeback for relocation data
1087 * extents follows a NOCOW path because relocation preallocates the
1088 * extents. However, due to an operation such as scrub turning a block
1089 * group to RO mode, it may fallback to COW mode, so we must make sure
1090 * an extent allocated during COW has exactly the requested size and can
1091 * not be split into smaller extents, otherwise relocation breaks and
1092 * fails during the stage where it updates the bytenr of file extent
1095 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1096 min_alloc_size = num_bytes;
1098 min_alloc_size = fs_info->sectorsize;
1100 while (num_bytes > 0) {
1101 cur_alloc_size = num_bytes;
1102 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1103 min_alloc_size, 0, alloc_hint,
1107 cur_alloc_size = ins.offset;
1108 extent_reserved = true;
1110 ram_size = ins.offset;
1111 em = create_io_em(inode, start, ins.offset, /* len */
1112 start, /* orig_start */
1113 ins.objectid, /* block_start */
1114 ins.offset, /* block_len */
1115 ins.offset, /* orig_block_len */
1116 ram_size, /* ram_bytes */
1117 BTRFS_COMPRESS_NONE, /* compress_type */
1118 BTRFS_ORDERED_REGULAR /* type */);
1123 free_extent_map(em);
1125 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1126 ram_size, cur_alloc_size,
1127 BTRFS_ORDERED_REGULAR);
1129 goto out_drop_extent_cache;
1131 if (root->root_key.objectid ==
1132 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1133 ret = btrfs_reloc_clone_csums(inode, start,
1136 * Only drop cache here, and process as normal.
1138 * We must not allow extent_clear_unlock_delalloc()
1139 * at out_unlock label to free meta of this ordered
1140 * extent, as its meta should be freed by
1141 * btrfs_finish_ordered_io().
1143 * So we must continue until @start is increased to
1144 * skip current ordered extent.
1147 btrfs_drop_extent_cache(inode, start,
1148 start + ram_size - 1, 0);
1151 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1153 /* we're not doing compressed IO, don't unlock the first
1154 * page (which the caller expects to stay locked), don't
1155 * clear any dirty bits and don't set any writeback bits
1157 * Do set the Private2 bit so we know this page was properly
1158 * setup for writepage
1160 page_ops = unlock ? PAGE_UNLOCK : 0;
1161 page_ops |= PAGE_SET_PRIVATE2;
1163 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1165 EXTENT_LOCKED | EXTENT_DELALLOC,
1167 if (num_bytes < cur_alloc_size)
1170 num_bytes -= cur_alloc_size;
1171 alloc_hint = ins.objectid + ins.offset;
1172 start += cur_alloc_size;
1173 extent_reserved = false;
1176 * btrfs_reloc_clone_csums() error, since start is increased
1177 * extent_clear_unlock_delalloc() at out_unlock label won't
1178 * free metadata of current ordered extent, we're OK to exit.
1186 out_drop_extent_cache:
1187 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1189 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1190 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1192 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1193 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1194 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1196 * If we reserved an extent for our delalloc range (or a subrange) and
1197 * failed to create the respective ordered extent, then it means that
1198 * when we reserved the extent we decremented the extent's size from
1199 * the data space_info's bytes_may_use counter and incremented the
1200 * space_info's bytes_reserved counter by the same amount. We must make
1201 * sure extent_clear_unlock_delalloc() does not try to decrement again
1202 * the data space_info's bytes_may_use counter, therefore we do not pass
1203 * it the flag EXTENT_CLEAR_DATA_RESV.
1205 if (extent_reserved) {
1206 extent_clear_unlock_delalloc(inode, start,
1207 start + cur_alloc_size - 1,
1211 start += cur_alloc_size;
1215 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1216 clear_bits | EXTENT_CLEAR_DATA_RESV,
1222 * work queue call back to started compression on a file and pages
1224 static noinline void async_cow_start(struct btrfs_work *work)
1226 struct async_chunk *async_chunk;
1227 int compressed_extents;
1229 async_chunk = container_of(work, struct async_chunk, work);
1231 compressed_extents = compress_file_range(async_chunk);
1232 if (compressed_extents == 0) {
1233 btrfs_add_delayed_iput(async_chunk->inode);
1234 async_chunk->inode = NULL;
1239 * work queue call back to submit previously compressed pages
1241 static noinline void async_cow_submit(struct btrfs_work *work)
1243 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1245 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1246 unsigned long nr_pages;
1248 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1251 /* atomic_sub_return implies a barrier */
1252 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1254 cond_wake_up_nomb(&fs_info->async_submit_wait);
1257 * ->inode could be NULL if async_chunk_start has failed to compress,
1258 * in which case we don't have anything to submit, yet we need to
1259 * always adjust ->async_delalloc_pages as its paired with the init
1260 * happening in cow_file_range_async
1262 if (async_chunk->inode)
1263 submit_compressed_extents(async_chunk);
1266 static noinline void async_cow_free(struct btrfs_work *work)
1268 struct async_chunk *async_chunk;
1270 async_chunk = container_of(work, struct async_chunk, work);
1271 if (async_chunk->inode)
1272 btrfs_add_delayed_iput(async_chunk->inode);
1273 if (async_chunk->blkcg_css)
1274 css_put(async_chunk->blkcg_css);
1276 * Since the pointer to 'pending' is at the beginning of the array of
1277 * async_chunk's, freeing it ensures the whole array has been freed.
1279 if (atomic_dec_and_test(async_chunk->pending))
1280 kvfree(async_chunk->pending);
1283 static int cow_file_range_async(struct btrfs_inode *inode,
1284 struct writeback_control *wbc,
1285 struct page *locked_page,
1286 u64 start, u64 end, int *page_started,
1287 unsigned long *nr_written)
1289 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1290 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1291 struct async_cow *ctx;
1292 struct async_chunk *async_chunk;
1293 unsigned long nr_pages;
1295 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1297 bool should_compress;
1299 const unsigned int write_flags = wbc_to_write_flags(wbc);
1301 unlock_extent(&inode->io_tree, start, end);
1303 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1304 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1306 should_compress = false;
1308 should_compress = true;
1311 nofs_flag = memalloc_nofs_save();
1312 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1313 memalloc_nofs_restore(nofs_flag);
1316 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1317 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1318 EXTENT_DO_ACCOUNTING;
1319 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1320 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1322 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1323 clear_bits, page_ops);
1327 async_chunk = ctx->chunks;
1328 atomic_set(&ctx->num_chunks, num_chunks);
1330 for (i = 0; i < num_chunks; i++) {
1331 if (should_compress)
1332 cur_end = min(end, start + SZ_512K - 1);
1337 * igrab is called higher up in the call chain, take only the
1338 * lightweight reference for the callback lifetime
1340 ihold(&inode->vfs_inode);
1341 async_chunk[i].pending = &ctx->num_chunks;
1342 async_chunk[i].inode = &inode->vfs_inode;
1343 async_chunk[i].start = start;
1344 async_chunk[i].end = cur_end;
1345 async_chunk[i].write_flags = write_flags;
1346 INIT_LIST_HEAD(&async_chunk[i].extents);
1349 * The locked_page comes all the way from writepage and its
1350 * the original page we were actually given. As we spread
1351 * this large delalloc region across multiple async_chunk
1352 * structs, only the first struct needs a pointer to locked_page
1354 * This way we don't need racey decisions about who is supposed
1359 * Depending on the compressibility, the pages might or
1360 * might not go through async. We want all of them to
1361 * be accounted against wbc once. Let's do it here
1362 * before the paths diverge. wbc accounting is used
1363 * only for foreign writeback detection and doesn't
1364 * need full accuracy. Just account the whole thing
1365 * against the first page.
1367 wbc_account_cgroup_owner(wbc, locked_page,
1369 async_chunk[i].locked_page = locked_page;
1372 async_chunk[i].locked_page = NULL;
1375 if (blkcg_css != blkcg_root_css) {
1377 async_chunk[i].blkcg_css = blkcg_css;
1379 async_chunk[i].blkcg_css = NULL;
1382 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1383 async_cow_submit, async_cow_free);
1385 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1386 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1388 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1390 *nr_written += nr_pages;
1391 start = cur_end + 1;
1397 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1398 struct page *locked_page, u64 start,
1399 u64 end, int *page_started,
1400 unsigned long *nr_written)
1404 ret = cow_file_range(inode, locked_page, start, end, page_started,
1412 __set_page_dirty_nobuffers(locked_page);
1413 account_page_redirty(locked_page);
1414 extent_write_locked_range(&inode->vfs_inode, start, end, WB_SYNC_ALL);
1420 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1421 u64 bytenr, u64 num_bytes)
1424 struct btrfs_ordered_sum *sums;
1427 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1428 bytenr + num_bytes - 1, &list, 0);
1429 if (ret == 0 && list_empty(&list))
1432 while (!list_empty(&list)) {
1433 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1434 list_del(&sums->list);
1442 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1443 const u64 start, const u64 end,
1444 int *page_started, unsigned long *nr_written)
1446 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1447 const bool is_reloc_ino = (inode->root->root_key.objectid ==
1448 BTRFS_DATA_RELOC_TREE_OBJECTID);
1449 const u64 range_bytes = end + 1 - start;
1450 struct extent_io_tree *io_tree = &inode->io_tree;
1451 u64 range_start = start;
1455 * If EXTENT_NORESERVE is set it means that when the buffered write was
1456 * made we had not enough available data space and therefore we did not
1457 * reserve data space for it, since we though we could do NOCOW for the
1458 * respective file range (either there is prealloc extent or the inode
1459 * has the NOCOW bit set).
1461 * However when we need to fallback to COW mode (because for example the
1462 * block group for the corresponding extent was turned to RO mode by a
1463 * scrub or relocation) we need to do the following:
1465 * 1) We increment the bytes_may_use counter of the data space info.
1466 * If COW succeeds, it allocates a new data extent and after doing
1467 * that it decrements the space info's bytes_may_use counter and
1468 * increments its bytes_reserved counter by the same amount (we do
1469 * this at btrfs_add_reserved_bytes()). So we need to increment the
1470 * bytes_may_use counter to compensate (when space is reserved at
1471 * buffered write time, the bytes_may_use counter is incremented);
1473 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1474 * that if the COW path fails for any reason, it decrements (through
1475 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1476 * data space info, which we incremented in the step above.
1478 * If we need to fallback to cow and the inode corresponds to a free
1479 * space cache inode or an inode of the data relocation tree, we must
1480 * also increment bytes_may_use of the data space_info for the same
1481 * reason. Space caches and relocated data extents always get a prealloc
1482 * extent for them, however scrub or balance may have set the block
1483 * group that contains that extent to RO mode and therefore force COW
1484 * when starting writeback.
1486 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1487 EXTENT_NORESERVE, 0);
1488 if (count > 0 || is_space_ino || is_reloc_ino) {
1490 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1491 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1493 if (is_space_ino || is_reloc_ino)
1494 bytes = range_bytes;
1496 spin_lock(&sinfo->lock);
1497 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1498 spin_unlock(&sinfo->lock);
1501 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1505 return cow_file_range(inode, locked_page, start, end, page_started,
1510 * when nowcow writeback call back. This checks for snapshots or COW copies
1511 * of the extents that exist in the file, and COWs the file as required.
1513 * If no cow copies or snapshots exist, we write directly to the existing
1516 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1517 struct page *locked_page,
1518 const u64 start, const u64 end,
1520 unsigned long *nr_written)
1522 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1523 struct btrfs_root *root = inode->root;
1524 struct btrfs_path *path;
1525 u64 cow_start = (u64)-1;
1526 u64 cur_offset = start;
1528 bool check_prev = true;
1529 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1530 u64 ino = btrfs_ino(inode);
1532 u64 disk_bytenr = 0;
1533 const bool force = inode->flags & BTRFS_INODE_NODATACOW;
1535 path = btrfs_alloc_path();
1537 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1538 EXTENT_LOCKED | EXTENT_DELALLOC |
1539 EXTENT_DO_ACCOUNTING |
1540 EXTENT_DEFRAG, PAGE_UNLOCK |
1541 PAGE_START_WRITEBACK |
1542 PAGE_END_WRITEBACK);
1547 struct btrfs_key found_key;
1548 struct btrfs_file_extent_item *fi;
1549 struct extent_buffer *leaf;
1559 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1565 * If there is no extent for our range when doing the initial
1566 * search, then go back to the previous slot as it will be the
1567 * one containing the search offset
1569 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1570 leaf = path->nodes[0];
1571 btrfs_item_key_to_cpu(leaf, &found_key,
1572 path->slots[0] - 1);
1573 if (found_key.objectid == ino &&
1574 found_key.type == BTRFS_EXTENT_DATA_KEY)
1579 /* Go to next leaf if we have exhausted the current one */
1580 leaf = path->nodes[0];
1581 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1582 ret = btrfs_next_leaf(root, path);
1584 if (cow_start != (u64)-1)
1585 cur_offset = cow_start;
1590 leaf = path->nodes[0];
1593 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1595 /* Didn't find anything for our INO */
1596 if (found_key.objectid > ino)
1599 * Keep searching until we find an EXTENT_ITEM or there are no
1600 * more extents for this inode
1602 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1603 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1608 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1609 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1610 found_key.offset > end)
1614 * If the found extent starts after requested offset, then
1615 * adjust extent_end to be right before this extent begins
1617 if (found_key.offset > cur_offset) {
1618 extent_end = found_key.offset;
1624 * Found extent which begins before our range and potentially
1627 fi = btrfs_item_ptr(leaf, path->slots[0],
1628 struct btrfs_file_extent_item);
1629 extent_type = btrfs_file_extent_type(leaf, fi);
1631 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1632 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1633 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1634 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1635 extent_offset = btrfs_file_extent_offset(leaf, fi);
1636 extent_end = found_key.offset +
1637 btrfs_file_extent_num_bytes(leaf, fi);
1639 btrfs_file_extent_disk_num_bytes(leaf, fi);
1641 * If the extent we got ends before our current offset,
1642 * skip to the next extent.
1644 if (extent_end <= cur_offset) {
1649 if (disk_bytenr == 0)
1651 /* Skip compressed/encrypted/encoded extents */
1652 if (btrfs_file_extent_compression(leaf, fi) ||
1653 btrfs_file_extent_encryption(leaf, fi) ||
1654 btrfs_file_extent_other_encoding(leaf, fi))
1657 * If extent is created before the last volume's snapshot
1658 * this implies the extent is shared, hence we can't do
1659 * nocow. This is the same check as in
1660 * btrfs_cross_ref_exist but without calling
1661 * btrfs_search_slot.
1663 if (!freespace_inode &&
1664 btrfs_file_extent_generation(leaf, fi) <=
1665 btrfs_root_last_snapshot(&root->root_item))
1667 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1671 * The following checks can be expensive, as they need to
1672 * take other locks and do btree or rbtree searches, so
1673 * release the path to avoid blocking other tasks for too
1676 btrfs_release_path(path);
1678 ret = btrfs_cross_ref_exist(root, ino,
1680 extent_offset, disk_bytenr, false);
1683 * ret could be -EIO if the above fails to read
1687 if (cow_start != (u64)-1)
1688 cur_offset = cow_start;
1692 WARN_ON_ONCE(freespace_inode);
1695 disk_bytenr += extent_offset;
1696 disk_bytenr += cur_offset - found_key.offset;
1697 num_bytes = min(end + 1, extent_end) - cur_offset;
1699 * If there are pending snapshots for this root, we
1700 * fall into common COW way
1702 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1705 * force cow if csum exists in the range.
1706 * this ensure that csum for a given extent are
1707 * either valid or do not exist.
1709 ret = csum_exist_in_range(fs_info, disk_bytenr,
1713 * ret could be -EIO if the above fails to read
1717 if (cow_start != (u64)-1)
1718 cur_offset = cow_start;
1721 WARN_ON_ONCE(freespace_inode);
1724 /* If the extent's block group is RO, we must COW */
1725 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1728 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1729 extent_end = found_key.offset + ram_bytes;
1730 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1731 /* Skip extents outside of our requested range */
1732 if (extent_end <= start) {
1737 /* If this triggers then we have a memory corruption */
1742 * If nocow is false then record the beginning of the range
1743 * that needs to be COWed
1746 if (cow_start == (u64)-1)
1747 cow_start = cur_offset;
1748 cur_offset = extent_end;
1749 if (cur_offset > end)
1751 if (!path->nodes[0])
1758 * COW range from cow_start to found_key.offset - 1. As the key
1759 * will contain the beginning of the first extent that can be
1760 * NOCOW, following one which needs to be COW'ed
1762 if (cow_start != (u64)-1) {
1763 ret = fallback_to_cow(inode, locked_page,
1764 cow_start, found_key.offset - 1,
1765 page_started, nr_written);
1768 cow_start = (u64)-1;
1771 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1772 u64 orig_start = found_key.offset - extent_offset;
1773 struct extent_map *em;
1775 em = create_io_em(inode, cur_offset, num_bytes,
1777 disk_bytenr, /* block_start */
1778 num_bytes, /* block_len */
1779 disk_num_bytes, /* orig_block_len */
1780 ram_bytes, BTRFS_COMPRESS_NONE,
1781 BTRFS_ORDERED_PREALLOC);
1786 free_extent_map(em);
1787 ret = btrfs_add_ordered_extent(inode, cur_offset,
1788 disk_bytenr, num_bytes,
1790 BTRFS_ORDERED_PREALLOC);
1792 btrfs_drop_extent_cache(inode, cur_offset,
1793 cur_offset + num_bytes - 1,
1798 ret = btrfs_add_ordered_extent(inode, cur_offset,
1799 disk_bytenr, num_bytes,
1801 BTRFS_ORDERED_NOCOW);
1807 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1810 if (root->root_key.objectid ==
1811 BTRFS_DATA_RELOC_TREE_OBJECTID)
1813 * Error handled later, as we must prevent
1814 * extent_clear_unlock_delalloc() in error handler
1815 * from freeing metadata of created ordered extent.
1817 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1820 extent_clear_unlock_delalloc(inode, cur_offset,
1821 cur_offset + num_bytes - 1,
1822 locked_page, EXTENT_LOCKED |
1824 EXTENT_CLEAR_DATA_RESV,
1825 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1827 cur_offset = extent_end;
1830 * btrfs_reloc_clone_csums() error, now we're OK to call error
1831 * handler, as metadata for created ordered extent will only
1832 * be freed by btrfs_finish_ordered_io().
1836 if (cur_offset > end)
1839 btrfs_release_path(path);
1841 if (cur_offset <= end && cow_start == (u64)-1)
1842 cow_start = cur_offset;
1844 if (cow_start != (u64)-1) {
1846 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1847 page_started, nr_written);
1854 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1856 if (ret && cur_offset < end)
1857 extent_clear_unlock_delalloc(inode, cur_offset, end,
1858 locked_page, EXTENT_LOCKED |
1859 EXTENT_DELALLOC | EXTENT_DEFRAG |
1860 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1861 PAGE_START_WRITEBACK |
1862 PAGE_END_WRITEBACK);
1863 btrfs_free_path(path);
1867 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
1869 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
1870 if (inode->defrag_bytes &&
1871 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
1880 * Function to process delayed allocation (create CoW) for ranges which are
1881 * being touched for the first time.
1883 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1884 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1885 struct writeback_control *wbc)
1888 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
1890 if (should_nocow(inode, start, end)) {
1892 ret = run_delalloc_nocow(inode, locked_page, start, end,
1893 page_started, nr_written);
1894 } else if (!inode_can_compress(inode) ||
1895 !inode_need_compress(inode, start, end)) {
1897 ret = run_delalloc_zoned(inode, locked_page, start, end,
1898 page_started, nr_written);
1900 ret = cow_file_range(inode, locked_page, start, end,
1901 page_started, nr_written, 1);
1903 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1904 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1905 page_started, nr_written);
1908 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1913 void btrfs_split_delalloc_extent(struct inode *inode,
1914 struct extent_state *orig, u64 split)
1918 /* not delalloc, ignore it */
1919 if (!(orig->state & EXTENT_DELALLOC))
1922 size = orig->end - orig->start + 1;
1923 if (size > BTRFS_MAX_EXTENT_SIZE) {
1928 * See the explanation in btrfs_merge_delalloc_extent, the same
1929 * applies here, just in reverse.
1931 new_size = orig->end - split + 1;
1932 num_extents = count_max_extents(new_size);
1933 new_size = split - orig->start;
1934 num_extents += count_max_extents(new_size);
1935 if (count_max_extents(size) >= num_extents)
1939 spin_lock(&BTRFS_I(inode)->lock);
1940 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1941 spin_unlock(&BTRFS_I(inode)->lock);
1945 * Handle merged delayed allocation extents so we can keep track of new extents
1946 * that are just merged onto old extents, such as when we are doing sequential
1947 * writes, so we can properly account for the metadata space we'll need.
1949 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1950 struct extent_state *other)
1952 u64 new_size, old_size;
1955 /* not delalloc, ignore it */
1956 if (!(other->state & EXTENT_DELALLOC))
1959 if (new->start > other->start)
1960 new_size = new->end - other->start + 1;
1962 new_size = other->end - new->start + 1;
1964 /* we're not bigger than the max, unreserve the space and go */
1965 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1966 spin_lock(&BTRFS_I(inode)->lock);
1967 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1968 spin_unlock(&BTRFS_I(inode)->lock);
1973 * We have to add up either side to figure out how many extents were
1974 * accounted for before we merged into one big extent. If the number of
1975 * extents we accounted for is <= the amount we need for the new range
1976 * then we can return, otherwise drop. Think of it like this
1980 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1981 * need 2 outstanding extents, on one side we have 1 and the other side
1982 * we have 1 so they are == and we can return. But in this case
1984 * [MAX_SIZE+4k][MAX_SIZE+4k]
1986 * Each range on their own accounts for 2 extents, but merged together
1987 * they are only 3 extents worth of accounting, so we need to drop in
1990 old_size = other->end - other->start + 1;
1991 num_extents = count_max_extents(old_size);
1992 old_size = new->end - new->start + 1;
1993 num_extents += count_max_extents(old_size);
1994 if (count_max_extents(new_size) >= num_extents)
1997 spin_lock(&BTRFS_I(inode)->lock);
1998 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1999 spin_unlock(&BTRFS_I(inode)->lock);
2002 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2003 struct inode *inode)
2005 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2007 spin_lock(&root->delalloc_lock);
2008 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2009 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2010 &root->delalloc_inodes);
2011 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2012 &BTRFS_I(inode)->runtime_flags);
2013 root->nr_delalloc_inodes++;
2014 if (root->nr_delalloc_inodes == 1) {
2015 spin_lock(&fs_info->delalloc_root_lock);
2016 BUG_ON(!list_empty(&root->delalloc_root));
2017 list_add_tail(&root->delalloc_root,
2018 &fs_info->delalloc_roots);
2019 spin_unlock(&fs_info->delalloc_root_lock);
2022 spin_unlock(&root->delalloc_lock);
2026 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2027 struct btrfs_inode *inode)
2029 struct btrfs_fs_info *fs_info = root->fs_info;
2031 if (!list_empty(&inode->delalloc_inodes)) {
2032 list_del_init(&inode->delalloc_inodes);
2033 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2034 &inode->runtime_flags);
2035 root->nr_delalloc_inodes--;
2036 if (!root->nr_delalloc_inodes) {
2037 ASSERT(list_empty(&root->delalloc_inodes));
2038 spin_lock(&fs_info->delalloc_root_lock);
2039 BUG_ON(list_empty(&root->delalloc_root));
2040 list_del_init(&root->delalloc_root);
2041 spin_unlock(&fs_info->delalloc_root_lock);
2046 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2047 struct btrfs_inode *inode)
2049 spin_lock(&root->delalloc_lock);
2050 __btrfs_del_delalloc_inode(root, inode);
2051 spin_unlock(&root->delalloc_lock);
2055 * Properly track delayed allocation bytes in the inode and to maintain the
2056 * list of inodes that have pending delalloc work to be done.
2058 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2061 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2063 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2066 * set_bit and clear bit hooks normally require _irqsave/restore
2067 * but in this case, we are only testing for the DELALLOC
2068 * bit, which is only set or cleared with irqs on
2070 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2071 struct btrfs_root *root = BTRFS_I(inode)->root;
2072 u64 len = state->end + 1 - state->start;
2073 u32 num_extents = count_max_extents(len);
2074 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2076 spin_lock(&BTRFS_I(inode)->lock);
2077 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2078 spin_unlock(&BTRFS_I(inode)->lock);
2080 /* For sanity tests */
2081 if (btrfs_is_testing(fs_info))
2084 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2085 fs_info->delalloc_batch);
2086 spin_lock(&BTRFS_I(inode)->lock);
2087 BTRFS_I(inode)->delalloc_bytes += len;
2088 if (*bits & EXTENT_DEFRAG)
2089 BTRFS_I(inode)->defrag_bytes += len;
2090 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2091 &BTRFS_I(inode)->runtime_flags))
2092 btrfs_add_delalloc_inodes(root, inode);
2093 spin_unlock(&BTRFS_I(inode)->lock);
2096 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2097 (*bits & EXTENT_DELALLOC_NEW)) {
2098 spin_lock(&BTRFS_I(inode)->lock);
2099 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2101 spin_unlock(&BTRFS_I(inode)->lock);
2106 * Once a range is no longer delalloc this function ensures that proper
2107 * accounting happens.
2109 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2110 struct extent_state *state, unsigned *bits)
2112 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2113 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2114 u64 len = state->end + 1 - state->start;
2115 u32 num_extents = count_max_extents(len);
2117 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2118 spin_lock(&inode->lock);
2119 inode->defrag_bytes -= len;
2120 spin_unlock(&inode->lock);
2124 * set_bit and clear bit hooks normally require _irqsave/restore
2125 * but in this case, we are only testing for the DELALLOC
2126 * bit, which is only set or cleared with irqs on
2128 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2129 struct btrfs_root *root = inode->root;
2130 bool do_list = !btrfs_is_free_space_inode(inode);
2132 spin_lock(&inode->lock);
2133 btrfs_mod_outstanding_extents(inode, -num_extents);
2134 spin_unlock(&inode->lock);
2137 * We don't reserve metadata space for space cache inodes so we
2138 * don't need to call delalloc_release_metadata if there is an
2141 if (*bits & EXTENT_CLEAR_META_RESV &&
2142 root != fs_info->tree_root)
2143 btrfs_delalloc_release_metadata(inode, len, false);
2145 /* For sanity tests. */
2146 if (btrfs_is_testing(fs_info))
2149 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2150 do_list && !(state->state & EXTENT_NORESERVE) &&
2151 (*bits & EXTENT_CLEAR_DATA_RESV))
2152 btrfs_free_reserved_data_space_noquota(fs_info, len);
2154 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2155 fs_info->delalloc_batch);
2156 spin_lock(&inode->lock);
2157 inode->delalloc_bytes -= len;
2158 if (do_list && inode->delalloc_bytes == 0 &&
2159 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2160 &inode->runtime_flags))
2161 btrfs_del_delalloc_inode(root, inode);
2162 spin_unlock(&inode->lock);
2165 if ((state->state & EXTENT_DELALLOC_NEW) &&
2166 (*bits & EXTENT_DELALLOC_NEW)) {
2167 spin_lock(&inode->lock);
2168 ASSERT(inode->new_delalloc_bytes >= len);
2169 inode->new_delalloc_bytes -= len;
2170 if (*bits & EXTENT_ADD_INODE_BYTES)
2171 inode_add_bytes(&inode->vfs_inode, len);
2172 spin_unlock(&inode->lock);
2177 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2178 * in a chunk's stripe. This function ensures that bios do not span a
2181 * @page - The page we are about to add to the bio
2182 * @size - size we want to add to the bio
2183 * @bio - bio we want to ensure is smaller than a stripe
2184 * @bio_flags - flags of the bio
2186 * return 1 if page cannot be added to the bio
2187 * return 0 if page can be added to the bio
2188 * return error otherwise
2190 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2191 unsigned long bio_flags)
2193 struct inode *inode = page->mapping->host;
2194 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2195 u64 logical = bio->bi_iter.bi_sector << 9;
2196 struct extent_map *em;
2200 struct btrfs_io_geometry geom;
2202 if (bio_flags & EXTENT_BIO_COMPRESSED)
2205 length = bio->bi_iter.bi_size;
2206 map_length = length;
2207 em = btrfs_get_chunk_map(fs_info, logical, map_length);
2210 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), logical,
2215 if (geom.len < length + size)
2218 free_extent_map(em);
2223 * in order to insert checksums into the metadata in large chunks,
2224 * we wait until bio submission time. All the pages in the bio are
2225 * checksummed and sums are attached onto the ordered extent record.
2227 * At IO completion time the cums attached on the ordered extent record
2228 * are inserted into the btree
2230 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2231 u64 dio_file_offset)
2233 return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2236 bool btrfs_bio_fits_in_ordered_extent(struct page *page, struct bio *bio,
2239 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
2240 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2241 struct btrfs_ordered_extent *ordered;
2242 u64 len = bio->bi_iter.bi_size + size;
2245 ASSERT(btrfs_is_zoned(fs_info));
2246 ASSERT(fs_info->max_zone_append_size > 0);
2247 ASSERT(bio_op(bio) == REQ_OP_ZONE_APPEND);
2249 /* Ordered extent not yet created, so we're good */
2250 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
2254 if ((bio->bi_iter.bi_sector << SECTOR_SHIFT) + len >
2255 ordered->disk_bytenr + ordered->disk_num_bytes)
2258 btrfs_put_ordered_extent(ordered);
2263 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2264 struct bio *bio, loff_t file_offset)
2266 struct btrfs_ordered_extent *ordered;
2267 struct extent_map *em = NULL, *em_new = NULL;
2268 struct extent_map_tree *em_tree = &inode->extent_tree;
2269 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2270 u64 len = bio->bi_iter.bi_size;
2271 u64 end = start + len;
2276 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2277 if (WARN_ON_ONCE(!ordered))
2278 return BLK_STS_IOERR;
2280 /* No need to split */
2281 if (ordered->disk_num_bytes == len)
2284 /* We cannot split once end_bio'd ordered extent */
2285 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2290 /* We cannot split a compressed ordered extent */
2291 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2296 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2297 /* bio must be in one ordered extent */
2298 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2303 /* Checksum list should be empty */
2304 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2309 pre = start - ordered->disk_bytenr;
2310 post = ordered_end - end;
2312 ret = btrfs_split_ordered_extent(ordered, pre, post);
2316 read_lock(&em_tree->lock);
2317 em = lookup_extent_mapping(em_tree, ordered->file_offset, len);
2319 read_unlock(&em_tree->lock);
2323 read_unlock(&em_tree->lock);
2325 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2327 * We cannot reuse em_new here but have to create a new one, as
2328 * unpin_extent_cache() expects the start of the extent map to be the
2329 * logical offset of the file, which does not hold true anymore after
2332 em_new = create_io_em(inode, em->start + pre, len,
2333 em->start + pre, em->block_start + pre, len,
2334 len, len, BTRFS_COMPRESS_NONE,
2335 BTRFS_ORDERED_REGULAR);
2336 if (IS_ERR(em_new)) {
2337 ret = PTR_ERR(em_new);
2340 free_extent_map(em_new);
2343 free_extent_map(em);
2344 btrfs_put_ordered_extent(ordered);
2346 return errno_to_blk_status(ret);
2350 * extent_io.c submission hook. This does the right thing for csum calculation
2351 * on write, or reading the csums from the tree before a read.
2353 * Rules about async/sync submit,
2354 * a) read: sync submit
2356 * b) write without checksum: sync submit
2358 * c) write with checksum:
2359 * c-1) if bio is issued by fsync: sync submit
2360 * (sync_writers != 0)
2362 * c-2) if root is reloc root: sync submit
2363 * (only in case of buffered IO)
2365 * c-3) otherwise: async submit
2367 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2368 int mirror_num, unsigned long bio_flags)
2371 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2372 struct btrfs_root *root = BTRFS_I(inode)->root;
2373 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2374 blk_status_t ret = 0;
2376 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2378 skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2379 !fs_info->csum_root;
2381 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2382 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2384 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2385 struct page *page = bio_first_bvec_all(bio)->bv_page;
2386 loff_t file_offset = page_offset(page);
2388 ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2393 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2394 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2398 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2399 ret = btrfs_submit_compressed_read(inode, bio,
2405 * Lookup bio sums does extra checks around whether we
2406 * need to csum or not, which is why we ignore skip_sum
2409 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2414 } else if (async && !skip_sum) {
2415 /* csum items have already been cloned */
2416 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2418 /* we're doing a write, do the async checksumming */
2419 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2420 0, btrfs_submit_bio_start);
2422 } else if (!skip_sum) {
2423 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2429 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2433 bio->bi_status = ret;
2440 * given a list of ordered sums record them in the inode. This happens
2441 * at IO completion time based on sums calculated at bio submission time.
2443 static int add_pending_csums(struct btrfs_trans_handle *trans,
2444 struct list_head *list)
2446 struct btrfs_ordered_sum *sum;
2449 list_for_each_entry(sum, list, list) {
2450 trans->adding_csums = true;
2451 ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2452 trans->adding_csums = false;
2459 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2462 struct extent_state **cached_state)
2464 u64 search_start = start;
2465 const u64 end = start + len - 1;
2467 while (search_start < end) {
2468 const u64 search_len = end - search_start + 1;
2469 struct extent_map *em;
2473 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2477 if (em->block_start != EXTENT_MAP_HOLE)
2481 if (em->start < search_start)
2482 em_len -= search_start - em->start;
2483 if (em_len > search_len)
2484 em_len = search_len;
2486 ret = set_extent_bit(&inode->io_tree, search_start,
2487 search_start + em_len - 1,
2488 EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2491 search_start = extent_map_end(em);
2492 free_extent_map(em);
2499 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2500 unsigned int extra_bits,
2501 struct extent_state **cached_state)
2503 WARN_ON(PAGE_ALIGNED(end));
2505 if (start >= i_size_read(&inode->vfs_inode) &&
2506 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2508 * There can't be any extents following eof in this case so just
2509 * set the delalloc new bit for the range directly.
2511 extra_bits |= EXTENT_DELALLOC_NEW;
2515 ret = btrfs_find_new_delalloc_bytes(inode, start,
2522 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2526 /* see btrfs_writepage_start_hook for details on why this is required */
2527 struct btrfs_writepage_fixup {
2529 struct inode *inode;
2530 struct btrfs_work work;
2533 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2535 struct btrfs_writepage_fixup *fixup;
2536 struct btrfs_ordered_extent *ordered;
2537 struct extent_state *cached_state = NULL;
2538 struct extent_changeset *data_reserved = NULL;
2540 struct btrfs_inode *inode;
2544 bool free_delalloc_space = true;
2546 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2548 inode = BTRFS_I(fixup->inode);
2549 page_start = page_offset(page);
2550 page_end = page_offset(page) + PAGE_SIZE - 1;
2553 * This is similar to page_mkwrite, we need to reserve the space before
2554 * we take the page lock.
2556 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2562 * Before we queued this fixup, we took a reference on the page.
2563 * page->mapping may go NULL, but it shouldn't be moved to a different
2566 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2568 * Unfortunately this is a little tricky, either
2570 * 1) We got here and our page had already been dealt with and
2571 * we reserved our space, thus ret == 0, so we need to just
2572 * drop our space reservation and bail. This can happen the
2573 * first time we come into the fixup worker, or could happen
2574 * while waiting for the ordered extent.
2575 * 2) Our page was already dealt with, but we happened to get an
2576 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2577 * this case we obviously don't have anything to release, but
2578 * because the page was already dealt with we don't want to
2579 * mark the page with an error, so make sure we're resetting
2580 * ret to 0. This is why we have this check _before_ the ret
2581 * check, because we do not want to have a surprise ENOSPC
2582 * when the page was already properly dealt with.
2585 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2586 btrfs_delalloc_release_space(inode, data_reserved,
2587 page_start, PAGE_SIZE,
2595 * We can't mess with the page state unless it is locked, so now that
2596 * it is locked bail if we failed to make our space reservation.
2601 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2603 /* already ordered? We're done */
2604 if (PagePrivate2(page))
2607 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2609 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2612 btrfs_start_ordered_extent(ordered, 1);
2613 btrfs_put_ordered_extent(ordered);
2617 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2623 * Everything went as planned, we're now the owner of a dirty page with
2624 * delayed allocation bits set and space reserved for our COW
2627 * The page was dirty when we started, nothing should have cleaned it.
2629 BUG_ON(!PageDirty(page));
2630 free_delalloc_space = false;
2632 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2633 if (free_delalloc_space)
2634 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2636 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2641 * We hit ENOSPC or other errors. Update the mapping and page
2642 * to reflect the errors and clean the page.
2644 mapping_set_error(page->mapping, ret);
2645 end_extent_writepage(page, ret, page_start, page_end);
2646 clear_page_dirty_for_io(page);
2649 ClearPageChecked(page);
2653 extent_changeset_free(data_reserved);
2655 * As a precaution, do a delayed iput in case it would be the last iput
2656 * that could need flushing space. Recursing back to fixup worker would
2659 btrfs_add_delayed_iput(&inode->vfs_inode);
2663 * There are a few paths in the higher layers of the kernel that directly
2664 * set the page dirty bit without asking the filesystem if it is a
2665 * good idea. This causes problems because we want to make sure COW
2666 * properly happens and the data=ordered rules are followed.
2668 * In our case any range that doesn't have the ORDERED bit set
2669 * hasn't been properly setup for IO. We kick off an async process
2670 * to fix it up. The async helper will wait for ordered extents, set
2671 * the delalloc bit and make it safe to write the page.
2673 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2675 struct inode *inode = page->mapping->host;
2676 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2677 struct btrfs_writepage_fixup *fixup;
2679 /* this page is properly in the ordered list */
2680 if (TestClearPagePrivate2(page))
2684 * PageChecked is set below when we create a fixup worker for this page,
2685 * don't try to create another one if we're already PageChecked()
2687 * The extent_io writepage code will redirty the page if we send back
2690 if (PageChecked(page))
2693 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2698 * We are already holding a reference to this inode from
2699 * write_cache_pages. We need to hold it because the space reservation
2700 * takes place outside of the page lock, and we can't trust
2701 * page->mapping outside of the page lock.
2704 SetPageChecked(page);
2706 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2708 fixup->inode = inode;
2709 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2714 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2715 struct btrfs_inode *inode, u64 file_pos,
2716 struct btrfs_file_extent_item *stack_fi,
2717 const bool update_inode_bytes,
2718 u64 qgroup_reserved)
2720 struct btrfs_root *root = inode->root;
2721 const u64 sectorsize = root->fs_info->sectorsize;
2722 struct btrfs_path *path;
2723 struct extent_buffer *leaf;
2724 struct btrfs_key ins;
2725 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2726 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2727 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2728 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2729 struct btrfs_drop_extents_args drop_args = { 0 };
2732 path = btrfs_alloc_path();
2737 * we may be replacing one extent in the tree with another.
2738 * The new extent is pinned in the extent map, and we don't want
2739 * to drop it from the cache until it is completely in the btree.
2741 * So, tell btrfs_drop_extents to leave this extent in the cache.
2742 * the caller is expected to unpin it and allow it to be merged
2745 drop_args.path = path;
2746 drop_args.start = file_pos;
2747 drop_args.end = file_pos + num_bytes;
2748 drop_args.replace_extent = true;
2749 drop_args.extent_item_size = sizeof(*stack_fi);
2750 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2754 if (!drop_args.extent_inserted) {
2755 ins.objectid = btrfs_ino(inode);
2756 ins.offset = file_pos;
2757 ins.type = BTRFS_EXTENT_DATA_KEY;
2759 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2764 leaf = path->nodes[0];
2765 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2766 write_extent_buffer(leaf, stack_fi,
2767 btrfs_item_ptr_offset(leaf, path->slots[0]),
2768 sizeof(struct btrfs_file_extent_item));
2770 btrfs_mark_buffer_dirty(leaf);
2771 btrfs_release_path(path);
2774 * If we dropped an inline extent here, we know the range where it is
2775 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2776 * number of bytes only for that range contaning the inline extent.
2777 * The remaining of the range will be processed when clearning the
2778 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2780 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2781 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2783 inline_size = drop_args.bytes_found - inline_size;
2784 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2785 drop_args.bytes_found -= inline_size;
2786 num_bytes -= sectorsize;
2789 if (update_inode_bytes)
2790 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2792 ins.objectid = disk_bytenr;
2793 ins.offset = disk_num_bytes;
2794 ins.type = BTRFS_EXTENT_ITEM_KEY;
2796 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2800 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2801 file_pos, qgroup_reserved, &ins);
2803 btrfs_free_path(path);
2808 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2811 struct btrfs_block_group *cache;
2813 cache = btrfs_lookup_block_group(fs_info, start);
2816 spin_lock(&cache->lock);
2817 cache->delalloc_bytes -= len;
2818 spin_unlock(&cache->lock);
2820 btrfs_put_block_group(cache);
2823 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2824 struct btrfs_ordered_extent *oe)
2826 struct btrfs_file_extent_item stack_fi;
2828 bool update_inode_bytes;
2830 memset(&stack_fi, 0, sizeof(stack_fi));
2831 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2832 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2833 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2834 oe->disk_num_bytes);
2835 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2836 logical_len = oe->truncated_len;
2838 logical_len = oe->num_bytes;
2839 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2840 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2841 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2842 /* Encryption and other encoding is reserved and all 0 */
2845 * For delalloc, when completing an ordered extent we update the inode's
2846 * bytes when clearing the range in the inode's io tree, so pass false
2847 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
2848 * except if the ordered extent was truncated.
2850 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
2851 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
2853 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
2854 oe->file_offset, &stack_fi,
2855 update_inode_bytes, oe->qgroup_rsv);
2859 * As ordered data IO finishes, this gets called so we can finish
2860 * an ordered extent if the range of bytes in the file it covers are
2863 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2865 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
2866 struct btrfs_root *root = inode->root;
2867 struct btrfs_fs_info *fs_info = root->fs_info;
2868 struct btrfs_trans_handle *trans = NULL;
2869 struct extent_io_tree *io_tree = &inode->io_tree;
2870 struct extent_state *cached_state = NULL;
2872 int compress_type = 0;
2874 u64 logical_len = ordered_extent->num_bytes;
2875 bool freespace_inode;
2876 bool truncated = false;
2877 bool clear_reserved_extent = true;
2878 unsigned int clear_bits = EXTENT_DEFRAG;
2880 start = ordered_extent->file_offset;
2881 end = start + ordered_extent->num_bytes - 1;
2883 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2884 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2885 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2886 clear_bits |= EXTENT_DELALLOC_NEW;
2888 freespace_inode = btrfs_is_free_space_inode(inode);
2890 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2895 if (ordered_extent->disk)
2896 btrfs_rewrite_logical_zoned(ordered_extent);
2898 btrfs_free_io_failure_record(inode, start, end);
2900 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2902 logical_len = ordered_extent->truncated_len;
2903 /* Truncated the entire extent, don't bother adding */
2908 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2909 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2911 btrfs_inode_safe_disk_i_size_write(inode, 0);
2912 if (freespace_inode)
2913 trans = btrfs_join_transaction_spacecache(root);
2915 trans = btrfs_join_transaction(root);
2916 if (IS_ERR(trans)) {
2917 ret = PTR_ERR(trans);
2921 trans->block_rsv = &inode->block_rsv;
2922 ret = btrfs_update_inode_fallback(trans, root, inode);
2923 if (ret) /* -ENOMEM or corruption */
2924 btrfs_abort_transaction(trans, ret);
2928 clear_bits |= EXTENT_LOCKED;
2929 lock_extent_bits(io_tree, start, end, &cached_state);
2931 if (freespace_inode)
2932 trans = btrfs_join_transaction_spacecache(root);
2934 trans = btrfs_join_transaction(root);
2935 if (IS_ERR(trans)) {
2936 ret = PTR_ERR(trans);
2941 trans->block_rsv = &inode->block_rsv;
2943 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2944 compress_type = ordered_extent->compress_type;
2945 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2946 BUG_ON(compress_type);
2947 ret = btrfs_mark_extent_written(trans, inode,
2948 ordered_extent->file_offset,
2949 ordered_extent->file_offset +
2952 BUG_ON(root == fs_info->tree_root);
2953 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
2955 clear_reserved_extent = false;
2956 btrfs_release_delalloc_bytes(fs_info,
2957 ordered_extent->disk_bytenr,
2958 ordered_extent->disk_num_bytes);
2961 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
2962 ordered_extent->num_bytes, trans->transid);
2964 btrfs_abort_transaction(trans, ret);
2968 ret = add_pending_csums(trans, &ordered_extent->list);
2970 btrfs_abort_transaction(trans, ret);
2975 * If this is a new delalloc range, clear its new delalloc flag to
2976 * update the inode's number of bytes. This needs to be done first
2977 * before updating the inode item.
2979 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
2980 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
2981 clear_extent_bit(&inode->io_tree, start, end,
2982 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
2983 0, 0, &cached_state);
2985 btrfs_inode_safe_disk_i_size_write(inode, 0);
2986 ret = btrfs_update_inode_fallback(trans, root, inode);
2987 if (ret) { /* -ENOMEM or corruption */
2988 btrfs_abort_transaction(trans, ret);
2993 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
2994 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2998 btrfs_end_transaction(trans);
3000 if (ret || truncated) {
3001 u64 unwritten_start = start;
3004 unwritten_start += logical_len;
3005 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3007 /* Drop the cache for the part of the extent we didn't write. */
3008 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3011 * If the ordered extent had an IOERR or something else went
3012 * wrong we need to return the space for this ordered extent
3013 * back to the allocator. We only free the extent in the
3014 * truncated case if we didn't write out the extent at all.
3016 * If we made it past insert_reserved_file_extent before we
3017 * errored out then we don't need to do this as the accounting
3018 * has already been done.
3020 if ((ret || !logical_len) &&
3021 clear_reserved_extent &&
3022 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3023 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3025 * Discard the range before returning it back to the
3028 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3029 btrfs_discard_extent(fs_info,
3030 ordered_extent->disk_bytenr,
3031 ordered_extent->disk_num_bytes,
3033 btrfs_free_reserved_extent(fs_info,
3034 ordered_extent->disk_bytenr,
3035 ordered_extent->disk_num_bytes, 1);
3040 * This needs to be done to make sure anybody waiting knows we are done
3041 * updating everything for this ordered extent.
3043 btrfs_remove_ordered_extent(inode, ordered_extent);
3046 btrfs_put_ordered_extent(ordered_extent);
3047 /* once for the tree */
3048 btrfs_put_ordered_extent(ordered_extent);
3053 static void finish_ordered_fn(struct btrfs_work *work)
3055 struct btrfs_ordered_extent *ordered_extent;
3056 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3057 btrfs_finish_ordered_io(ordered_extent);
3060 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3061 u64 end, int uptodate)
3063 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3064 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3065 struct btrfs_ordered_extent *ordered_extent = NULL;
3066 struct btrfs_workqueue *wq;
3068 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3070 ClearPagePrivate2(page);
3071 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3072 end - start + 1, uptodate))
3075 if (btrfs_is_free_space_inode(inode))
3076 wq = fs_info->endio_freespace_worker;
3078 wq = fs_info->endio_write_workers;
3080 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
3081 btrfs_queue_work(wq, &ordered_extent->work);
3085 * check_data_csum - verify checksum of one sector of uncompressed data
3087 * @io_bio: btrfs_io_bio which contains the csum
3088 * @bio_offset: offset to the beginning of the bio (in bytes)
3089 * @page: page where is the data to be verified
3090 * @pgoff: offset inside the page
3091 * @start: logical offset in the file
3093 * The length of such check is always one sector size.
3095 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
3096 u32 bio_offset, struct page *page, u32 pgoff,
3099 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3100 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3102 u32 len = fs_info->sectorsize;
3103 const u32 csum_size = fs_info->csum_size;
3104 unsigned int offset_sectors;
3106 u8 csum[BTRFS_CSUM_SIZE];
3108 ASSERT(pgoff + len <= PAGE_SIZE);
3110 offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3111 csum_expected = ((u8 *)io_bio->csum) + offset_sectors * csum_size;
3113 kaddr = kmap_atomic(page);
3114 shash->tfm = fs_info->csum_shash;
3116 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3118 if (memcmp(csum, csum_expected, csum_size))
3121 kunmap_atomic(kaddr);
3124 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3125 io_bio->mirror_num);
3127 btrfs_dev_stat_inc_and_print(io_bio->device,
3128 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3129 memset(kaddr + pgoff, 1, len);
3130 flush_dcache_page(page);
3131 kunmap_atomic(kaddr);
3136 * When reads are done, we need to check csums to verify the data is correct.
3137 * if there's a match, we allow the bio to finish. If not, the code in
3138 * extent_io.c will try to find good copies for us.
3140 * @bio_offset: offset to the beginning of the bio (in bytes)
3141 * @start: file offset of the range start
3142 * @end: file offset of the range end (inclusive)
3143 * @mirror: mirror number
3145 int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u32 bio_offset,
3146 struct page *page, u64 start, u64 end, int mirror)
3148 struct inode *inode = page->mapping->host;
3149 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3150 struct btrfs_root *root = BTRFS_I(inode)->root;
3151 const u32 sectorsize = root->fs_info->sectorsize;
3154 if (PageChecked(page)) {
3155 ClearPageChecked(page);
3159 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3162 if (!root->fs_info->csum_root)
3165 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3166 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3167 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3171 ASSERT(page_offset(page) <= start &&
3172 end <= page_offset(page) + PAGE_SIZE - 1);
3173 for (pg_off = offset_in_page(start);
3174 pg_off < offset_in_page(end);
3175 pg_off += sectorsize, bio_offset += sectorsize) {
3178 ret = check_data_csum(inode, io_bio, bio_offset, page, pg_off,
3179 page_offset(page) + pg_off);
3187 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3189 * @inode: The inode we want to perform iput on
3191 * This function uses the generic vfs_inode::i_count to track whether we should
3192 * just decrement it (in case it's > 1) or if this is the last iput then link
3193 * the inode to the delayed iput machinery. Delayed iputs are processed at
3194 * transaction commit time/superblock commit/cleaner kthread.
3196 void btrfs_add_delayed_iput(struct inode *inode)
3198 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3199 struct btrfs_inode *binode = BTRFS_I(inode);
3201 if (atomic_add_unless(&inode->i_count, -1, 1))
3204 atomic_inc(&fs_info->nr_delayed_iputs);
3205 spin_lock(&fs_info->delayed_iput_lock);
3206 ASSERT(list_empty(&binode->delayed_iput));
3207 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3208 spin_unlock(&fs_info->delayed_iput_lock);
3209 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3210 wake_up_process(fs_info->cleaner_kthread);
3213 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3214 struct btrfs_inode *inode)
3216 list_del_init(&inode->delayed_iput);
3217 spin_unlock(&fs_info->delayed_iput_lock);
3218 iput(&inode->vfs_inode);
3219 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3220 wake_up(&fs_info->delayed_iputs_wait);
3221 spin_lock(&fs_info->delayed_iput_lock);
3224 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3225 struct btrfs_inode *inode)
3227 if (!list_empty(&inode->delayed_iput)) {
3228 spin_lock(&fs_info->delayed_iput_lock);
3229 if (!list_empty(&inode->delayed_iput))
3230 run_delayed_iput_locked(fs_info, inode);
3231 spin_unlock(&fs_info->delayed_iput_lock);
3235 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3238 spin_lock(&fs_info->delayed_iput_lock);
3239 while (!list_empty(&fs_info->delayed_iputs)) {
3240 struct btrfs_inode *inode;
3242 inode = list_first_entry(&fs_info->delayed_iputs,
3243 struct btrfs_inode, delayed_iput);
3244 run_delayed_iput_locked(fs_info, inode);
3246 spin_unlock(&fs_info->delayed_iput_lock);
3250 * Wait for flushing all delayed iputs
3252 * @fs_info: the filesystem
3254 * This will wait on any delayed iputs that are currently running with KILLABLE
3255 * set. Once they are all done running we will return, unless we are killed in
3256 * which case we return EINTR. This helps in user operations like fallocate etc
3257 * that might get blocked on the iputs.
3259 * Return EINTR if we were killed, 0 if nothing's pending
3261 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3263 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3264 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3271 * This creates an orphan entry for the given inode in case something goes wrong
3272 * in the middle of an unlink.
3274 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3275 struct btrfs_inode *inode)
3279 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3280 if (ret && ret != -EEXIST) {
3281 btrfs_abort_transaction(trans, ret);
3289 * We have done the delete so we can go ahead and remove the orphan item for
3290 * this particular inode.
3292 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3293 struct btrfs_inode *inode)
3295 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3299 * this cleans up any orphans that may be left on the list from the last use
3302 int btrfs_orphan_cleanup(struct btrfs_root *root)
3304 struct btrfs_fs_info *fs_info = root->fs_info;
3305 struct btrfs_path *path;
3306 struct extent_buffer *leaf;
3307 struct btrfs_key key, found_key;
3308 struct btrfs_trans_handle *trans;
3309 struct inode *inode;
3310 u64 last_objectid = 0;
3311 int ret = 0, nr_unlink = 0;
3313 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3316 path = btrfs_alloc_path();
3321 path->reada = READA_BACK;
3323 key.objectid = BTRFS_ORPHAN_OBJECTID;
3324 key.type = BTRFS_ORPHAN_ITEM_KEY;
3325 key.offset = (u64)-1;
3328 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3333 * if ret == 0 means we found what we were searching for, which
3334 * is weird, but possible, so only screw with path if we didn't
3335 * find the key and see if we have stuff that matches
3339 if (path->slots[0] == 0)
3344 /* pull out the item */
3345 leaf = path->nodes[0];
3346 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3348 /* make sure the item matches what we want */
3349 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3351 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3354 /* release the path since we're done with it */
3355 btrfs_release_path(path);
3358 * this is where we are basically btrfs_lookup, without the
3359 * crossing root thing. we store the inode number in the
3360 * offset of the orphan item.
3363 if (found_key.offset == last_objectid) {
3365 "Error removing orphan entry, stopping orphan cleanup");
3370 last_objectid = found_key.offset;
3372 found_key.objectid = found_key.offset;
3373 found_key.type = BTRFS_INODE_ITEM_KEY;
3374 found_key.offset = 0;
3375 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3376 ret = PTR_ERR_OR_ZERO(inode);
3377 if (ret && ret != -ENOENT)
3380 if (ret == -ENOENT && root == fs_info->tree_root) {
3381 struct btrfs_root *dead_root;
3382 int is_dead_root = 0;
3385 * this is an orphan in the tree root. Currently these
3386 * could come from 2 sources:
3387 * a) a snapshot deletion in progress
3388 * b) a free space cache inode
3389 * We need to distinguish those two, as the snapshot
3390 * orphan must not get deleted.
3391 * find_dead_roots already ran before us, so if this
3392 * is a snapshot deletion, we should find the root
3393 * in the fs_roots radix tree.
3396 spin_lock(&fs_info->fs_roots_radix_lock);
3397 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3398 (unsigned long)found_key.objectid);
3399 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3401 spin_unlock(&fs_info->fs_roots_radix_lock);
3404 /* prevent this orphan from being found again */
3405 key.offset = found_key.objectid - 1;
3412 * If we have an inode with links, there are a couple of
3413 * possibilities. Old kernels (before v3.12) used to create an
3414 * orphan item for truncate indicating that there were possibly
3415 * extent items past i_size that needed to be deleted. In v3.12,
3416 * truncate was changed to update i_size in sync with the extent
3417 * items, but the (useless) orphan item was still created. Since
3418 * v4.18, we don't create the orphan item for truncate at all.
3420 * So, this item could mean that we need to do a truncate, but
3421 * only if this filesystem was last used on a pre-v3.12 kernel
3422 * and was not cleanly unmounted. The odds of that are quite
3423 * slim, and it's a pain to do the truncate now, so just delete
3426 * It's also possible that this orphan item was supposed to be
3427 * deleted but wasn't. The inode number may have been reused,
3428 * but either way, we can delete the orphan item.
3430 if (ret == -ENOENT || inode->i_nlink) {
3433 trans = btrfs_start_transaction(root, 1);
3434 if (IS_ERR(trans)) {
3435 ret = PTR_ERR(trans);
3438 btrfs_debug(fs_info, "auto deleting %Lu",
3439 found_key.objectid);
3440 ret = btrfs_del_orphan_item(trans, root,
3441 found_key.objectid);
3442 btrfs_end_transaction(trans);
3450 /* this will do delete_inode and everything for us */
3453 /* release the path since we're done with it */
3454 btrfs_release_path(path);
3456 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3458 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3459 trans = btrfs_join_transaction(root);
3461 btrfs_end_transaction(trans);
3465 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3469 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3470 btrfs_free_path(path);
3475 * very simple check to peek ahead in the leaf looking for xattrs. If we
3476 * don't find any xattrs, we know there can't be any acls.
3478 * slot is the slot the inode is in, objectid is the objectid of the inode
3480 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3481 int slot, u64 objectid,
3482 int *first_xattr_slot)
3484 u32 nritems = btrfs_header_nritems(leaf);
3485 struct btrfs_key found_key;
3486 static u64 xattr_access = 0;
3487 static u64 xattr_default = 0;
3490 if (!xattr_access) {
3491 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3492 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3493 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3494 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3498 *first_xattr_slot = -1;
3499 while (slot < nritems) {
3500 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3502 /* we found a different objectid, there must not be acls */
3503 if (found_key.objectid != objectid)
3506 /* we found an xattr, assume we've got an acl */
3507 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3508 if (*first_xattr_slot == -1)
3509 *first_xattr_slot = slot;
3510 if (found_key.offset == xattr_access ||
3511 found_key.offset == xattr_default)
3516 * we found a key greater than an xattr key, there can't
3517 * be any acls later on
3519 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3526 * it goes inode, inode backrefs, xattrs, extents,
3527 * so if there are a ton of hard links to an inode there can
3528 * be a lot of backrefs. Don't waste time searching too hard,
3529 * this is just an optimization
3534 /* we hit the end of the leaf before we found an xattr or
3535 * something larger than an xattr. We have to assume the inode
3538 if (*first_xattr_slot == -1)
3539 *first_xattr_slot = slot;
3544 * read an inode from the btree into the in-memory inode
3546 static int btrfs_read_locked_inode(struct inode *inode,
3547 struct btrfs_path *in_path)
3549 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3550 struct btrfs_path *path = in_path;
3551 struct extent_buffer *leaf;
3552 struct btrfs_inode_item *inode_item;
3553 struct btrfs_root *root = BTRFS_I(inode)->root;
3554 struct btrfs_key location;
3559 bool filled = false;
3560 int first_xattr_slot;
3562 ret = btrfs_fill_inode(inode, &rdev);
3567 path = btrfs_alloc_path();
3572 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3574 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3576 if (path != in_path)
3577 btrfs_free_path(path);
3581 leaf = path->nodes[0];
3586 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3587 struct btrfs_inode_item);
3588 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3589 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3590 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3591 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3592 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3593 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3594 round_up(i_size_read(inode), fs_info->sectorsize));
3596 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3597 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3599 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3600 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3602 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3603 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3605 BTRFS_I(inode)->i_otime.tv_sec =
3606 btrfs_timespec_sec(leaf, &inode_item->otime);
3607 BTRFS_I(inode)->i_otime.tv_nsec =
3608 btrfs_timespec_nsec(leaf, &inode_item->otime);
3610 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3611 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3612 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3614 inode_set_iversion_queried(inode,
3615 btrfs_inode_sequence(leaf, inode_item));
3616 inode->i_generation = BTRFS_I(inode)->generation;
3618 rdev = btrfs_inode_rdev(leaf, inode_item);
3620 BTRFS_I(inode)->index_cnt = (u64)-1;
3621 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3625 * If we were modified in the current generation and evicted from memory
3626 * and then re-read we need to do a full sync since we don't have any
3627 * idea about which extents were modified before we were evicted from
3630 * This is required for both inode re-read from disk and delayed inode
3631 * in delayed_nodes_tree.
3633 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3634 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3635 &BTRFS_I(inode)->runtime_flags);
3638 * We don't persist the id of the transaction where an unlink operation
3639 * against the inode was last made. So here we assume the inode might
3640 * have been evicted, and therefore the exact value of last_unlink_trans
3641 * lost, and set it to last_trans to avoid metadata inconsistencies
3642 * between the inode and its parent if the inode is fsync'ed and the log
3643 * replayed. For example, in the scenario:
3646 * ln mydir/foo mydir/bar
3649 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3650 * xfs_io -c fsync mydir/foo
3652 * mount fs, triggers fsync log replay
3654 * We must make sure that when we fsync our inode foo we also log its
3655 * parent inode, otherwise after log replay the parent still has the
3656 * dentry with the "bar" name but our inode foo has a link count of 1
3657 * and doesn't have an inode ref with the name "bar" anymore.
3659 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3660 * but it guarantees correctness at the expense of occasional full
3661 * transaction commits on fsync if our inode is a directory, or if our
3662 * inode is not a directory, logging its parent unnecessarily.
3664 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3667 * Same logic as for last_unlink_trans. We don't persist the generation
3668 * of the last transaction where this inode was used for a reflink
3669 * operation, so after eviction and reloading the inode we must be
3670 * pessimistic and assume the last transaction that modified the inode.
3672 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3675 if (inode->i_nlink != 1 ||
3676 path->slots[0] >= btrfs_header_nritems(leaf))
3679 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3680 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3683 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3684 if (location.type == BTRFS_INODE_REF_KEY) {
3685 struct btrfs_inode_ref *ref;
3687 ref = (struct btrfs_inode_ref *)ptr;
3688 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3689 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3690 struct btrfs_inode_extref *extref;
3692 extref = (struct btrfs_inode_extref *)ptr;
3693 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3698 * try to precache a NULL acl entry for files that don't have
3699 * any xattrs or acls
3701 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3702 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3703 if (first_xattr_slot != -1) {
3704 path->slots[0] = first_xattr_slot;
3705 ret = btrfs_load_inode_props(inode, path);
3708 "error loading props for ino %llu (root %llu): %d",
3709 btrfs_ino(BTRFS_I(inode)),
3710 root->root_key.objectid, ret);
3712 if (path != in_path)
3713 btrfs_free_path(path);
3716 cache_no_acl(inode);
3718 switch (inode->i_mode & S_IFMT) {
3720 inode->i_mapping->a_ops = &btrfs_aops;
3721 inode->i_fop = &btrfs_file_operations;
3722 inode->i_op = &btrfs_file_inode_operations;
3725 inode->i_fop = &btrfs_dir_file_operations;
3726 inode->i_op = &btrfs_dir_inode_operations;
3729 inode->i_op = &btrfs_symlink_inode_operations;
3730 inode_nohighmem(inode);
3731 inode->i_mapping->a_ops = &btrfs_aops;
3734 inode->i_op = &btrfs_special_inode_operations;
3735 init_special_inode(inode, inode->i_mode, rdev);
3739 btrfs_sync_inode_flags_to_i_flags(inode);
3744 * given a leaf and an inode, copy the inode fields into the leaf
3746 static void fill_inode_item(struct btrfs_trans_handle *trans,
3747 struct extent_buffer *leaf,
3748 struct btrfs_inode_item *item,
3749 struct inode *inode)
3751 struct btrfs_map_token token;
3753 btrfs_init_map_token(&token, leaf);
3755 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3756 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3757 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3758 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3759 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3761 btrfs_set_token_timespec_sec(&token, &item->atime,
3762 inode->i_atime.tv_sec);
3763 btrfs_set_token_timespec_nsec(&token, &item->atime,
3764 inode->i_atime.tv_nsec);
3766 btrfs_set_token_timespec_sec(&token, &item->mtime,
3767 inode->i_mtime.tv_sec);
3768 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3769 inode->i_mtime.tv_nsec);
3771 btrfs_set_token_timespec_sec(&token, &item->ctime,
3772 inode->i_ctime.tv_sec);
3773 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3774 inode->i_ctime.tv_nsec);
3776 btrfs_set_token_timespec_sec(&token, &item->otime,
3777 BTRFS_I(inode)->i_otime.tv_sec);
3778 btrfs_set_token_timespec_nsec(&token, &item->otime,
3779 BTRFS_I(inode)->i_otime.tv_nsec);
3781 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3782 btrfs_set_token_inode_generation(&token, item,
3783 BTRFS_I(inode)->generation);
3784 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3785 btrfs_set_token_inode_transid(&token, item, trans->transid);
3786 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3787 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3788 btrfs_set_token_inode_block_group(&token, item, 0);
3792 * copy everything in the in-memory inode into the btree.
3794 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3795 struct btrfs_root *root,
3796 struct btrfs_inode *inode)
3798 struct btrfs_inode_item *inode_item;
3799 struct btrfs_path *path;
3800 struct extent_buffer *leaf;
3803 path = btrfs_alloc_path();
3807 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
3814 leaf = path->nodes[0];
3815 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3816 struct btrfs_inode_item);
3818 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
3819 btrfs_mark_buffer_dirty(leaf);
3820 btrfs_set_inode_last_trans(trans, inode);
3823 btrfs_free_path(path);
3828 * copy everything in the in-memory inode into the btree.
3830 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3831 struct btrfs_root *root,
3832 struct btrfs_inode *inode)
3834 struct btrfs_fs_info *fs_info = root->fs_info;
3838 * If the inode is a free space inode, we can deadlock during commit
3839 * if we put it into the delayed code.
3841 * The data relocation inode should also be directly updated
3844 if (!btrfs_is_free_space_inode(inode)
3845 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3846 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3847 btrfs_update_root_times(trans, root);
3849 ret = btrfs_delayed_update_inode(trans, root, inode);
3851 btrfs_set_inode_last_trans(trans, inode);
3855 return btrfs_update_inode_item(trans, root, inode);
3858 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3859 struct btrfs_root *root, struct btrfs_inode *inode)
3863 ret = btrfs_update_inode(trans, root, inode);
3865 return btrfs_update_inode_item(trans, root, inode);
3870 * unlink helper that gets used here in inode.c and in the tree logging
3871 * recovery code. It remove a link in a directory with a given name, and
3872 * also drops the back refs in the inode to the directory
3874 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3875 struct btrfs_root *root,
3876 struct btrfs_inode *dir,
3877 struct btrfs_inode *inode,
3878 const char *name, int name_len)
3880 struct btrfs_fs_info *fs_info = root->fs_info;
3881 struct btrfs_path *path;
3883 struct btrfs_dir_item *di;
3885 u64 ino = btrfs_ino(inode);
3886 u64 dir_ino = btrfs_ino(dir);
3888 path = btrfs_alloc_path();
3894 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3895 name, name_len, -1);
3896 if (IS_ERR_OR_NULL(di)) {
3897 ret = di ? PTR_ERR(di) : -ENOENT;
3900 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3903 btrfs_release_path(path);
3906 * If we don't have dir index, we have to get it by looking up
3907 * the inode ref, since we get the inode ref, remove it directly,
3908 * it is unnecessary to do delayed deletion.
3910 * But if we have dir index, needn't search inode ref to get it.
3911 * Since the inode ref is close to the inode item, it is better
3912 * that we delay to delete it, and just do this deletion when
3913 * we update the inode item.
3915 if (inode->dir_index) {
3916 ret = btrfs_delayed_delete_inode_ref(inode);
3918 index = inode->dir_index;
3923 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3927 "failed to delete reference to %.*s, inode %llu parent %llu",
3928 name_len, name, ino, dir_ino);
3929 btrfs_abort_transaction(trans, ret);
3933 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3935 btrfs_abort_transaction(trans, ret);
3939 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3941 if (ret != 0 && ret != -ENOENT) {
3942 btrfs_abort_transaction(trans, ret);
3946 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3951 btrfs_abort_transaction(trans, ret);
3954 * If we have a pending delayed iput we could end up with the final iput
3955 * being run in btrfs-cleaner context. If we have enough of these built
3956 * up we can end up burning a lot of time in btrfs-cleaner without any
3957 * way to throttle the unlinks. Since we're currently holding a ref on
3958 * the inode we can run the delayed iput here without any issues as the
3959 * final iput won't be done until after we drop the ref we're currently
3962 btrfs_run_delayed_iput(fs_info, inode);
3964 btrfs_free_path(path);
3968 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3969 inode_inc_iversion(&inode->vfs_inode);
3970 inode_inc_iversion(&dir->vfs_inode);
3971 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3972 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3973 ret = btrfs_update_inode(trans, root, dir);
3978 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3979 struct btrfs_root *root,
3980 struct btrfs_inode *dir, struct btrfs_inode *inode,
3981 const char *name, int name_len)
3984 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3986 drop_nlink(&inode->vfs_inode);
3987 ret = btrfs_update_inode(trans, root, inode);
3993 * helper to start transaction for unlink and rmdir.
3995 * unlink and rmdir are special in btrfs, they do not always free space, so
3996 * if we cannot make our reservations the normal way try and see if there is
3997 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3998 * allow the unlink to occur.
4000 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4002 struct btrfs_root *root = BTRFS_I(dir)->root;
4005 * 1 for the possible orphan item
4006 * 1 for the dir item
4007 * 1 for the dir index
4008 * 1 for the inode ref
4011 return btrfs_start_transaction_fallback_global_rsv(root, 5);
4014 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4016 struct btrfs_root *root = BTRFS_I(dir)->root;
4017 struct btrfs_trans_handle *trans;
4018 struct inode *inode = d_inode(dentry);
4021 trans = __unlink_start_trans(dir);
4023 return PTR_ERR(trans);
4025 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4028 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4029 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4030 dentry->d_name.len);
4034 if (inode->i_nlink == 0) {
4035 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4041 btrfs_end_transaction(trans);
4042 btrfs_btree_balance_dirty(root->fs_info);
4046 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4047 struct inode *dir, struct dentry *dentry)
4049 struct btrfs_root *root = BTRFS_I(dir)->root;
4050 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4051 struct btrfs_path *path;
4052 struct extent_buffer *leaf;
4053 struct btrfs_dir_item *di;
4054 struct btrfs_key key;
4055 const char *name = dentry->d_name.name;
4056 int name_len = dentry->d_name.len;
4060 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4062 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4063 objectid = inode->root->root_key.objectid;
4064 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4065 objectid = inode->location.objectid;
4071 path = btrfs_alloc_path();
4075 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4076 name, name_len, -1);
4077 if (IS_ERR_OR_NULL(di)) {
4078 ret = di ? PTR_ERR(di) : -ENOENT;
4082 leaf = path->nodes[0];
4083 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4084 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4085 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4087 btrfs_abort_transaction(trans, ret);
4090 btrfs_release_path(path);
4093 * This is a placeholder inode for a subvolume we didn't have a
4094 * reference to at the time of the snapshot creation. In the meantime
4095 * we could have renamed the real subvol link into our snapshot, so
4096 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
4097 * Instead simply lookup the dir_index_item for this entry so we can
4098 * remove it. Otherwise we know we have a ref to the root and we can
4099 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4101 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4102 di = btrfs_search_dir_index_item(root, path, dir_ino,
4104 if (IS_ERR_OR_NULL(di)) {
4109 btrfs_abort_transaction(trans, ret);
4113 leaf = path->nodes[0];
4114 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4116 btrfs_release_path(path);
4118 ret = btrfs_del_root_ref(trans, objectid,
4119 root->root_key.objectid, dir_ino,
4120 &index, name, name_len);
4122 btrfs_abort_transaction(trans, ret);
4127 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4129 btrfs_abort_transaction(trans, ret);
4133 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4134 inode_inc_iversion(dir);
4135 dir->i_mtime = dir->i_ctime = current_time(dir);
4136 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4138 btrfs_abort_transaction(trans, ret);
4140 btrfs_free_path(path);
4145 * Helper to check if the subvolume references other subvolumes or if it's
4148 static noinline int may_destroy_subvol(struct btrfs_root *root)
4150 struct btrfs_fs_info *fs_info = root->fs_info;
4151 struct btrfs_path *path;
4152 struct btrfs_dir_item *di;
4153 struct btrfs_key key;
4157 path = btrfs_alloc_path();
4161 /* Make sure this root isn't set as the default subvol */
4162 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4163 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4164 dir_id, "default", 7, 0);
4165 if (di && !IS_ERR(di)) {
4166 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4167 if (key.objectid == root->root_key.objectid) {
4170 "deleting default subvolume %llu is not allowed",
4174 btrfs_release_path(path);
4177 key.objectid = root->root_key.objectid;
4178 key.type = BTRFS_ROOT_REF_KEY;
4179 key.offset = (u64)-1;
4181 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4187 if (path->slots[0] > 0) {
4189 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4190 if (key.objectid == root->root_key.objectid &&
4191 key.type == BTRFS_ROOT_REF_KEY)
4195 btrfs_free_path(path);
4199 /* Delete all dentries for inodes belonging to the root */
4200 static void btrfs_prune_dentries(struct btrfs_root *root)
4202 struct btrfs_fs_info *fs_info = root->fs_info;
4203 struct rb_node *node;
4204 struct rb_node *prev;
4205 struct btrfs_inode *entry;
4206 struct inode *inode;
4209 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4210 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4212 spin_lock(&root->inode_lock);
4214 node = root->inode_tree.rb_node;
4218 entry = rb_entry(node, struct btrfs_inode, rb_node);
4220 if (objectid < btrfs_ino(entry))
4221 node = node->rb_left;
4222 else if (objectid > btrfs_ino(entry))
4223 node = node->rb_right;
4229 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4230 if (objectid <= btrfs_ino(entry)) {
4234 prev = rb_next(prev);
4238 entry = rb_entry(node, struct btrfs_inode, rb_node);
4239 objectid = btrfs_ino(entry) + 1;
4240 inode = igrab(&entry->vfs_inode);
4242 spin_unlock(&root->inode_lock);
4243 if (atomic_read(&inode->i_count) > 1)
4244 d_prune_aliases(inode);
4246 * btrfs_drop_inode will have it removed from the inode
4247 * cache when its usage count hits zero.
4251 spin_lock(&root->inode_lock);
4255 if (cond_resched_lock(&root->inode_lock))
4258 node = rb_next(node);
4260 spin_unlock(&root->inode_lock);
4263 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4265 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4266 struct btrfs_root *root = BTRFS_I(dir)->root;
4267 struct inode *inode = d_inode(dentry);
4268 struct btrfs_root *dest = BTRFS_I(inode)->root;
4269 struct btrfs_trans_handle *trans;
4270 struct btrfs_block_rsv block_rsv;
4275 * Don't allow to delete a subvolume with send in progress. This is
4276 * inside the inode lock so the error handling that has to drop the bit
4277 * again is not run concurrently.
4279 spin_lock(&dest->root_item_lock);
4280 if (dest->send_in_progress) {
4281 spin_unlock(&dest->root_item_lock);
4283 "attempt to delete subvolume %llu during send",
4284 dest->root_key.objectid);
4287 root_flags = btrfs_root_flags(&dest->root_item);
4288 btrfs_set_root_flags(&dest->root_item,
4289 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4290 spin_unlock(&dest->root_item_lock);
4292 down_write(&fs_info->subvol_sem);
4294 ret = may_destroy_subvol(dest);
4298 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4300 * One for dir inode,
4301 * two for dir entries,
4302 * two for root ref/backref.
4304 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4308 trans = btrfs_start_transaction(root, 0);
4309 if (IS_ERR(trans)) {
4310 ret = PTR_ERR(trans);
4313 trans->block_rsv = &block_rsv;
4314 trans->bytes_reserved = block_rsv.size;
4316 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4318 ret = btrfs_unlink_subvol(trans, dir, dentry);
4320 btrfs_abort_transaction(trans, ret);
4324 btrfs_record_root_in_trans(trans, dest);
4326 memset(&dest->root_item.drop_progress, 0,
4327 sizeof(dest->root_item.drop_progress));
4328 btrfs_set_root_drop_level(&dest->root_item, 0);
4329 btrfs_set_root_refs(&dest->root_item, 0);
4331 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4332 ret = btrfs_insert_orphan_item(trans,
4334 dest->root_key.objectid);
4336 btrfs_abort_transaction(trans, ret);
4341 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4342 BTRFS_UUID_KEY_SUBVOL,
4343 dest->root_key.objectid);
4344 if (ret && ret != -ENOENT) {
4345 btrfs_abort_transaction(trans, ret);
4348 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4349 ret = btrfs_uuid_tree_remove(trans,
4350 dest->root_item.received_uuid,
4351 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4352 dest->root_key.objectid);
4353 if (ret && ret != -ENOENT) {
4354 btrfs_abort_transaction(trans, ret);
4359 free_anon_bdev(dest->anon_dev);
4362 trans->block_rsv = NULL;
4363 trans->bytes_reserved = 0;
4364 ret = btrfs_end_transaction(trans);
4365 inode->i_flags |= S_DEAD;
4367 btrfs_subvolume_release_metadata(root, &block_rsv);
4369 up_write(&fs_info->subvol_sem);
4371 spin_lock(&dest->root_item_lock);
4372 root_flags = btrfs_root_flags(&dest->root_item);
4373 btrfs_set_root_flags(&dest->root_item,
4374 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4375 spin_unlock(&dest->root_item_lock);
4377 d_invalidate(dentry);
4378 btrfs_prune_dentries(dest);
4379 ASSERT(dest->send_in_progress == 0);
4385 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4387 struct inode *inode = d_inode(dentry);
4389 struct btrfs_root *root = BTRFS_I(dir)->root;
4390 struct btrfs_trans_handle *trans;
4391 u64 last_unlink_trans;
4393 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4395 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4396 return btrfs_delete_subvolume(dir, dentry);
4398 trans = __unlink_start_trans(dir);
4400 return PTR_ERR(trans);
4402 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4403 err = btrfs_unlink_subvol(trans, dir, dentry);
4407 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4411 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4413 /* now the directory is empty */
4414 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4415 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4416 dentry->d_name.len);
4418 btrfs_i_size_write(BTRFS_I(inode), 0);
4420 * Propagate the last_unlink_trans value of the deleted dir to
4421 * its parent directory. This is to prevent an unrecoverable
4422 * log tree in the case we do something like this:
4424 * 2) create snapshot under dir foo
4425 * 3) delete the snapshot
4428 * 6) fsync foo or some file inside foo
4430 if (last_unlink_trans >= trans->transid)
4431 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4434 btrfs_end_transaction(trans);
4435 btrfs_btree_balance_dirty(root->fs_info);
4441 * Return this if we need to call truncate_block for the last bit of the
4444 #define NEED_TRUNCATE_BLOCK 1
4447 * this can truncate away extent items, csum items and directory items.
4448 * It starts at a high offset and removes keys until it can't find
4449 * any higher than new_size
4451 * csum items that cross the new i_size are truncated to the new size
4454 * min_type is the minimum key type to truncate down to. If set to 0, this
4455 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4457 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4458 struct btrfs_root *root,
4459 struct btrfs_inode *inode,
4460 u64 new_size, u32 min_type)
4462 struct btrfs_fs_info *fs_info = root->fs_info;
4463 struct btrfs_path *path;
4464 struct extent_buffer *leaf;
4465 struct btrfs_file_extent_item *fi;
4466 struct btrfs_key key;
4467 struct btrfs_key found_key;
4468 u64 extent_start = 0;
4469 u64 extent_num_bytes = 0;
4470 u64 extent_offset = 0;
4472 u64 last_size = new_size;
4473 u32 found_type = (u8)-1;
4476 int pending_del_nr = 0;
4477 int pending_del_slot = 0;
4478 int extent_type = -1;
4480 u64 ino = btrfs_ino(inode);
4481 u64 bytes_deleted = 0;
4482 bool be_nice = false;
4483 bool should_throttle = false;
4484 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4485 struct extent_state *cached_state = NULL;
4487 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4490 * For non-free space inodes and non-shareable roots, we want to back
4491 * off from time to time. This means all inodes in subvolume roots,
4492 * reloc roots, and data reloc roots.
4494 if (!btrfs_is_free_space_inode(inode) &&
4495 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4498 path = btrfs_alloc_path();
4501 path->reada = READA_BACK;
4503 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4504 lock_extent_bits(&inode->io_tree, lock_start, (u64)-1,
4508 * We want to drop from the next block forward in case this
4509 * new size is not block aligned since we will be keeping the
4510 * last block of the extent just the way it is.
4512 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4513 fs_info->sectorsize),
4518 * This function is also used to drop the items in the log tree before
4519 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4520 * it is used to drop the logged items. So we shouldn't kill the delayed
4523 if (min_type == 0 && root == inode->root)
4524 btrfs_kill_delayed_inode_items(inode);
4527 key.offset = (u64)-1;
4532 * with a 16K leaf size and 128MB extents, you can actually queue
4533 * up a huge file in a single leaf. Most of the time that
4534 * bytes_deleted is > 0, it will be huge by the time we get here
4536 if (be_nice && bytes_deleted > SZ_32M &&
4537 btrfs_should_end_transaction(trans)) {
4542 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4548 /* there are no items in the tree for us to truncate, we're
4551 if (path->slots[0] == 0)
4557 u64 clear_start = 0, clear_len = 0;
4560 leaf = path->nodes[0];
4561 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4562 found_type = found_key.type;
4564 if (found_key.objectid != ino)
4567 if (found_type < min_type)
4570 item_end = found_key.offset;
4571 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4572 fi = btrfs_item_ptr(leaf, path->slots[0],
4573 struct btrfs_file_extent_item);
4574 extent_type = btrfs_file_extent_type(leaf, fi);
4575 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4577 btrfs_file_extent_num_bytes(leaf, fi);
4579 trace_btrfs_truncate_show_fi_regular(
4580 inode, leaf, fi, found_key.offset);
4581 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4582 item_end += btrfs_file_extent_ram_bytes(leaf,
4585 trace_btrfs_truncate_show_fi_inline(
4586 inode, leaf, fi, path->slots[0],
4591 if (found_type > min_type) {
4594 if (item_end < new_size)
4596 if (found_key.offset >= new_size)
4602 /* FIXME, shrink the extent if the ref count is only 1 */
4603 if (found_type != BTRFS_EXTENT_DATA_KEY)
4606 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4609 clear_start = found_key.offset;
4610 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4612 u64 orig_num_bytes =
4613 btrfs_file_extent_num_bytes(leaf, fi);
4614 extent_num_bytes = ALIGN(new_size -
4616 fs_info->sectorsize);
4617 clear_start = ALIGN(new_size, fs_info->sectorsize);
4618 btrfs_set_file_extent_num_bytes(leaf, fi,
4620 num_dec = (orig_num_bytes -
4622 if (test_bit(BTRFS_ROOT_SHAREABLE,
4625 inode_sub_bytes(&inode->vfs_inode,
4627 btrfs_mark_buffer_dirty(leaf);
4630 btrfs_file_extent_disk_num_bytes(leaf,
4632 extent_offset = found_key.offset -
4633 btrfs_file_extent_offset(leaf, fi);
4635 /* FIXME blocksize != 4096 */
4636 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4637 if (extent_start != 0) {
4639 if (test_bit(BTRFS_ROOT_SHAREABLE,
4641 inode_sub_bytes(&inode->vfs_inode,
4645 clear_len = num_dec;
4646 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4648 * we can't truncate inline items that have had
4652 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4653 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4654 btrfs_file_extent_compression(leaf, fi) == 0) {
4655 u32 size = (u32)(new_size - found_key.offset);
4657 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4658 size = btrfs_file_extent_calc_inline_size(size);
4659 btrfs_truncate_item(path, size, 1);
4660 } else if (!del_item) {
4662 * We have to bail so the last_size is set to
4663 * just before this extent.
4665 ret = NEED_TRUNCATE_BLOCK;
4669 * Inline extents are special, we just treat
4670 * them as a full sector worth in the file
4671 * extent tree just for simplicity sake.
4673 clear_len = fs_info->sectorsize;
4676 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4677 inode_sub_bytes(&inode->vfs_inode,
4678 item_end + 1 - new_size);
4682 * We use btrfs_truncate_inode_items() to clean up log trees for
4683 * multiple fsyncs, and in this case we don't want to clear the
4684 * file extent range because it's just the log.
4686 if (root == inode->root) {
4687 ret = btrfs_inode_clear_file_extent_range(inode,
4688 clear_start, clear_len);
4690 btrfs_abort_transaction(trans, ret);
4696 last_size = found_key.offset;
4698 last_size = new_size;
4700 if (!pending_del_nr) {
4701 /* no pending yet, add ourselves */
4702 pending_del_slot = path->slots[0];
4704 } else if (pending_del_nr &&
4705 path->slots[0] + 1 == pending_del_slot) {
4706 /* hop on the pending chunk */
4708 pending_del_slot = path->slots[0];
4715 should_throttle = false;
4718 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4719 struct btrfs_ref ref = { 0 };
4721 bytes_deleted += extent_num_bytes;
4723 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4724 extent_start, extent_num_bytes, 0);
4725 ref.real_root = root->root_key.objectid;
4726 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4727 ino, extent_offset);
4728 ret = btrfs_free_extent(trans, &ref);
4730 btrfs_abort_transaction(trans, ret);
4734 if (btrfs_should_throttle_delayed_refs(trans))
4735 should_throttle = true;
4739 if (found_type == BTRFS_INODE_ITEM_KEY)
4742 if (path->slots[0] == 0 ||
4743 path->slots[0] != pending_del_slot ||
4745 if (pending_del_nr) {
4746 ret = btrfs_del_items(trans, root, path,
4750 btrfs_abort_transaction(trans, ret);
4755 btrfs_release_path(path);
4758 * We can generate a lot of delayed refs, so we need to
4759 * throttle every once and a while and make sure we're
4760 * adding enough space to keep up with the work we are
4761 * generating. Since we hold a transaction here we
4762 * can't flush, and we don't want to FLUSH_LIMIT because
4763 * we could have generated too many delayed refs to
4764 * actually allocate, so just bail if we're short and
4765 * let the normal reservation dance happen higher up.
4767 if (should_throttle) {
4768 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4769 BTRFS_RESERVE_NO_FLUSH);
4781 if (ret >= 0 && pending_del_nr) {
4784 err = btrfs_del_items(trans, root, path, pending_del_slot,
4787 btrfs_abort_transaction(trans, err);
4791 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4792 ASSERT(last_size >= new_size);
4793 if (!ret && last_size > new_size)
4794 last_size = new_size;
4795 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4796 unlock_extent_cached(&inode->io_tree, lock_start, (u64)-1,
4800 btrfs_free_path(path);
4805 * btrfs_truncate_block - read, zero a chunk and write a block
4806 * @inode - inode that we're zeroing
4807 * @from - the offset to start zeroing
4808 * @len - the length to zero, 0 to zero the entire range respective to the
4810 * @front - zero up to the offset instead of from the offset on
4812 * This will find the block for the "from" offset and cow the block and zero the
4813 * part we want to zero. This is used with truncate and hole punching.
4815 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4818 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4819 struct address_space *mapping = inode->vfs_inode.i_mapping;
4820 struct extent_io_tree *io_tree = &inode->io_tree;
4821 struct btrfs_ordered_extent *ordered;
4822 struct extent_state *cached_state = NULL;
4823 struct extent_changeset *data_reserved = NULL;
4825 bool only_release_metadata = false;
4826 u32 blocksize = fs_info->sectorsize;
4827 pgoff_t index = from >> PAGE_SHIFT;
4828 unsigned offset = from & (blocksize - 1);
4830 gfp_t mask = btrfs_alloc_write_mask(mapping);
4831 size_t write_bytes = blocksize;
4836 if (IS_ALIGNED(offset, blocksize) &&
4837 (!len || IS_ALIGNED(len, blocksize)))
4840 block_start = round_down(from, blocksize);
4841 block_end = block_start + blocksize - 1;
4843 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4846 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
4847 /* For nocow case, no need to reserve data space */
4848 only_release_metadata = true;
4853 ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
4855 if (!only_release_metadata)
4856 btrfs_free_reserved_data_space(inode, data_reserved,
4857 block_start, blocksize);
4861 page = find_or_create_page(mapping, index, mask);
4863 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4865 btrfs_delalloc_release_extents(inode, blocksize);
4869 ret = set_page_extent_mapped(page);
4873 if (!PageUptodate(page)) {
4874 ret = btrfs_readpage(NULL, page);
4876 if (page->mapping != mapping) {
4881 if (!PageUptodate(page)) {
4886 wait_on_page_writeback(page);
4888 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4890 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4892 unlock_extent_cached(io_tree, block_start, block_end,
4896 btrfs_start_ordered_extent(ordered, 1);
4897 btrfs_put_ordered_extent(ordered);
4901 clear_extent_bit(&inode->io_tree, block_start, block_end,
4902 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4903 0, 0, &cached_state);
4905 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4908 unlock_extent_cached(io_tree, block_start, block_end,
4913 if (offset != blocksize) {
4915 len = blocksize - offset;
4918 memset(kaddr + (block_start - page_offset(page)),
4921 memset(kaddr + (block_start - page_offset(page)) + offset,
4923 flush_dcache_page(page);
4926 ClearPageChecked(page);
4927 set_page_dirty(page);
4928 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4930 if (only_release_metadata)
4931 set_extent_bit(&inode->io_tree, block_start, block_end,
4932 EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
4936 if (only_release_metadata)
4937 btrfs_delalloc_release_metadata(inode, blocksize, true);
4939 btrfs_delalloc_release_space(inode, data_reserved,
4940 block_start, blocksize, true);
4942 btrfs_delalloc_release_extents(inode, blocksize);
4946 if (only_release_metadata)
4947 btrfs_check_nocow_unlock(inode);
4948 extent_changeset_free(data_reserved);
4952 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4953 u64 offset, u64 len)
4955 struct btrfs_fs_info *fs_info = root->fs_info;
4956 struct btrfs_trans_handle *trans;
4957 struct btrfs_drop_extents_args drop_args = { 0 };
4961 * Still need to make sure the inode looks like it's been updated so
4962 * that any holes get logged if we fsync.
4964 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4965 inode->last_trans = fs_info->generation;
4966 inode->last_sub_trans = root->log_transid;
4967 inode->last_log_commit = root->last_log_commit;
4972 * 1 - for the one we're dropping
4973 * 1 - for the one we're adding
4974 * 1 - for updating the inode.
4976 trans = btrfs_start_transaction(root, 3);
4978 return PTR_ERR(trans);
4980 drop_args.start = offset;
4981 drop_args.end = offset + len;
4982 drop_args.drop_cache = true;
4984 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4986 btrfs_abort_transaction(trans, ret);
4987 btrfs_end_transaction(trans);
4991 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
4992 offset, 0, 0, len, 0, len, 0, 0, 0);
4994 btrfs_abort_transaction(trans, ret);
4996 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
4997 btrfs_update_inode(trans, root, inode);
4999 btrfs_end_transaction(trans);
5004 * This function puts in dummy file extents for the area we're creating a hole
5005 * for. So if we are truncating this file to a larger size we need to insert
5006 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5007 * the range between oldsize and size
5009 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5011 struct btrfs_root *root = inode->root;
5012 struct btrfs_fs_info *fs_info = root->fs_info;
5013 struct extent_io_tree *io_tree = &inode->io_tree;
5014 struct extent_map *em = NULL;
5015 struct extent_state *cached_state = NULL;
5016 struct extent_map_tree *em_tree = &inode->extent_tree;
5017 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5018 u64 block_end = ALIGN(size, fs_info->sectorsize);
5025 * If our size started in the middle of a block we need to zero out the
5026 * rest of the block before we expand the i_size, otherwise we could
5027 * expose stale data.
5029 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5033 if (size <= hole_start)
5036 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5038 cur_offset = hole_start;
5040 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5041 block_end - cur_offset);
5047 last_byte = min(extent_map_end(em), block_end);
5048 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5049 hole_size = last_byte - cur_offset;
5051 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5052 struct extent_map *hole_em;
5054 err = maybe_insert_hole(root, inode, cur_offset,
5059 err = btrfs_inode_set_file_extent_range(inode,
5060 cur_offset, hole_size);
5064 btrfs_drop_extent_cache(inode, cur_offset,
5065 cur_offset + hole_size - 1, 0);
5066 hole_em = alloc_extent_map();
5068 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5069 &inode->runtime_flags);
5072 hole_em->start = cur_offset;
5073 hole_em->len = hole_size;
5074 hole_em->orig_start = cur_offset;
5076 hole_em->block_start = EXTENT_MAP_HOLE;
5077 hole_em->block_len = 0;
5078 hole_em->orig_block_len = 0;
5079 hole_em->ram_bytes = hole_size;
5080 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5081 hole_em->generation = fs_info->generation;
5084 write_lock(&em_tree->lock);
5085 err = add_extent_mapping(em_tree, hole_em, 1);
5086 write_unlock(&em_tree->lock);
5089 btrfs_drop_extent_cache(inode, cur_offset,
5093 free_extent_map(hole_em);
5095 err = btrfs_inode_set_file_extent_range(inode,
5096 cur_offset, hole_size);
5101 free_extent_map(em);
5103 cur_offset = last_byte;
5104 if (cur_offset >= block_end)
5107 free_extent_map(em);
5108 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5112 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5114 struct btrfs_root *root = BTRFS_I(inode)->root;
5115 struct btrfs_trans_handle *trans;
5116 loff_t oldsize = i_size_read(inode);
5117 loff_t newsize = attr->ia_size;
5118 int mask = attr->ia_valid;
5122 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5123 * special case where we need to update the times despite not having
5124 * these flags set. For all other operations the VFS set these flags
5125 * explicitly if it wants a timestamp update.
5127 if (newsize != oldsize) {
5128 inode_inc_iversion(inode);
5129 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5130 inode->i_ctime = inode->i_mtime =
5131 current_time(inode);
5134 if (newsize > oldsize) {
5136 * Don't do an expanding truncate while snapshotting is ongoing.
5137 * This is to ensure the snapshot captures a fully consistent
5138 * state of this file - if the snapshot captures this expanding
5139 * truncation, it must capture all writes that happened before
5142 btrfs_drew_write_lock(&root->snapshot_lock);
5143 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5145 btrfs_drew_write_unlock(&root->snapshot_lock);
5149 trans = btrfs_start_transaction(root, 1);
5150 if (IS_ERR(trans)) {
5151 btrfs_drew_write_unlock(&root->snapshot_lock);
5152 return PTR_ERR(trans);
5155 i_size_write(inode, newsize);
5156 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5157 pagecache_isize_extended(inode, oldsize, newsize);
5158 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5159 btrfs_drew_write_unlock(&root->snapshot_lock);
5160 btrfs_end_transaction(trans);
5162 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5164 if (btrfs_is_zoned(fs_info)) {
5165 ret = btrfs_wait_ordered_range(inode,
5166 ALIGN(newsize, fs_info->sectorsize),
5173 * We're truncating a file that used to have good data down to
5174 * zero. Make sure any new writes to the file get on disk
5178 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5179 &BTRFS_I(inode)->runtime_flags);
5181 truncate_setsize(inode, newsize);
5183 inode_dio_wait(inode);
5185 ret = btrfs_truncate(inode, newsize == oldsize);
5186 if (ret && inode->i_nlink) {
5190 * Truncate failed, so fix up the in-memory size. We
5191 * adjusted disk_i_size down as we removed extents, so
5192 * wait for disk_i_size to be stable and then update the
5193 * in-memory size to match.
5195 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5198 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5205 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5208 struct inode *inode = d_inode(dentry);
5209 struct btrfs_root *root = BTRFS_I(inode)->root;
5212 if (btrfs_root_readonly(root))
5215 err = setattr_prepare(&init_user_ns, dentry, attr);
5219 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5220 err = btrfs_setsize(inode, attr);
5225 if (attr->ia_valid) {
5226 setattr_copy(&init_user_ns, inode, attr);
5227 inode_inc_iversion(inode);
5228 err = btrfs_dirty_inode(inode);
5230 if (!err && attr->ia_valid & ATTR_MODE)
5231 err = posix_acl_chmod(&init_user_ns, inode,
5239 * While truncating the inode pages during eviction, we get the VFS calling
5240 * btrfs_invalidatepage() against each page of the inode. This is slow because
5241 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5242 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5243 * extent_state structures over and over, wasting lots of time.
5245 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5246 * those expensive operations on a per page basis and do only the ordered io
5247 * finishing, while we release here the extent_map and extent_state structures,
5248 * without the excessive merging and splitting.
5250 static void evict_inode_truncate_pages(struct inode *inode)
5252 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5253 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5254 struct rb_node *node;
5256 ASSERT(inode->i_state & I_FREEING);
5257 truncate_inode_pages_final(&inode->i_data);
5259 write_lock(&map_tree->lock);
5260 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5261 struct extent_map *em;
5263 node = rb_first_cached(&map_tree->map);
5264 em = rb_entry(node, struct extent_map, rb_node);
5265 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5266 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5267 remove_extent_mapping(map_tree, em);
5268 free_extent_map(em);
5269 if (need_resched()) {
5270 write_unlock(&map_tree->lock);
5272 write_lock(&map_tree->lock);
5275 write_unlock(&map_tree->lock);
5278 * Keep looping until we have no more ranges in the io tree.
5279 * We can have ongoing bios started by readahead that have
5280 * their endio callback (extent_io.c:end_bio_extent_readpage)
5281 * still in progress (unlocked the pages in the bio but did not yet
5282 * unlocked the ranges in the io tree). Therefore this means some
5283 * ranges can still be locked and eviction started because before
5284 * submitting those bios, which are executed by a separate task (work
5285 * queue kthread), inode references (inode->i_count) were not taken
5286 * (which would be dropped in the end io callback of each bio).
5287 * Therefore here we effectively end up waiting for those bios and
5288 * anyone else holding locked ranges without having bumped the inode's
5289 * reference count - if we don't do it, when they access the inode's
5290 * io_tree to unlock a range it may be too late, leading to an
5291 * use-after-free issue.
5293 spin_lock(&io_tree->lock);
5294 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5295 struct extent_state *state;
5296 struct extent_state *cached_state = NULL;
5299 unsigned state_flags;
5301 node = rb_first(&io_tree->state);
5302 state = rb_entry(node, struct extent_state, rb_node);
5303 start = state->start;
5305 state_flags = state->state;
5306 spin_unlock(&io_tree->lock);
5308 lock_extent_bits(io_tree, start, end, &cached_state);
5311 * If still has DELALLOC flag, the extent didn't reach disk,
5312 * and its reserved space won't be freed by delayed_ref.
5313 * So we need to free its reserved space here.
5314 * (Refer to comment in btrfs_invalidatepage, case 2)
5316 * Note, end is the bytenr of last byte, so we need + 1 here.
5318 if (state_flags & EXTENT_DELALLOC)
5319 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5322 clear_extent_bit(io_tree, start, end,
5323 EXTENT_LOCKED | EXTENT_DELALLOC |
5324 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5328 spin_lock(&io_tree->lock);
5330 spin_unlock(&io_tree->lock);
5333 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5334 struct btrfs_block_rsv *rsv)
5336 struct btrfs_fs_info *fs_info = root->fs_info;
5337 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5338 struct btrfs_trans_handle *trans;
5339 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5343 * Eviction should be taking place at some place safe because of our
5344 * delayed iputs. However the normal flushing code will run delayed
5345 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5347 * We reserve the delayed_refs_extra here again because we can't use
5348 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5349 * above. We reserve our extra bit here because we generate a ton of
5350 * delayed refs activity by truncating.
5352 * If we cannot make our reservation we'll attempt to steal from the
5353 * global reserve, because we really want to be able to free up space.
5355 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5356 BTRFS_RESERVE_FLUSH_EVICT);
5359 * Try to steal from the global reserve if there is space for
5362 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5363 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5365 "could not allocate space for delete; will truncate on mount");
5366 return ERR_PTR(-ENOSPC);
5368 delayed_refs_extra = 0;
5371 trans = btrfs_join_transaction(root);
5375 if (delayed_refs_extra) {
5376 trans->block_rsv = &fs_info->trans_block_rsv;
5377 trans->bytes_reserved = delayed_refs_extra;
5378 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5379 delayed_refs_extra, 1);
5384 void btrfs_evict_inode(struct inode *inode)
5386 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5387 struct btrfs_trans_handle *trans;
5388 struct btrfs_root *root = BTRFS_I(inode)->root;
5389 struct btrfs_block_rsv *rsv;
5392 trace_btrfs_inode_evict(inode);
5399 evict_inode_truncate_pages(inode);
5401 if (inode->i_nlink &&
5402 ((btrfs_root_refs(&root->root_item) != 0 &&
5403 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5404 btrfs_is_free_space_inode(BTRFS_I(inode))))
5407 if (is_bad_inode(inode))
5410 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5412 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5415 if (inode->i_nlink > 0) {
5416 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5417 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5421 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5425 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5428 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5431 btrfs_i_size_write(BTRFS_I(inode), 0);
5434 trans = evict_refill_and_join(root, rsv);
5438 trans->block_rsv = rsv;
5440 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
5442 trans->block_rsv = &fs_info->trans_block_rsv;
5443 btrfs_end_transaction(trans);
5444 btrfs_btree_balance_dirty(fs_info);
5445 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5452 * Errors here aren't a big deal, it just means we leave orphan items in
5453 * the tree. They will be cleaned up on the next mount. If the inode
5454 * number gets reused, cleanup deletes the orphan item without doing
5455 * anything, and unlink reuses the existing orphan item.
5457 * If it turns out that we are dropping too many of these, we might want
5458 * to add a mechanism for retrying these after a commit.
5460 trans = evict_refill_and_join(root, rsv);
5461 if (!IS_ERR(trans)) {
5462 trans->block_rsv = rsv;
5463 btrfs_orphan_del(trans, BTRFS_I(inode));
5464 trans->block_rsv = &fs_info->trans_block_rsv;
5465 btrfs_end_transaction(trans);
5469 btrfs_free_block_rsv(fs_info, rsv);
5472 * If we didn't successfully delete, the orphan item will still be in
5473 * the tree and we'll retry on the next mount. Again, we might also want
5474 * to retry these periodically in the future.
5476 btrfs_remove_delayed_node(BTRFS_I(inode));
5481 * Return the key found in the dir entry in the location pointer, fill @type
5482 * with BTRFS_FT_*, and return 0.
5484 * If no dir entries were found, returns -ENOENT.
5485 * If found a corrupted location in dir entry, returns -EUCLEAN.
5487 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5488 struct btrfs_key *location, u8 *type)
5490 const char *name = dentry->d_name.name;
5491 int namelen = dentry->d_name.len;
5492 struct btrfs_dir_item *di;
5493 struct btrfs_path *path;
5494 struct btrfs_root *root = BTRFS_I(dir)->root;
5497 path = btrfs_alloc_path();
5501 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5503 if (IS_ERR_OR_NULL(di)) {
5504 ret = di ? PTR_ERR(di) : -ENOENT;
5508 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5509 if (location->type != BTRFS_INODE_ITEM_KEY &&
5510 location->type != BTRFS_ROOT_ITEM_KEY) {
5512 btrfs_warn(root->fs_info,
5513 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5514 __func__, name, btrfs_ino(BTRFS_I(dir)),
5515 location->objectid, location->type, location->offset);
5518 *type = btrfs_dir_type(path->nodes[0], di);
5520 btrfs_free_path(path);
5525 * when we hit a tree root in a directory, the btrfs part of the inode
5526 * needs to be changed to reflect the root directory of the tree root. This
5527 * is kind of like crossing a mount point.
5529 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5531 struct dentry *dentry,
5532 struct btrfs_key *location,
5533 struct btrfs_root **sub_root)
5535 struct btrfs_path *path;
5536 struct btrfs_root *new_root;
5537 struct btrfs_root_ref *ref;
5538 struct extent_buffer *leaf;
5539 struct btrfs_key key;
5543 path = btrfs_alloc_path();
5550 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5551 key.type = BTRFS_ROOT_REF_KEY;
5552 key.offset = location->objectid;
5554 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5561 leaf = path->nodes[0];
5562 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5563 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5564 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5567 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5568 (unsigned long)(ref + 1),
5569 dentry->d_name.len);
5573 btrfs_release_path(path);
5575 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5576 if (IS_ERR(new_root)) {
5577 err = PTR_ERR(new_root);
5581 *sub_root = new_root;
5582 location->objectid = btrfs_root_dirid(&new_root->root_item);
5583 location->type = BTRFS_INODE_ITEM_KEY;
5584 location->offset = 0;
5587 btrfs_free_path(path);
5591 static void inode_tree_add(struct inode *inode)
5593 struct btrfs_root *root = BTRFS_I(inode)->root;
5594 struct btrfs_inode *entry;
5596 struct rb_node *parent;
5597 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5598 u64 ino = btrfs_ino(BTRFS_I(inode));
5600 if (inode_unhashed(inode))
5603 spin_lock(&root->inode_lock);
5604 p = &root->inode_tree.rb_node;
5607 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5609 if (ino < btrfs_ino(entry))
5610 p = &parent->rb_left;
5611 else if (ino > btrfs_ino(entry))
5612 p = &parent->rb_right;
5614 WARN_ON(!(entry->vfs_inode.i_state &
5615 (I_WILL_FREE | I_FREEING)));
5616 rb_replace_node(parent, new, &root->inode_tree);
5617 RB_CLEAR_NODE(parent);
5618 spin_unlock(&root->inode_lock);
5622 rb_link_node(new, parent, p);
5623 rb_insert_color(new, &root->inode_tree);
5624 spin_unlock(&root->inode_lock);
5627 static void inode_tree_del(struct btrfs_inode *inode)
5629 struct btrfs_root *root = inode->root;
5632 spin_lock(&root->inode_lock);
5633 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5634 rb_erase(&inode->rb_node, &root->inode_tree);
5635 RB_CLEAR_NODE(&inode->rb_node);
5636 empty = RB_EMPTY_ROOT(&root->inode_tree);
5638 spin_unlock(&root->inode_lock);
5640 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5641 spin_lock(&root->inode_lock);
5642 empty = RB_EMPTY_ROOT(&root->inode_tree);
5643 spin_unlock(&root->inode_lock);
5645 btrfs_add_dead_root(root);
5650 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5652 struct btrfs_iget_args *args = p;
5654 inode->i_ino = args->ino;
5655 BTRFS_I(inode)->location.objectid = args->ino;
5656 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5657 BTRFS_I(inode)->location.offset = 0;
5658 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5659 BUG_ON(args->root && !BTRFS_I(inode)->root);
5663 static int btrfs_find_actor(struct inode *inode, void *opaque)
5665 struct btrfs_iget_args *args = opaque;
5667 return args->ino == BTRFS_I(inode)->location.objectid &&
5668 args->root == BTRFS_I(inode)->root;
5671 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5672 struct btrfs_root *root)
5674 struct inode *inode;
5675 struct btrfs_iget_args args;
5676 unsigned long hashval = btrfs_inode_hash(ino, root);
5681 inode = iget5_locked(s, hashval, btrfs_find_actor,
5682 btrfs_init_locked_inode,
5688 * Get an inode object given its inode number and corresponding root.
5689 * Path can be preallocated to prevent recursing back to iget through
5690 * allocator. NULL is also valid but may require an additional allocation
5693 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5694 struct btrfs_root *root, struct btrfs_path *path)
5696 struct inode *inode;
5698 inode = btrfs_iget_locked(s, ino, root);
5700 return ERR_PTR(-ENOMEM);
5702 if (inode->i_state & I_NEW) {
5705 ret = btrfs_read_locked_inode(inode, path);
5707 inode_tree_add(inode);
5708 unlock_new_inode(inode);
5712 * ret > 0 can come from btrfs_search_slot called by
5713 * btrfs_read_locked_inode, this means the inode item
5718 inode = ERR_PTR(ret);
5725 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5727 return btrfs_iget_path(s, ino, root, NULL);
5730 static struct inode *new_simple_dir(struct super_block *s,
5731 struct btrfs_key *key,
5732 struct btrfs_root *root)
5734 struct inode *inode = new_inode(s);
5737 return ERR_PTR(-ENOMEM);
5739 BTRFS_I(inode)->root = btrfs_grab_root(root);
5740 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5741 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5743 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5745 * We only need lookup, the rest is read-only and there's no inode
5746 * associated with the dentry
5748 inode->i_op = &simple_dir_inode_operations;
5749 inode->i_opflags &= ~IOP_XATTR;
5750 inode->i_fop = &simple_dir_operations;
5751 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5752 inode->i_mtime = current_time(inode);
5753 inode->i_atime = inode->i_mtime;
5754 inode->i_ctime = inode->i_mtime;
5755 BTRFS_I(inode)->i_otime = inode->i_mtime;
5760 static inline u8 btrfs_inode_type(struct inode *inode)
5763 * Compile-time asserts that generic FT_* types still match
5766 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5767 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5768 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5769 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5770 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5771 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5772 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5773 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5775 return fs_umode_to_ftype(inode->i_mode);
5778 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5780 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5781 struct inode *inode;
5782 struct btrfs_root *root = BTRFS_I(dir)->root;
5783 struct btrfs_root *sub_root = root;
5784 struct btrfs_key location;
5788 if (dentry->d_name.len > BTRFS_NAME_LEN)
5789 return ERR_PTR(-ENAMETOOLONG);
5791 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5793 return ERR_PTR(ret);
5795 if (location.type == BTRFS_INODE_ITEM_KEY) {
5796 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5800 /* Do extra check against inode mode with di_type */
5801 if (btrfs_inode_type(inode) != di_type) {
5803 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5804 inode->i_mode, btrfs_inode_type(inode),
5807 return ERR_PTR(-EUCLEAN);
5812 ret = fixup_tree_root_location(fs_info, dir, dentry,
5813 &location, &sub_root);
5816 inode = ERR_PTR(ret);
5818 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5820 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5822 if (root != sub_root)
5823 btrfs_put_root(sub_root);
5825 if (!IS_ERR(inode) && root != sub_root) {
5826 down_read(&fs_info->cleanup_work_sem);
5827 if (!sb_rdonly(inode->i_sb))
5828 ret = btrfs_orphan_cleanup(sub_root);
5829 up_read(&fs_info->cleanup_work_sem);
5832 inode = ERR_PTR(ret);
5839 static int btrfs_dentry_delete(const struct dentry *dentry)
5841 struct btrfs_root *root;
5842 struct inode *inode = d_inode(dentry);
5844 if (!inode && !IS_ROOT(dentry))
5845 inode = d_inode(dentry->d_parent);
5848 root = BTRFS_I(inode)->root;
5849 if (btrfs_root_refs(&root->root_item) == 0)
5852 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5858 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5861 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5863 if (inode == ERR_PTR(-ENOENT))
5865 return d_splice_alias(inode, dentry);
5869 * All this infrastructure exists because dir_emit can fault, and we are holding
5870 * the tree lock when doing readdir. For now just allocate a buffer and copy
5871 * our information into that, and then dir_emit from the buffer. This is
5872 * similar to what NFS does, only we don't keep the buffer around in pagecache
5873 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5874 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5877 static int btrfs_opendir(struct inode *inode, struct file *file)
5879 struct btrfs_file_private *private;
5881 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5884 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5885 if (!private->filldir_buf) {
5889 file->private_data = private;
5900 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5903 struct dir_entry *entry = addr;
5904 char *name = (char *)(entry + 1);
5906 ctx->pos = get_unaligned(&entry->offset);
5907 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5908 get_unaligned(&entry->ino),
5909 get_unaligned(&entry->type)))
5911 addr += sizeof(struct dir_entry) +
5912 get_unaligned(&entry->name_len);
5918 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5920 struct inode *inode = file_inode(file);
5921 struct btrfs_root *root = BTRFS_I(inode)->root;
5922 struct btrfs_file_private *private = file->private_data;
5923 struct btrfs_dir_item *di;
5924 struct btrfs_key key;
5925 struct btrfs_key found_key;
5926 struct btrfs_path *path;
5928 struct list_head ins_list;
5929 struct list_head del_list;
5931 struct extent_buffer *leaf;
5938 struct btrfs_key location;
5940 if (!dir_emit_dots(file, ctx))
5943 path = btrfs_alloc_path();
5947 addr = private->filldir_buf;
5948 path->reada = READA_FORWARD;
5950 INIT_LIST_HEAD(&ins_list);
5951 INIT_LIST_HEAD(&del_list);
5952 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5955 key.type = BTRFS_DIR_INDEX_KEY;
5956 key.offset = ctx->pos;
5957 key.objectid = btrfs_ino(BTRFS_I(inode));
5959 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5964 struct dir_entry *entry;
5966 leaf = path->nodes[0];
5967 slot = path->slots[0];
5968 if (slot >= btrfs_header_nritems(leaf)) {
5969 ret = btrfs_next_leaf(root, path);
5977 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5979 if (found_key.objectid != key.objectid)
5981 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5983 if (found_key.offset < ctx->pos)
5985 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5987 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5988 name_len = btrfs_dir_name_len(leaf, di);
5989 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5991 btrfs_release_path(path);
5992 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5995 addr = private->filldir_buf;
6002 put_unaligned(name_len, &entry->name_len);
6003 name_ptr = (char *)(entry + 1);
6004 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6006 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6008 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6009 put_unaligned(location.objectid, &entry->ino);
6010 put_unaligned(found_key.offset, &entry->offset);
6012 addr += sizeof(struct dir_entry) + name_len;
6013 total_len += sizeof(struct dir_entry) + name_len;
6017 btrfs_release_path(path);
6019 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6023 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6028 * Stop new entries from being returned after we return the last
6031 * New directory entries are assigned a strictly increasing
6032 * offset. This means that new entries created during readdir
6033 * are *guaranteed* to be seen in the future by that readdir.
6034 * This has broken buggy programs which operate on names as
6035 * they're returned by readdir. Until we re-use freed offsets
6036 * we have this hack to stop new entries from being returned
6037 * under the assumption that they'll never reach this huge
6040 * This is being careful not to overflow 32bit loff_t unless the
6041 * last entry requires it because doing so has broken 32bit apps
6044 if (ctx->pos >= INT_MAX)
6045 ctx->pos = LLONG_MAX;
6052 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6053 btrfs_free_path(path);
6058 * This is somewhat expensive, updating the tree every time the
6059 * inode changes. But, it is most likely to find the inode in cache.
6060 * FIXME, needs more benchmarking...there are no reasons other than performance
6061 * to keep or drop this code.
6063 static int btrfs_dirty_inode(struct inode *inode)
6065 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6066 struct btrfs_root *root = BTRFS_I(inode)->root;
6067 struct btrfs_trans_handle *trans;
6070 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6073 trans = btrfs_join_transaction(root);
6075 return PTR_ERR(trans);
6077 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6078 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6079 /* whoops, lets try again with the full transaction */
6080 btrfs_end_transaction(trans);
6081 trans = btrfs_start_transaction(root, 1);
6083 return PTR_ERR(trans);
6085 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6087 btrfs_end_transaction(trans);
6088 if (BTRFS_I(inode)->delayed_node)
6089 btrfs_balance_delayed_items(fs_info);
6095 * This is a copy of file_update_time. We need this so we can return error on
6096 * ENOSPC for updating the inode in the case of file write and mmap writes.
6098 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6101 struct btrfs_root *root = BTRFS_I(inode)->root;
6102 bool dirty = flags & ~S_VERSION;
6104 if (btrfs_root_readonly(root))
6107 if (flags & S_VERSION)
6108 dirty |= inode_maybe_inc_iversion(inode, dirty);
6109 if (flags & S_CTIME)
6110 inode->i_ctime = *now;
6111 if (flags & S_MTIME)
6112 inode->i_mtime = *now;
6113 if (flags & S_ATIME)
6114 inode->i_atime = *now;
6115 return dirty ? btrfs_dirty_inode(inode) : 0;
6119 * find the highest existing sequence number in a directory
6120 * and then set the in-memory index_cnt variable to reflect
6121 * free sequence numbers
6123 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6125 struct btrfs_root *root = inode->root;
6126 struct btrfs_key key, found_key;
6127 struct btrfs_path *path;
6128 struct extent_buffer *leaf;
6131 key.objectid = btrfs_ino(inode);
6132 key.type = BTRFS_DIR_INDEX_KEY;
6133 key.offset = (u64)-1;
6135 path = btrfs_alloc_path();
6139 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6142 /* FIXME: we should be able to handle this */
6148 * MAGIC NUMBER EXPLANATION:
6149 * since we search a directory based on f_pos we have to start at 2
6150 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6151 * else has to start at 2
6153 if (path->slots[0] == 0) {
6154 inode->index_cnt = 2;
6160 leaf = path->nodes[0];
6161 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6163 if (found_key.objectid != btrfs_ino(inode) ||
6164 found_key.type != BTRFS_DIR_INDEX_KEY) {
6165 inode->index_cnt = 2;
6169 inode->index_cnt = found_key.offset + 1;
6171 btrfs_free_path(path);
6176 * helper to find a free sequence number in a given directory. This current
6177 * code is very simple, later versions will do smarter things in the btree
6179 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6183 if (dir->index_cnt == (u64)-1) {
6184 ret = btrfs_inode_delayed_dir_index_count(dir);
6186 ret = btrfs_set_inode_index_count(dir);
6192 *index = dir->index_cnt;
6198 static int btrfs_insert_inode_locked(struct inode *inode)
6200 struct btrfs_iget_args args;
6202 args.ino = BTRFS_I(inode)->location.objectid;
6203 args.root = BTRFS_I(inode)->root;
6205 return insert_inode_locked4(inode,
6206 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6207 btrfs_find_actor, &args);
6211 * Inherit flags from the parent inode.
6213 * Currently only the compression flags and the cow flags are inherited.
6215 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6222 flags = BTRFS_I(dir)->flags;
6224 if (flags & BTRFS_INODE_NOCOMPRESS) {
6225 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6226 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6227 } else if (flags & BTRFS_INODE_COMPRESS) {
6228 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6229 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6232 if (flags & BTRFS_INODE_NODATACOW) {
6233 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6234 if (S_ISREG(inode->i_mode))
6235 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6238 btrfs_sync_inode_flags_to_i_flags(inode);
6241 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6242 struct btrfs_root *root,
6244 const char *name, int name_len,
6245 u64 ref_objectid, u64 objectid,
6246 umode_t mode, u64 *index)
6248 struct btrfs_fs_info *fs_info = root->fs_info;
6249 struct inode *inode;
6250 struct btrfs_inode_item *inode_item;
6251 struct btrfs_key *location;
6252 struct btrfs_path *path;
6253 struct btrfs_inode_ref *ref;
6254 struct btrfs_key key[2];
6256 int nitems = name ? 2 : 1;
6258 unsigned int nofs_flag;
6261 path = btrfs_alloc_path();
6263 return ERR_PTR(-ENOMEM);
6265 nofs_flag = memalloc_nofs_save();
6266 inode = new_inode(fs_info->sb);
6267 memalloc_nofs_restore(nofs_flag);
6269 btrfs_free_path(path);
6270 return ERR_PTR(-ENOMEM);
6274 * O_TMPFILE, set link count to 0, so that after this point,
6275 * we fill in an inode item with the correct link count.
6278 set_nlink(inode, 0);
6281 * we have to initialize this early, so we can reclaim the inode
6282 * number if we fail afterwards in this function.
6284 inode->i_ino = objectid;
6287 trace_btrfs_inode_request(dir);
6289 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6291 btrfs_free_path(path);
6293 return ERR_PTR(ret);
6299 * index_cnt is ignored for everything but a dir,
6300 * btrfs_set_inode_index_count has an explanation for the magic
6303 BTRFS_I(inode)->index_cnt = 2;
6304 BTRFS_I(inode)->dir_index = *index;
6305 BTRFS_I(inode)->root = btrfs_grab_root(root);
6306 BTRFS_I(inode)->generation = trans->transid;
6307 inode->i_generation = BTRFS_I(inode)->generation;
6310 * We could have gotten an inode number from somebody who was fsynced
6311 * and then removed in this same transaction, so let's just set full
6312 * sync since it will be a full sync anyway and this will blow away the
6313 * old info in the log.
6315 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6317 key[0].objectid = objectid;
6318 key[0].type = BTRFS_INODE_ITEM_KEY;
6321 sizes[0] = sizeof(struct btrfs_inode_item);
6325 * Start new inodes with an inode_ref. This is slightly more
6326 * efficient for small numbers of hard links since they will
6327 * be packed into one item. Extended refs will kick in if we
6328 * add more hard links than can fit in the ref item.
6330 key[1].objectid = objectid;
6331 key[1].type = BTRFS_INODE_REF_KEY;
6332 key[1].offset = ref_objectid;
6334 sizes[1] = name_len + sizeof(*ref);
6337 location = &BTRFS_I(inode)->location;
6338 location->objectid = objectid;
6339 location->offset = 0;
6340 location->type = BTRFS_INODE_ITEM_KEY;
6342 ret = btrfs_insert_inode_locked(inode);
6348 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6352 inode_init_owner(&init_user_ns, inode, dir, mode);
6353 inode_set_bytes(inode, 0);
6355 inode->i_mtime = current_time(inode);
6356 inode->i_atime = inode->i_mtime;
6357 inode->i_ctime = inode->i_mtime;
6358 BTRFS_I(inode)->i_otime = inode->i_mtime;
6360 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6361 struct btrfs_inode_item);
6362 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6363 sizeof(*inode_item));
6364 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6367 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6368 struct btrfs_inode_ref);
6369 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6370 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6371 ptr = (unsigned long)(ref + 1);
6372 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6375 btrfs_mark_buffer_dirty(path->nodes[0]);
6376 btrfs_free_path(path);
6378 btrfs_inherit_iflags(inode, dir);
6380 if (S_ISREG(mode)) {
6381 if (btrfs_test_opt(fs_info, NODATASUM))
6382 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6383 if (btrfs_test_opt(fs_info, NODATACOW))
6384 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6385 BTRFS_INODE_NODATASUM;
6388 inode_tree_add(inode);
6390 trace_btrfs_inode_new(inode);
6391 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6393 btrfs_update_root_times(trans, root);
6395 ret = btrfs_inode_inherit_props(trans, inode, dir);
6398 "error inheriting props for ino %llu (root %llu): %d",
6399 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6404 discard_new_inode(inode);
6407 BTRFS_I(dir)->index_cnt--;
6408 btrfs_free_path(path);
6409 return ERR_PTR(ret);
6413 * utility function to add 'inode' into 'parent_inode' with
6414 * a give name and a given sequence number.
6415 * if 'add_backref' is true, also insert a backref from the
6416 * inode to the parent directory.
6418 int btrfs_add_link(struct btrfs_trans_handle *trans,
6419 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6420 const char *name, int name_len, int add_backref, u64 index)
6423 struct btrfs_key key;
6424 struct btrfs_root *root = parent_inode->root;
6425 u64 ino = btrfs_ino(inode);
6426 u64 parent_ino = btrfs_ino(parent_inode);
6428 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6429 memcpy(&key, &inode->root->root_key, sizeof(key));
6432 key.type = BTRFS_INODE_ITEM_KEY;
6436 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6437 ret = btrfs_add_root_ref(trans, key.objectid,
6438 root->root_key.objectid, parent_ino,
6439 index, name, name_len);
6440 } else if (add_backref) {
6441 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6445 /* Nothing to clean up yet */
6449 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6450 btrfs_inode_type(&inode->vfs_inode), index);
6451 if (ret == -EEXIST || ret == -EOVERFLOW)
6454 btrfs_abort_transaction(trans, ret);
6458 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6460 inode_inc_iversion(&parent_inode->vfs_inode);
6462 * If we are replaying a log tree, we do not want to update the mtime
6463 * and ctime of the parent directory with the current time, since the
6464 * log replay procedure is responsible for setting them to their correct
6465 * values (the ones it had when the fsync was done).
6467 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6468 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6470 parent_inode->vfs_inode.i_mtime = now;
6471 parent_inode->vfs_inode.i_ctime = now;
6473 ret = btrfs_update_inode(trans, root, parent_inode);
6475 btrfs_abort_transaction(trans, ret);
6479 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6482 err = btrfs_del_root_ref(trans, key.objectid,
6483 root->root_key.objectid, parent_ino,
6484 &local_index, name, name_len);
6486 btrfs_abort_transaction(trans, err);
6487 } else if (add_backref) {
6491 err = btrfs_del_inode_ref(trans, root, name, name_len,
6492 ino, parent_ino, &local_index);
6494 btrfs_abort_transaction(trans, err);
6497 /* Return the original error code */
6501 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6502 struct btrfs_inode *dir, struct dentry *dentry,
6503 struct btrfs_inode *inode, int backref, u64 index)
6505 int err = btrfs_add_link(trans, dir, inode,
6506 dentry->d_name.name, dentry->d_name.len,
6513 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6514 struct dentry *dentry, umode_t mode, dev_t rdev)
6516 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6517 struct btrfs_trans_handle *trans;
6518 struct btrfs_root *root = BTRFS_I(dir)->root;
6519 struct inode *inode = NULL;
6525 * 2 for inode item and ref
6527 * 1 for xattr if selinux is on
6529 trans = btrfs_start_transaction(root, 5);
6531 return PTR_ERR(trans);
6533 err = btrfs_get_free_objectid(root, &objectid);
6537 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6538 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6540 if (IS_ERR(inode)) {
6541 err = PTR_ERR(inode);
6547 * If the active LSM wants to access the inode during
6548 * d_instantiate it needs these. Smack checks to see
6549 * if the filesystem supports xattrs by looking at the
6552 inode->i_op = &btrfs_special_inode_operations;
6553 init_special_inode(inode, inode->i_mode, rdev);
6555 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6559 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6564 btrfs_update_inode(trans, root, BTRFS_I(inode));
6565 d_instantiate_new(dentry, inode);
6568 btrfs_end_transaction(trans);
6569 btrfs_btree_balance_dirty(fs_info);
6571 inode_dec_link_count(inode);
6572 discard_new_inode(inode);
6577 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6578 struct dentry *dentry, umode_t mode, bool excl)
6580 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6581 struct btrfs_trans_handle *trans;
6582 struct btrfs_root *root = BTRFS_I(dir)->root;
6583 struct inode *inode = NULL;
6589 * 2 for inode item and ref
6591 * 1 for xattr if selinux is on
6593 trans = btrfs_start_transaction(root, 5);
6595 return PTR_ERR(trans);
6597 err = btrfs_get_free_objectid(root, &objectid);
6601 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6602 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6604 if (IS_ERR(inode)) {
6605 err = PTR_ERR(inode);
6610 * If the active LSM wants to access the inode during
6611 * d_instantiate it needs these. Smack checks to see
6612 * if the filesystem supports xattrs by looking at the
6615 inode->i_fop = &btrfs_file_operations;
6616 inode->i_op = &btrfs_file_inode_operations;
6617 inode->i_mapping->a_ops = &btrfs_aops;
6619 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6623 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6627 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6632 d_instantiate_new(dentry, inode);
6635 btrfs_end_transaction(trans);
6637 inode_dec_link_count(inode);
6638 discard_new_inode(inode);
6640 btrfs_btree_balance_dirty(fs_info);
6644 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6645 struct dentry *dentry)
6647 struct btrfs_trans_handle *trans = NULL;
6648 struct btrfs_root *root = BTRFS_I(dir)->root;
6649 struct inode *inode = d_inode(old_dentry);
6650 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6655 /* do not allow sys_link's with other subvols of the same device */
6656 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6659 if (inode->i_nlink >= BTRFS_LINK_MAX)
6662 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6667 * 2 items for inode and inode ref
6668 * 2 items for dir items
6669 * 1 item for parent inode
6670 * 1 item for orphan item deletion if O_TMPFILE
6672 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6673 if (IS_ERR(trans)) {
6674 err = PTR_ERR(trans);
6679 /* There are several dir indexes for this inode, clear the cache. */
6680 BTRFS_I(inode)->dir_index = 0ULL;
6682 inode_inc_iversion(inode);
6683 inode->i_ctime = current_time(inode);
6685 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6687 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6693 struct dentry *parent = dentry->d_parent;
6695 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6698 if (inode->i_nlink == 1) {
6700 * If new hard link count is 1, it's a file created
6701 * with open(2) O_TMPFILE flag.
6703 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6707 d_instantiate(dentry, inode);
6708 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6713 btrfs_end_transaction(trans);
6715 inode_dec_link_count(inode);
6718 btrfs_btree_balance_dirty(fs_info);
6722 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6723 struct dentry *dentry, umode_t mode)
6725 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6726 struct inode *inode = NULL;
6727 struct btrfs_trans_handle *trans;
6728 struct btrfs_root *root = BTRFS_I(dir)->root;
6734 * 2 items for inode and ref
6735 * 2 items for dir items
6736 * 1 for xattr if selinux is on
6738 trans = btrfs_start_transaction(root, 5);
6740 return PTR_ERR(trans);
6742 err = btrfs_get_free_objectid(root, &objectid);
6746 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6747 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6748 S_IFDIR | mode, &index);
6749 if (IS_ERR(inode)) {
6750 err = PTR_ERR(inode);
6755 /* these must be set before we unlock the inode */
6756 inode->i_op = &btrfs_dir_inode_operations;
6757 inode->i_fop = &btrfs_dir_file_operations;
6759 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6763 btrfs_i_size_write(BTRFS_I(inode), 0);
6764 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6768 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6769 dentry->d_name.name,
6770 dentry->d_name.len, 0, index);
6774 d_instantiate_new(dentry, inode);
6777 btrfs_end_transaction(trans);
6779 inode_dec_link_count(inode);
6780 discard_new_inode(inode);
6782 btrfs_btree_balance_dirty(fs_info);
6786 static noinline int uncompress_inline(struct btrfs_path *path,
6788 size_t pg_offset, u64 extent_offset,
6789 struct btrfs_file_extent_item *item)
6792 struct extent_buffer *leaf = path->nodes[0];
6795 unsigned long inline_size;
6799 WARN_ON(pg_offset != 0);
6800 compress_type = btrfs_file_extent_compression(leaf, item);
6801 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6802 inline_size = btrfs_file_extent_inline_item_len(leaf,
6803 btrfs_item_nr(path->slots[0]));
6804 tmp = kmalloc(inline_size, GFP_NOFS);
6807 ptr = btrfs_file_extent_inline_start(item);
6809 read_extent_buffer(leaf, tmp, ptr, inline_size);
6811 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6812 ret = btrfs_decompress(compress_type, tmp, page,
6813 extent_offset, inline_size, max_size);
6816 * decompression code contains a memset to fill in any space between the end
6817 * of the uncompressed data and the end of max_size in case the decompressed
6818 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6819 * the end of an inline extent and the beginning of the next block, so we
6820 * cover that region here.
6823 if (max_size + pg_offset < PAGE_SIZE) {
6824 char *map = kmap(page);
6825 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6833 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6834 * @inode: file to search in
6835 * @page: page to read extent data into if the extent is inline
6836 * @pg_offset: offset into @page to copy to
6837 * @start: file offset
6838 * @len: length of range starting at @start
6840 * This returns the first &struct extent_map which overlaps with the given
6841 * range, reading it from the B-tree and caching it if necessary. Note that
6842 * there may be more extents which overlap the given range after the returned
6845 * If @page is not NULL and the extent is inline, this also reads the extent
6846 * data directly into the page and marks the extent up to date in the io_tree.
6848 * Return: ERR_PTR on error, non-NULL extent_map on success.
6850 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6851 struct page *page, size_t pg_offset,
6854 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6856 u64 extent_start = 0;
6858 u64 objectid = btrfs_ino(inode);
6859 int extent_type = -1;
6860 struct btrfs_path *path = NULL;
6861 struct btrfs_root *root = inode->root;
6862 struct btrfs_file_extent_item *item;
6863 struct extent_buffer *leaf;
6864 struct btrfs_key found_key;
6865 struct extent_map *em = NULL;
6866 struct extent_map_tree *em_tree = &inode->extent_tree;
6867 struct extent_io_tree *io_tree = &inode->io_tree;
6869 read_lock(&em_tree->lock);
6870 em = lookup_extent_mapping(em_tree, start, len);
6871 read_unlock(&em_tree->lock);
6874 if (em->start > start || em->start + em->len <= start)
6875 free_extent_map(em);
6876 else if (em->block_start == EXTENT_MAP_INLINE && page)
6877 free_extent_map(em);
6881 em = alloc_extent_map();
6886 em->start = EXTENT_MAP_HOLE;
6887 em->orig_start = EXTENT_MAP_HOLE;
6889 em->block_len = (u64)-1;
6891 path = btrfs_alloc_path();
6897 /* Chances are we'll be called again, so go ahead and do readahead */
6898 path->reada = READA_FORWARD;
6901 * The same explanation in load_free_space_cache applies here as well,
6902 * we only read when we're loading the free space cache, and at that
6903 * point the commit_root has everything we need.
6905 if (btrfs_is_free_space_inode(inode)) {
6906 path->search_commit_root = 1;
6907 path->skip_locking = 1;
6910 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6913 } else if (ret > 0) {
6914 if (path->slots[0] == 0)
6920 leaf = path->nodes[0];
6921 item = btrfs_item_ptr(leaf, path->slots[0],
6922 struct btrfs_file_extent_item);
6923 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6924 if (found_key.objectid != objectid ||
6925 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6927 * If we backup past the first extent we want to move forward
6928 * and see if there is an extent in front of us, otherwise we'll
6929 * say there is a hole for our whole search range which can
6936 extent_type = btrfs_file_extent_type(leaf, item);
6937 extent_start = found_key.offset;
6938 extent_end = btrfs_file_extent_end(path);
6939 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6940 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6941 /* Only regular file could have regular/prealloc extent */
6942 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6945 "regular/prealloc extent found for non-regular inode %llu",
6949 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6951 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6952 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6957 if (start >= extent_end) {
6959 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6960 ret = btrfs_next_leaf(root, path);
6966 leaf = path->nodes[0];
6968 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6969 if (found_key.objectid != objectid ||
6970 found_key.type != BTRFS_EXTENT_DATA_KEY)
6972 if (start + len <= found_key.offset)
6974 if (start > found_key.offset)
6977 /* New extent overlaps with existing one */
6979 em->orig_start = start;
6980 em->len = found_key.offset - start;
6981 em->block_start = EXTENT_MAP_HOLE;
6985 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6987 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6988 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6990 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6994 size_t extent_offset;
7000 size = btrfs_file_extent_ram_bytes(leaf, item);
7001 extent_offset = page_offset(page) + pg_offset - extent_start;
7002 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7003 size - extent_offset);
7004 em->start = extent_start + extent_offset;
7005 em->len = ALIGN(copy_size, fs_info->sectorsize);
7006 em->orig_block_len = em->len;
7007 em->orig_start = em->start;
7008 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7010 if (!PageUptodate(page)) {
7011 if (btrfs_file_extent_compression(leaf, item) !=
7012 BTRFS_COMPRESS_NONE) {
7013 ret = uncompress_inline(path, page, pg_offset,
7014 extent_offset, item);
7019 read_extent_buffer(leaf, map + pg_offset, ptr,
7021 if (pg_offset + copy_size < PAGE_SIZE) {
7022 memset(map + pg_offset + copy_size, 0,
7023 PAGE_SIZE - pg_offset -
7028 flush_dcache_page(page);
7030 set_extent_uptodate(io_tree, em->start,
7031 extent_map_end(em) - 1, NULL, GFP_NOFS);
7036 em->orig_start = start;
7038 em->block_start = EXTENT_MAP_HOLE;
7041 btrfs_release_path(path);
7042 if (em->start > start || extent_map_end(em) <= start) {
7044 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7045 em->start, em->len, start, len);
7050 write_lock(&em_tree->lock);
7051 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7052 write_unlock(&em_tree->lock);
7054 btrfs_free_path(path);
7056 trace_btrfs_get_extent(root, inode, em);
7059 free_extent_map(em);
7060 return ERR_PTR(ret);
7065 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7068 struct extent_map *em;
7069 struct extent_map *hole_em = NULL;
7070 u64 delalloc_start = start;
7076 em = btrfs_get_extent(inode, NULL, 0, start, len);
7080 * If our em maps to:
7082 * - a pre-alloc extent,
7083 * there might actually be delalloc bytes behind it.
7085 if (em->block_start != EXTENT_MAP_HOLE &&
7086 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7091 /* check to see if we've wrapped (len == -1 or similar) */
7100 /* ok, we didn't find anything, lets look for delalloc */
7101 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7102 end, len, EXTENT_DELALLOC, 1);
7103 delalloc_end = delalloc_start + delalloc_len;
7104 if (delalloc_end < delalloc_start)
7105 delalloc_end = (u64)-1;
7108 * We didn't find anything useful, return the original results from
7111 if (delalloc_start > end || delalloc_end <= start) {
7118 * Adjust the delalloc_start to make sure it doesn't go backwards from
7119 * the start they passed in
7121 delalloc_start = max(start, delalloc_start);
7122 delalloc_len = delalloc_end - delalloc_start;
7124 if (delalloc_len > 0) {
7127 const u64 hole_end = extent_map_end(hole_em);
7129 em = alloc_extent_map();
7137 * When btrfs_get_extent can't find anything it returns one
7140 * Make sure what it found really fits our range, and adjust to
7141 * make sure it is based on the start from the caller
7143 if (hole_end <= start || hole_em->start > end) {
7144 free_extent_map(hole_em);
7147 hole_start = max(hole_em->start, start);
7148 hole_len = hole_end - hole_start;
7151 if (hole_em && delalloc_start > hole_start) {
7153 * Our hole starts before our delalloc, so we have to
7154 * return just the parts of the hole that go until the
7157 em->len = min(hole_len, delalloc_start - hole_start);
7158 em->start = hole_start;
7159 em->orig_start = hole_start;
7161 * Don't adjust block start at all, it is fixed at
7164 em->block_start = hole_em->block_start;
7165 em->block_len = hole_len;
7166 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7167 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7170 * Hole is out of passed range or it starts after
7173 em->start = delalloc_start;
7174 em->len = delalloc_len;
7175 em->orig_start = delalloc_start;
7176 em->block_start = EXTENT_MAP_DELALLOC;
7177 em->block_len = delalloc_len;
7184 free_extent_map(hole_em);
7186 free_extent_map(em);
7187 return ERR_PTR(err);
7192 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7195 const u64 orig_start,
7196 const u64 block_start,
7197 const u64 block_len,
7198 const u64 orig_block_len,
7199 const u64 ram_bytes,
7202 struct extent_map *em = NULL;
7205 if (type != BTRFS_ORDERED_NOCOW) {
7206 em = create_io_em(inode, start, len, orig_start, block_start,
7207 block_len, orig_block_len, ram_bytes,
7208 BTRFS_COMPRESS_NONE, /* compress_type */
7213 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7217 free_extent_map(em);
7218 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7227 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7230 struct btrfs_root *root = inode->root;
7231 struct btrfs_fs_info *fs_info = root->fs_info;
7232 struct extent_map *em;
7233 struct btrfs_key ins;
7237 alloc_hint = get_extent_allocation_hint(inode, start, len);
7238 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7239 0, alloc_hint, &ins, 1, 1);
7241 return ERR_PTR(ret);
7243 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7244 ins.objectid, ins.offset, ins.offset,
7245 ins.offset, BTRFS_ORDERED_REGULAR);
7246 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7248 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7254 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7256 struct btrfs_block_group *block_group;
7257 bool readonly = false;
7259 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7260 if (!block_group || block_group->ro)
7263 btrfs_put_block_group(block_group);
7268 * Check if we can do nocow write into the range [@offset, @offset + @len)
7270 * @offset: File offset
7271 * @len: The length to write, will be updated to the nocow writeable
7273 * @orig_start: (optional) Return the original file offset of the file extent
7274 * @orig_len: (optional) Return the original on-disk length of the file extent
7275 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7276 * @strict: if true, omit optimizations that might force us into unnecessary
7277 * cow. e.g., don't trust generation number.
7280 * >0 and update @len if we can do nocow write
7281 * 0 if we can't do nocow write
7282 * <0 if error happened
7284 * NOTE: This only checks the file extents, caller is responsible to wait for
7285 * any ordered extents.
7287 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7288 u64 *orig_start, u64 *orig_block_len,
7289 u64 *ram_bytes, bool strict)
7291 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7292 struct btrfs_path *path;
7294 struct extent_buffer *leaf;
7295 struct btrfs_root *root = BTRFS_I(inode)->root;
7296 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7297 struct btrfs_file_extent_item *fi;
7298 struct btrfs_key key;
7305 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7307 path = btrfs_alloc_path();
7311 ret = btrfs_lookup_file_extent(NULL, root, path,
7312 btrfs_ino(BTRFS_I(inode)), offset, 0);
7316 slot = path->slots[0];
7319 /* can't find the item, must cow */
7326 leaf = path->nodes[0];
7327 btrfs_item_key_to_cpu(leaf, &key, slot);
7328 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7329 key.type != BTRFS_EXTENT_DATA_KEY) {
7330 /* not our file or wrong item type, must cow */
7334 if (key.offset > offset) {
7335 /* Wrong offset, must cow */
7339 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7340 found_type = btrfs_file_extent_type(leaf, fi);
7341 if (found_type != BTRFS_FILE_EXTENT_REG &&
7342 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7343 /* not a regular extent, must cow */
7347 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7350 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7351 if (extent_end <= offset)
7354 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7355 if (disk_bytenr == 0)
7358 if (btrfs_file_extent_compression(leaf, fi) ||
7359 btrfs_file_extent_encryption(leaf, fi) ||
7360 btrfs_file_extent_other_encoding(leaf, fi))
7364 * Do the same check as in btrfs_cross_ref_exist but without the
7365 * unnecessary search.
7368 (btrfs_file_extent_generation(leaf, fi) <=
7369 btrfs_root_last_snapshot(&root->root_item)))
7372 backref_offset = btrfs_file_extent_offset(leaf, fi);
7375 *orig_start = key.offset - backref_offset;
7376 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7377 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7380 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7383 num_bytes = min(offset + *len, extent_end) - offset;
7384 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7387 range_end = round_up(offset + num_bytes,
7388 root->fs_info->sectorsize) - 1;
7389 ret = test_range_bit(io_tree, offset, range_end,
7390 EXTENT_DELALLOC, 0, NULL);
7397 btrfs_release_path(path);
7400 * look for other files referencing this extent, if we
7401 * find any we must cow
7404 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7405 key.offset - backref_offset, disk_bytenr,
7413 * adjust disk_bytenr and num_bytes to cover just the bytes
7414 * in this extent we are about to write. If there
7415 * are any csums in that range we have to cow in order
7416 * to keep the csums correct
7418 disk_bytenr += backref_offset;
7419 disk_bytenr += offset - key.offset;
7420 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7423 * all of the above have passed, it is safe to overwrite this extent
7429 btrfs_free_path(path);
7433 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7434 struct extent_state **cached_state, bool writing)
7436 struct btrfs_ordered_extent *ordered;
7440 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7443 * We're concerned with the entire range that we're going to be
7444 * doing DIO to, so we need to make sure there's no ordered
7445 * extents in this range.
7447 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7448 lockend - lockstart + 1);
7451 * We need to make sure there are no buffered pages in this
7452 * range either, we could have raced between the invalidate in
7453 * generic_file_direct_write and locking the extent. The
7454 * invalidate needs to happen so that reads after a write do not
7458 (!writing || !filemap_range_has_page(inode->i_mapping,
7459 lockstart, lockend)))
7462 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7467 * If we are doing a DIO read and the ordered extent we
7468 * found is for a buffered write, we can not wait for it
7469 * to complete and retry, because if we do so we can
7470 * deadlock with concurrent buffered writes on page
7471 * locks. This happens only if our DIO read covers more
7472 * than one extent map, if at this point has already
7473 * created an ordered extent for a previous extent map
7474 * and locked its range in the inode's io tree, and a
7475 * concurrent write against that previous extent map's
7476 * range and this range started (we unlock the ranges
7477 * in the io tree only when the bios complete and
7478 * buffered writes always lock pages before attempting
7479 * to lock range in the io tree).
7482 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7483 btrfs_start_ordered_extent(ordered, 1);
7486 btrfs_put_ordered_extent(ordered);
7489 * We could trigger writeback for this range (and wait
7490 * for it to complete) and then invalidate the pages for
7491 * this range (through invalidate_inode_pages2_range()),
7492 * but that can lead us to a deadlock with a concurrent
7493 * call to readahead (a buffered read or a defrag call
7494 * triggered a readahead) on a page lock due to an
7495 * ordered dio extent we created before but did not have
7496 * yet a corresponding bio submitted (whence it can not
7497 * complete), which makes readahead wait for that
7498 * ordered extent to complete while holding a lock on
7513 /* The callers of this must take lock_extent() */
7514 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7515 u64 len, u64 orig_start, u64 block_start,
7516 u64 block_len, u64 orig_block_len,
7517 u64 ram_bytes, int compress_type,
7520 struct extent_map_tree *em_tree;
7521 struct extent_map *em;
7524 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7525 type == BTRFS_ORDERED_COMPRESSED ||
7526 type == BTRFS_ORDERED_NOCOW ||
7527 type == BTRFS_ORDERED_REGULAR);
7529 em_tree = &inode->extent_tree;
7530 em = alloc_extent_map();
7532 return ERR_PTR(-ENOMEM);
7535 em->orig_start = orig_start;
7537 em->block_len = block_len;
7538 em->block_start = block_start;
7539 em->orig_block_len = orig_block_len;
7540 em->ram_bytes = ram_bytes;
7541 em->generation = -1;
7542 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7543 if (type == BTRFS_ORDERED_PREALLOC) {
7544 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7545 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7546 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7547 em->compress_type = compress_type;
7551 btrfs_drop_extent_cache(inode, em->start,
7552 em->start + em->len - 1, 0);
7553 write_lock(&em_tree->lock);
7554 ret = add_extent_mapping(em_tree, em, 1);
7555 write_unlock(&em_tree->lock);
7557 * The caller has taken lock_extent(), who could race with us
7560 } while (ret == -EEXIST);
7563 free_extent_map(em);
7564 return ERR_PTR(ret);
7567 /* em got 2 refs now, callers needs to do free_extent_map once. */
7572 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7573 struct inode *inode,
7574 struct btrfs_dio_data *dio_data,
7577 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7578 struct extent_map *em = *map;
7582 * We don't allocate a new extent in the following cases
7584 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7586 * 2) The extent is marked as PREALLOC. We're good to go here and can
7587 * just use the extent.
7590 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7591 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7592 em->block_start != EXTENT_MAP_HOLE)) {
7594 u64 block_start, orig_start, orig_block_len, ram_bytes;
7596 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7597 type = BTRFS_ORDERED_PREALLOC;
7599 type = BTRFS_ORDERED_NOCOW;
7600 len = min(len, em->len - (start - em->start));
7601 block_start = em->block_start + (start - em->start);
7603 if (can_nocow_extent(inode, start, &len, &orig_start,
7604 &orig_block_len, &ram_bytes, false) == 1 &&
7605 btrfs_inc_nocow_writers(fs_info, block_start)) {
7606 struct extent_map *em2;
7608 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7609 orig_start, block_start,
7610 len, orig_block_len,
7612 btrfs_dec_nocow_writers(fs_info, block_start);
7613 if (type == BTRFS_ORDERED_PREALLOC) {
7614 free_extent_map(em);
7618 if (em2 && IS_ERR(em2)) {
7623 * For inode marked NODATACOW or extent marked PREALLOC,
7624 * use the existing or preallocated extent, so does not
7625 * need to adjust btrfs_space_info's bytes_may_use.
7627 btrfs_free_reserved_data_space_noquota(fs_info, len);
7632 /* this will cow the extent */
7633 free_extent_map(em);
7634 *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7640 len = min(len, em->len - (start - em->start));
7644 * Need to update the i_size under the extent lock so buffered
7645 * readers will get the updated i_size when we unlock.
7647 if (start + len > i_size_read(inode))
7648 i_size_write(inode, start + len);
7650 dio_data->reserve -= len;
7655 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7656 loff_t length, unsigned int flags, struct iomap *iomap,
7657 struct iomap *srcmap)
7659 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7660 struct extent_map *em;
7661 struct extent_state *cached_state = NULL;
7662 struct btrfs_dio_data *dio_data = NULL;
7663 u64 lockstart, lockend;
7664 const bool write = !!(flags & IOMAP_WRITE);
7667 bool unlock_extents = false;
7670 len = min_t(u64, len, fs_info->sectorsize);
7673 lockend = start + len - 1;
7676 * The generic stuff only does filemap_write_and_wait_range, which
7677 * isn't enough if we've written compressed pages to this area, so we
7678 * need to flush the dirty pages again to make absolutely sure that any
7679 * outstanding dirty pages are on disk.
7681 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7682 &BTRFS_I(inode)->runtime_flags)) {
7683 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7684 start + length - 1);
7689 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7693 dio_data->length = length;
7695 dio_data->reserve = round_up(length, fs_info->sectorsize);
7696 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7697 &dio_data->data_reserved,
7698 start, dio_data->reserve);
7700 extent_changeset_free(dio_data->data_reserved);
7705 iomap->private = dio_data;
7709 * If this errors out it's because we couldn't invalidate pagecache for
7710 * this range and we need to fallback to buffered.
7712 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7717 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7724 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7725 * io. INLINE is special, and we could probably kludge it in here, but
7726 * it's still buffered so for safety lets just fall back to the generic
7729 * For COMPRESSED we _have_ to read the entire extent in so we can
7730 * decompress it, so there will be buffering required no matter what we
7731 * do, so go ahead and fallback to buffered.
7733 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7734 * to buffered IO. Don't blame me, this is the price we pay for using
7737 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7738 em->block_start == EXTENT_MAP_INLINE) {
7739 free_extent_map(em);
7744 len = min(len, em->len - (start - em->start));
7746 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7750 unlock_extents = true;
7751 /* Recalc len in case the new em is smaller than requested */
7752 len = min(len, em->len - (start - em->start));
7755 * We need to unlock only the end area that we aren't using.
7756 * The rest is going to be unlocked by the endio routine.
7758 lockstart = start + len;
7759 if (lockstart < lockend)
7760 unlock_extents = true;
7764 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7765 lockstart, lockend, &cached_state);
7767 free_extent_state(cached_state);
7770 * Translate extent map information to iomap.
7771 * We trim the extents (and move the addr) even though iomap code does
7772 * that, since we have locked only the parts we are performing I/O in.
7774 if ((em->block_start == EXTENT_MAP_HOLE) ||
7775 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7776 iomap->addr = IOMAP_NULL_ADDR;
7777 iomap->type = IOMAP_HOLE;
7779 iomap->addr = em->block_start + (start - em->start);
7780 iomap->type = IOMAP_MAPPED;
7782 iomap->offset = start;
7783 iomap->bdev = fs_info->fs_devices->latest_bdev;
7784 iomap->length = len;
7786 if (write && btrfs_use_zone_append(BTRFS_I(inode), em))
7787 iomap->flags |= IOMAP_F_ZONE_APPEND;
7789 free_extent_map(em);
7794 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7798 btrfs_delalloc_release_space(BTRFS_I(inode),
7799 dio_data->data_reserved, start,
7800 dio_data->reserve, true);
7801 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7802 extent_changeset_free(dio_data->data_reserved);
7808 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7809 ssize_t written, unsigned int flags, struct iomap *iomap)
7812 struct btrfs_dio_data *dio_data = iomap->private;
7813 size_t submitted = dio_data->submitted;
7814 const bool write = !!(flags & IOMAP_WRITE);
7816 if (!write && (iomap->type == IOMAP_HOLE)) {
7817 /* If reading from a hole, unlock and return */
7818 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7822 if (submitted < length) {
7824 length -= submitted;
7826 __endio_write_update_ordered(BTRFS_I(inode), pos,
7829 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7835 if (dio_data->reserve)
7836 btrfs_delalloc_release_space(BTRFS_I(inode),
7837 dio_data->data_reserved, pos,
7838 dio_data->reserve, true);
7839 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7840 extent_changeset_free(dio_data->data_reserved);
7844 iomap->private = NULL;
7849 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7852 * This implies a barrier so that stores to dio_bio->bi_status before
7853 * this and loads of dio_bio->bi_status after this are fully ordered.
7855 if (!refcount_dec_and_test(&dip->refs))
7858 if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
7859 __endio_write_update_ordered(BTRFS_I(dip->inode),
7860 dip->logical_offset,
7862 !dip->dio_bio->bi_status);
7864 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7865 dip->logical_offset,
7866 dip->logical_offset + dip->bytes - 1);
7869 bio_endio(dip->dio_bio);
7873 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7875 unsigned long bio_flags)
7877 struct btrfs_dio_private *dip = bio->bi_private;
7878 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7881 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7883 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7887 refcount_inc(&dip->refs);
7888 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7890 refcount_dec(&dip->refs);
7894 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7895 struct btrfs_io_bio *io_bio,
7896 const bool uptodate)
7898 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7899 const u32 sectorsize = fs_info->sectorsize;
7900 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7901 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7902 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7903 struct bio_vec bvec;
7904 struct bvec_iter iter;
7905 u64 start = io_bio->logical;
7907 blk_status_t err = BLK_STS_OK;
7909 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7910 unsigned int i, nr_sectors, pgoff;
7912 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7913 pgoff = bvec.bv_offset;
7914 for (i = 0; i < nr_sectors; i++) {
7915 ASSERT(pgoff < PAGE_SIZE);
7917 (!csum || !check_data_csum(inode, io_bio,
7918 bio_offset, bvec.bv_page,
7920 clean_io_failure(fs_info, failure_tree, io_tree,
7921 start, bvec.bv_page,
7922 btrfs_ino(BTRFS_I(inode)),
7925 blk_status_t status;
7927 ASSERT((start - io_bio->logical) < UINT_MAX);
7928 status = btrfs_submit_read_repair(inode,
7930 start - io_bio->logical,
7931 bvec.bv_page, pgoff,
7933 start + sectorsize - 1,
7935 submit_dio_repair_bio);
7939 start += sectorsize;
7940 ASSERT(bio_offset + sectorsize > bio_offset);
7941 bio_offset += sectorsize;
7942 pgoff += sectorsize;
7948 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7949 const u64 offset, const u64 bytes,
7950 const bool uptodate)
7952 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7953 struct btrfs_ordered_extent *ordered = NULL;
7954 struct btrfs_workqueue *wq;
7955 u64 ordered_offset = offset;
7956 u64 ordered_bytes = bytes;
7959 if (btrfs_is_free_space_inode(inode))
7960 wq = fs_info->endio_freespace_worker;
7962 wq = fs_info->endio_write_workers;
7964 while (ordered_offset < offset + bytes) {
7965 last_offset = ordered_offset;
7966 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7970 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7972 btrfs_queue_work(wq, &ordered->work);
7975 /* No ordered extent found in the range, exit */
7976 if (ordered_offset == last_offset)
7979 * Our bio might span multiple ordered extents. In this case
7980 * we keep going until we have accounted the whole dio.
7982 if (ordered_offset < offset + bytes) {
7983 ordered_bytes = offset + bytes - ordered_offset;
7989 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7991 u64 dio_file_offset)
7993 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, 1);
7996 static void btrfs_end_dio_bio(struct bio *bio)
7998 struct btrfs_dio_private *dip = bio->bi_private;
7999 blk_status_t err = bio->bi_status;
8002 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8003 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8004 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8005 bio->bi_opf, bio->bi_iter.bi_sector,
8006 bio->bi_iter.bi_size, err);
8008 if (bio_op(bio) == REQ_OP_READ) {
8009 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
8014 dip->dio_bio->bi_status = err;
8016 btrfs_record_physical_zoned(dip->inode, dip->logical_offset, bio);
8019 btrfs_dio_private_put(dip);
8022 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8023 struct inode *inode, u64 file_offset, int async_submit)
8025 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8026 struct btrfs_dio_private *dip = bio->bi_private;
8027 bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
8030 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8032 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8035 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8040 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8043 if (write && async_submit) {
8044 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
8045 btrfs_submit_bio_start_direct_io);
8049 * If we aren't doing async submit, calculate the csum of the
8052 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
8058 csum_offset = file_offset - dip->logical_offset;
8059 csum_offset >>= fs_info->sectorsize_bits;
8060 csum_offset *= fs_info->csum_size;
8061 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
8064 ret = btrfs_map_bio(fs_info, bio, 0);
8070 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
8071 * or ordered extents whether or not we submit any bios.
8073 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
8074 struct inode *inode,
8077 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8078 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8080 struct btrfs_dio_private *dip;
8082 dip_size = sizeof(*dip);
8083 if (!write && csum) {
8084 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8087 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
8088 dip_size += fs_info->csum_size * nblocks;
8091 dip = kzalloc(dip_size, GFP_NOFS);
8096 dip->logical_offset = file_offset;
8097 dip->bytes = dio_bio->bi_iter.bi_size;
8098 dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
8099 dip->dio_bio = dio_bio;
8100 refcount_set(&dip->refs, 1);
8104 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
8105 struct bio *dio_bio, loff_t file_offset)
8107 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8108 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8109 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8110 BTRFS_BLOCK_GROUP_RAID56_MASK);
8111 struct btrfs_dio_private *dip;
8114 int async_submit = 0;
8116 int clone_offset = 0;
8120 blk_status_t status;
8121 struct btrfs_io_geometry geom;
8122 struct btrfs_dio_data *dio_data = iomap->private;
8123 struct extent_map *em = NULL;
8125 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
8128 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8129 file_offset + dio_bio->bi_iter.bi_size - 1);
8131 dio_bio->bi_status = BLK_STS_RESOURCE;
8133 return BLK_QC_T_NONE;
8138 * Load the csums up front to reduce csum tree searches and
8139 * contention when submitting bios.
8141 * If we have csums disabled this will do nothing.
8143 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8144 if (status != BLK_STS_OK)
8148 start_sector = dio_bio->bi_iter.bi_sector;
8149 submit_len = dio_bio->bi_iter.bi_size;
8152 logical = start_sector << 9;
8153 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8155 status = errno_to_blk_status(PTR_ERR(em));
8159 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8160 logical, submit_len, &geom);
8162 status = errno_to_blk_status(ret);
8165 ASSERT(geom.len <= INT_MAX);
8167 clone_len = min_t(int, submit_len, geom.len);
8170 * This will never fail as it's passing GPF_NOFS and
8171 * the allocation is backed by btrfs_bioset.
8173 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8174 bio->bi_private = dip;
8175 bio->bi_end_io = btrfs_end_dio_bio;
8176 btrfs_io_bio(bio)->logical = file_offset;
8178 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8179 status = extract_ordered_extent(BTRFS_I(inode), bio,
8187 ASSERT(submit_len >= clone_len);
8188 submit_len -= clone_len;
8191 * Increase the count before we submit the bio so we know
8192 * the end IO handler won't happen before we increase the
8193 * count. Otherwise, the dip might get freed before we're
8194 * done setting it up.
8196 * We transfer the initial reference to the last bio, so we
8197 * don't need to increment the reference count for the last one.
8199 if (submit_len > 0) {
8200 refcount_inc(&dip->refs);
8202 * If we are submitting more than one bio, submit them
8203 * all asynchronously. The exception is RAID 5 or 6, as
8204 * asynchronous checksums make it difficult to collect
8205 * full stripe writes.
8211 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8216 refcount_dec(&dip->refs);
8220 dio_data->submitted += clone_len;
8221 clone_offset += clone_len;
8222 start_sector += clone_len >> 9;
8223 file_offset += clone_len;
8225 free_extent_map(em);
8226 } while (submit_len > 0);
8227 return BLK_QC_T_NONE;
8230 free_extent_map(em);
8232 dip->dio_bio->bi_status = status;
8233 btrfs_dio_private_put(dip);
8235 return BLK_QC_T_NONE;
8238 const struct iomap_ops btrfs_dio_iomap_ops = {
8239 .iomap_begin = btrfs_dio_iomap_begin,
8240 .iomap_end = btrfs_dio_iomap_end,
8243 const struct iomap_dio_ops btrfs_dio_ops = {
8244 .submit_io = btrfs_submit_direct,
8247 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8252 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8256 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8259 int btrfs_readpage(struct file *file, struct page *page)
8261 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8262 u64 start = page_offset(page);
8263 u64 end = start + PAGE_SIZE - 1;
8264 unsigned long bio_flags = 0;
8265 struct bio *bio = NULL;
8268 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8270 ret = btrfs_do_readpage(page, NULL, &bio, &bio_flags, 0, NULL);
8272 ret = submit_one_bio(bio, 0, bio_flags);
8276 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8278 struct inode *inode = page->mapping->host;
8281 if (current->flags & PF_MEMALLOC) {
8282 redirty_page_for_writepage(wbc, page);
8288 * If we are under memory pressure we will call this directly from the
8289 * VM, we need to make sure we have the inode referenced for the ordered
8290 * extent. If not just return like we didn't do anything.
8292 if (!igrab(inode)) {
8293 redirty_page_for_writepage(wbc, page);
8294 return AOP_WRITEPAGE_ACTIVATE;
8296 ret = extent_write_full_page(page, wbc);
8297 btrfs_add_delayed_iput(inode);
8301 static int btrfs_writepages(struct address_space *mapping,
8302 struct writeback_control *wbc)
8304 return extent_writepages(mapping, wbc);
8307 static void btrfs_readahead(struct readahead_control *rac)
8309 extent_readahead(rac);
8312 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8314 int ret = try_release_extent_mapping(page, gfp_flags);
8316 clear_page_extent_mapped(page);
8320 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8322 if (PageWriteback(page) || PageDirty(page))
8324 return __btrfs_releasepage(page, gfp_flags);
8327 #ifdef CONFIG_MIGRATION
8328 static int btrfs_migratepage(struct address_space *mapping,
8329 struct page *newpage, struct page *page,
8330 enum migrate_mode mode)
8334 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8335 if (ret != MIGRATEPAGE_SUCCESS)
8338 if (page_has_private(page))
8339 attach_page_private(newpage, detach_page_private(page));
8341 if (PagePrivate2(page)) {
8342 ClearPagePrivate2(page);
8343 SetPagePrivate2(newpage);
8346 if (mode != MIGRATE_SYNC_NO_COPY)
8347 migrate_page_copy(newpage, page);
8349 migrate_page_states(newpage, page);
8350 return MIGRATEPAGE_SUCCESS;
8354 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8355 unsigned int length)
8357 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8358 struct extent_io_tree *tree = &inode->io_tree;
8359 struct btrfs_ordered_extent *ordered;
8360 struct extent_state *cached_state = NULL;
8361 u64 page_start = page_offset(page);
8362 u64 page_end = page_start + PAGE_SIZE - 1;
8365 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8366 bool found_ordered = false;
8367 bool completed_ordered = false;
8370 * we have the page locked, so new writeback can't start,
8371 * and the dirty bit won't be cleared while we are here.
8373 * Wait for IO on this page so that we can safely clear
8374 * the PagePrivate2 bit and do ordered accounting
8376 wait_on_page_writeback(page);
8379 btrfs_releasepage(page, GFP_NOFS);
8383 if (!inode_evicting)
8384 lock_extent_bits(tree, page_start, page_end, &cached_state);
8388 ordered = btrfs_lookup_ordered_range(inode, start, page_end - start + 1);
8390 found_ordered = true;
8392 ordered->file_offset + ordered->num_bytes - 1);
8394 * IO on this page will never be started, so we need to account
8395 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8396 * here, must leave that up for the ordered extent completion.
8398 if (!inode_evicting)
8399 clear_extent_bit(tree, start, end,
8401 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8402 EXTENT_DEFRAG, 1, 0, &cached_state);
8404 * whoever cleared the private bit is responsible
8405 * for the finish_ordered_io
8407 if (TestClearPagePrivate2(page)) {
8408 struct btrfs_ordered_inode_tree *tree;
8411 tree = &inode->ordered_tree;
8413 spin_lock_irq(&tree->lock);
8414 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8415 new_len = start - ordered->file_offset;
8416 if (new_len < ordered->truncated_len)
8417 ordered->truncated_len = new_len;
8418 spin_unlock_irq(&tree->lock);
8420 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8422 end - start + 1, 1)) {
8423 btrfs_finish_ordered_io(ordered);
8424 completed_ordered = true;
8427 btrfs_put_ordered_extent(ordered);
8428 if (!inode_evicting) {
8429 cached_state = NULL;
8430 lock_extent_bits(tree, start, end,
8435 if (start < page_end)
8440 * Qgroup reserved space handler
8441 * Page here will be either
8442 * 1) Already written to disk or ordered extent already submitted
8443 * Then its QGROUP_RESERVED bit in io_tree is already cleaned.
8444 * Qgroup will be handled by its qgroup_record then.
8445 * btrfs_qgroup_free_data() call will do nothing here.
8447 * 2) Not written to disk yet
8448 * Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED
8449 * bit of its io_tree, and free the qgroup reserved data space.
8450 * Since the IO will never happen for this page.
8452 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8453 if (!inode_evicting) {
8457 * If there's an ordered extent for this range and we have not
8458 * finished it ourselves, we must leave EXTENT_DELALLOC_NEW set
8459 * in the range for the ordered extent completion. We must also
8460 * not delete the range, otherwise we would lose that bit (and
8461 * any other bits set in the range). Make sure EXTENT_UPTODATE
8462 * is cleared if we don't delete, otherwise it can lead to
8463 * corruptions if the i_size is extented later.
8465 if (found_ordered && !completed_ordered)
8467 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8468 EXTENT_DELALLOC | EXTENT_UPTODATE |
8469 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8470 delete, &cached_state);
8472 __btrfs_releasepage(page, GFP_NOFS);
8475 ClearPageChecked(page);
8476 clear_page_extent_mapped(page);
8480 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8481 * called from a page fault handler when a page is first dirtied. Hence we must
8482 * be careful to check for EOF conditions here. We set the page up correctly
8483 * for a written page which means we get ENOSPC checking when writing into
8484 * holes and correct delalloc and unwritten extent mapping on filesystems that
8485 * support these features.
8487 * We are not allowed to take the i_mutex here so we have to play games to
8488 * protect against truncate races as the page could now be beyond EOF. Because
8489 * truncate_setsize() writes the inode size before removing pages, once we have
8490 * the page lock we can determine safely if the page is beyond EOF. If it is not
8491 * beyond EOF, then the page is guaranteed safe against truncation until we
8494 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8496 struct page *page = vmf->page;
8497 struct inode *inode = file_inode(vmf->vma->vm_file);
8498 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8499 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8500 struct btrfs_ordered_extent *ordered;
8501 struct extent_state *cached_state = NULL;
8502 struct extent_changeset *data_reserved = NULL;
8504 unsigned long zero_start;
8514 reserved_space = PAGE_SIZE;
8516 sb_start_pagefault(inode->i_sb);
8517 page_start = page_offset(page);
8518 page_end = page_start + PAGE_SIZE - 1;
8522 * Reserving delalloc space after obtaining the page lock can lead to
8523 * deadlock. For example, if a dirty page is locked by this function
8524 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8525 * dirty page write out, then the btrfs_writepage() function could
8526 * end up waiting indefinitely to get a lock on the page currently
8527 * being processed by btrfs_page_mkwrite() function.
8529 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8530 page_start, reserved_space);
8532 ret2 = file_update_time(vmf->vma->vm_file);
8536 ret = vmf_error(ret2);
8542 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8545 size = i_size_read(inode);
8547 if ((page->mapping != inode->i_mapping) ||
8548 (page_start >= size)) {
8549 /* page got truncated out from underneath us */
8552 wait_on_page_writeback(page);
8554 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8555 ret2 = set_page_extent_mapped(page);
8557 ret = vmf_error(ret2);
8558 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8563 * we can't set the delalloc bits if there are pending ordered
8564 * extents. Drop our locks and wait for them to finish
8566 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8569 unlock_extent_cached(io_tree, page_start, page_end,
8572 btrfs_start_ordered_extent(ordered, 1);
8573 btrfs_put_ordered_extent(ordered);
8577 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8578 reserved_space = round_up(size - page_start,
8579 fs_info->sectorsize);
8580 if (reserved_space < PAGE_SIZE) {
8581 end = page_start + reserved_space - 1;
8582 btrfs_delalloc_release_space(BTRFS_I(inode),
8583 data_reserved, page_start,
8584 PAGE_SIZE - reserved_space, true);
8589 * page_mkwrite gets called when the page is firstly dirtied after it's
8590 * faulted in, but write(2) could also dirty a page and set delalloc
8591 * bits, thus in this case for space account reason, we still need to
8592 * clear any delalloc bits within this page range since we have to
8593 * reserve data&meta space before lock_page() (see above comments).
8595 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8596 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8597 EXTENT_DEFRAG, 0, 0, &cached_state);
8599 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8602 unlock_extent_cached(io_tree, page_start, page_end,
8604 ret = VM_FAULT_SIGBUS;
8608 /* page is wholly or partially inside EOF */
8609 if (page_start + PAGE_SIZE > size)
8610 zero_start = offset_in_page(size);
8612 zero_start = PAGE_SIZE;
8614 if (zero_start != PAGE_SIZE) {
8616 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8617 flush_dcache_page(page);
8620 ClearPageChecked(page);
8621 set_page_dirty(page);
8622 SetPageUptodate(page);
8624 BTRFS_I(inode)->last_trans = fs_info->generation;
8625 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8626 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8628 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8630 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8631 sb_end_pagefault(inode->i_sb);
8632 extent_changeset_free(data_reserved);
8633 return VM_FAULT_LOCKED;
8638 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8639 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8640 reserved_space, (ret != 0));
8642 sb_end_pagefault(inode->i_sb);
8643 extent_changeset_free(data_reserved);
8647 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8649 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8650 struct btrfs_root *root = BTRFS_I(inode)->root;
8651 struct btrfs_block_rsv *rsv;
8653 struct btrfs_trans_handle *trans;
8654 u64 mask = fs_info->sectorsize - 1;
8655 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8657 if (!skip_writeback) {
8658 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8665 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8666 * things going on here:
8668 * 1) We need to reserve space to update our inode.
8670 * 2) We need to have something to cache all the space that is going to
8671 * be free'd up by the truncate operation, but also have some slack
8672 * space reserved in case it uses space during the truncate (thank you
8673 * very much snapshotting).
8675 * And we need these to be separate. The fact is we can use a lot of
8676 * space doing the truncate, and we have no earthly idea how much space
8677 * we will use, so we need the truncate reservation to be separate so it
8678 * doesn't end up using space reserved for updating the inode. We also
8679 * need to be able to stop the transaction and start a new one, which
8680 * means we need to be able to update the inode several times, and we
8681 * have no idea of knowing how many times that will be, so we can't just
8682 * reserve 1 item for the entirety of the operation, so that has to be
8683 * done separately as well.
8685 * So that leaves us with
8687 * 1) rsv - for the truncate reservation, which we will steal from the
8688 * transaction reservation.
8689 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8690 * updating the inode.
8692 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8695 rsv->size = min_size;
8699 * 1 for the truncate slack space
8700 * 1 for updating the inode.
8702 trans = btrfs_start_transaction(root, 2);
8703 if (IS_ERR(trans)) {
8704 ret = PTR_ERR(trans);
8708 /* Migrate the slack space for the truncate to our reserve */
8709 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8714 * So if we truncate and then write and fsync we normally would just
8715 * write the extents that changed, which is a problem if we need to
8716 * first truncate that entire inode. So set this flag so we write out
8717 * all of the extents in the inode to the sync log so we're completely
8720 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8721 trans->block_rsv = rsv;
8724 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
8726 BTRFS_EXTENT_DATA_KEY);
8727 trans->block_rsv = &fs_info->trans_block_rsv;
8728 if (ret != -ENOSPC && ret != -EAGAIN)
8731 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8735 btrfs_end_transaction(trans);
8736 btrfs_btree_balance_dirty(fs_info);
8738 trans = btrfs_start_transaction(root, 2);
8739 if (IS_ERR(trans)) {
8740 ret = PTR_ERR(trans);
8745 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8746 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8747 rsv, min_size, false);
8748 BUG_ON(ret); /* shouldn't happen */
8749 trans->block_rsv = rsv;
8753 * We can't call btrfs_truncate_block inside a trans handle as we could
8754 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8755 * we've truncated everything except the last little bit, and can do
8756 * btrfs_truncate_block and then update the disk_i_size.
8758 if (ret == NEED_TRUNCATE_BLOCK) {
8759 btrfs_end_transaction(trans);
8760 btrfs_btree_balance_dirty(fs_info);
8762 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8765 trans = btrfs_start_transaction(root, 1);
8766 if (IS_ERR(trans)) {
8767 ret = PTR_ERR(trans);
8770 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8776 trans->block_rsv = &fs_info->trans_block_rsv;
8777 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8781 ret2 = btrfs_end_transaction(trans);
8784 btrfs_btree_balance_dirty(fs_info);
8787 btrfs_free_block_rsv(fs_info, rsv);
8793 * create a new subvolume directory/inode (helper for the ioctl).
8795 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8796 struct btrfs_root *new_root,
8797 struct btrfs_root *parent_root)
8799 struct inode *inode;
8804 err = btrfs_get_free_objectid(new_root, &ino);
8808 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, ino, ino,
8809 S_IFDIR | (~current_umask() & S_IRWXUGO),
8812 return PTR_ERR(inode);
8813 inode->i_op = &btrfs_dir_inode_operations;
8814 inode->i_fop = &btrfs_dir_file_operations;
8816 set_nlink(inode, 1);
8817 btrfs_i_size_write(BTRFS_I(inode), 0);
8818 unlock_new_inode(inode);
8820 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8822 btrfs_err(new_root->fs_info,
8823 "error inheriting subvolume %llu properties: %d",
8824 new_root->root_key.objectid, err);
8826 err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
8832 struct inode *btrfs_alloc_inode(struct super_block *sb)
8834 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8835 struct btrfs_inode *ei;
8836 struct inode *inode;
8838 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8845 ei->last_sub_trans = 0;
8846 ei->logged_trans = 0;
8847 ei->delalloc_bytes = 0;
8848 ei->new_delalloc_bytes = 0;
8849 ei->defrag_bytes = 0;
8850 ei->disk_i_size = 0;
8853 ei->index_cnt = (u64)-1;
8855 ei->last_unlink_trans = 0;
8856 ei->last_reflink_trans = 0;
8857 ei->last_log_commit = 0;
8859 spin_lock_init(&ei->lock);
8860 ei->outstanding_extents = 0;
8861 if (sb->s_magic != BTRFS_TEST_MAGIC)
8862 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8863 BTRFS_BLOCK_RSV_DELALLOC);
8864 ei->runtime_flags = 0;
8865 ei->prop_compress = BTRFS_COMPRESS_NONE;
8866 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8868 ei->delayed_node = NULL;
8870 ei->i_otime.tv_sec = 0;
8871 ei->i_otime.tv_nsec = 0;
8873 inode = &ei->vfs_inode;
8874 extent_map_tree_init(&ei->extent_tree);
8875 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8876 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8877 IO_TREE_INODE_IO_FAILURE, inode);
8878 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8879 IO_TREE_INODE_FILE_EXTENT, inode);
8880 ei->io_tree.track_uptodate = true;
8881 ei->io_failure_tree.track_uptodate = true;
8882 atomic_set(&ei->sync_writers, 0);
8883 mutex_init(&ei->log_mutex);
8884 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8885 INIT_LIST_HEAD(&ei->delalloc_inodes);
8886 INIT_LIST_HEAD(&ei->delayed_iput);
8887 RB_CLEAR_NODE(&ei->rb_node);
8892 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8893 void btrfs_test_destroy_inode(struct inode *inode)
8895 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8896 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8900 void btrfs_free_inode(struct inode *inode)
8902 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8905 void btrfs_destroy_inode(struct inode *vfs_inode)
8907 struct btrfs_ordered_extent *ordered;
8908 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8909 struct btrfs_root *root = inode->root;
8911 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8912 WARN_ON(vfs_inode->i_data.nrpages);
8913 WARN_ON(inode->block_rsv.reserved);
8914 WARN_ON(inode->block_rsv.size);
8915 WARN_ON(inode->outstanding_extents);
8916 WARN_ON(inode->delalloc_bytes);
8917 WARN_ON(inode->new_delalloc_bytes);
8918 WARN_ON(inode->csum_bytes);
8919 WARN_ON(inode->defrag_bytes);
8922 * This can happen where we create an inode, but somebody else also
8923 * created the same inode and we need to destroy the one we already
8930 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8934 btrfs_err(root->fs_info,
8935 "found ordered extent %llu %llu on inode cleanup",
8936 ordered->file_offset, ordered->num_bytes);
8937 btrfs_remove_ordered_extent(inode, ordered);
8938 btrfs_put_ordered_extent(ordered);
8939 btrfs_put_ordered_extent(ordered);
8942 btrfs_qgroup_check_reserved_leak(inode);
8943 inode_tree_del(inode);
8944 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8945 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8946 btrfs_put_root(inode->root);
8949 int btrfs_drop_inode(struct inode *inode)
8951 struct btrfs_root *root = BTRFS_I(inode)->root;
8956 /* the snap/subvol tree is on deleting */
8957 if (btrfs_root_refs(&root->root_item) == 0)
8960 return generic_drop_inode(inode);
8963 static void init_once(void *foo)
8965 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8967 inode_init_once(&ei->vfs_inode);
8970 void __cold btrfs_destroy_cachep(void)
8973 * Make sure all delayed rcu free inodes are flushed before we
8977 kmem_cache_destroy(btrfs_inode_cachep);
8978 kmem_cache_destroy(btrfs_trans_handle_cachep);
8979 kmem_cache_destroy(btrfs_path_cachep);
8980 kmem_cache_destroy(btrfs_free_space_cachep);
8981 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8984 int __init btrfs_init_cachep(void)
8986 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8987 sizeof(struct btrfs_inode), 0,
8988 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8990 if (!btrfs_inode_cachep)
8993 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8994 sizeof(struct btrfs_trans_handle), 0,
8995 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8996 if (!btrfs_trans_handle_cachep)
8999 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9000 sizeof(struct btrfs_path), 0,
9001 SLAB_MEM_SPREAD, NULL);
9002 if (!btrfs_path_cachep)
9005 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9006 sizeof(struct btrfs_free_space), 0,
9007 SLAB_MEM_SPREAD, NULL);
9008 if (!btrfs_free_space_cachep)
9011 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9012 PAGE_SIZE, PAGE_SIZE,
9013 SLAB_MEM_SPREAD, NULL);
9014 if (!btrfs_free_space_bitmap_cachep)
9019 btrfs_destroy_cachep();
9023 static int btrfs_getattr(struct user_namespace *mnt_userns,
9024 const struct path *path, struct kstat *stat,
9025 u32 request_mask, unsigned int flags)
9029 struct inode *inode = d_inode(path->dentry);
9030 u32 blocksize = inode->i_sb->s_blocksize;
9031 u32 bi_flags = BTRFS_I(inode)->flags;
9033 stat->result_mask |= STATX_BTIME;
9034 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9035 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9036 if (bi_flags & BTRFS_INODE_APPEND)
9037 stat->attributes |= STATX_ATTR_APPEND;
9038 if (bi_flags & BTRFS_INODE_COMPRESS)
9039 stat->attributes |= STATX_ATTR_COMPRESSED;
9040 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9041 stat->attributes |= STATX_ATTR_IMMUTABLE;
9042 if (bi_flags & BTRFS_INODE_NODUMP)
9043 stat->attributes |= STATX_ATTR_NODUMP;
9045 stat->attributes_mask |= (STATX_ATTR_APPEND |
9046 STATX_ATTR_COMPRESSED |
9047 STATX_ATTR_IMMUTABLE |
9050 generic_fillattr(&init_user_ns, inode, stat);
9051 stat->dev = BTRFS_I(inode)->root->anon_dev;
9053 spin_lock(&BTRFS_I(inode)->lock);
9054 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9055 inode_bytes = inode_get_bytes(inode);
9056 spin_unlock(&BTRFS_I(inode)->lock);
9057 stat->blocks = (ALIGN(inode_bytes, blocksize) +
9058 ALIGN(delalloc_bytes, blocksize)) >> 9;
9062 static int btrfs_rename_exchange(struct inode *old_dir,
9063 struct dentry *old_dentry,
9064 struct inode *new_dir,
9065 struct dentry *new_dentry)
9067 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9068 struct btrfs_trans_handle *trans;
9069 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9070 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9071 struct inode *new_inode = new_dentry->d_inode;
9072 struct inode *old_inode = old_dentry->d_inode;
9073 struct timespec64 ctime = current_time(old_inode);
9074 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9075 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9080 bool root_log_pinned = false;
9081 bool dest_log_pinned = false;
9083 /* we only allow rename subvolume link between subvolumes */
9084 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9087 /* close the race window with snapshot create/destroy ioctl */
9088 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9089 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9090 down_read(&fs_info->subvol_sem);
9093 * We want to reserve the absolute worst case amount of items. So if
9094 * both inodes are subvols and we need to unlink them then that would
9095 * require 4 item modifications, but if they are both normal inodes it
9096 * would require 5 item modifications, so we'll assume their normal
9097 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9098 * should cover the worst case number of items we'll modify.
9100 trans = btrfs_start_transaction(root, 12);
9101 if (IS_ERR(trans)) {
9102 ret = PTR_ERR(trans);
9107 btrfs_record_root_in_trans(trans, dest);
9110 * We need to find a free sequence number both in the source and
9111 * in the destination directory for the exchange.
9113 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9116 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9120 BTRFS_I(old_inode)->dir_index = 0ULL;
9121 BTRFS_I(new_inode)->dir_index = 0ULL;
9123 /* Reference for the source. */
9124 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9125 /* force full log commit if subvolume involved. */
9126 btrfs_set_log_full_commit(trans);
9128 btrfs_pin_log_trans(root);
9129 root_log_pinned = true;
9130 ret = btrfs_insert_inode_ref(trans, dest,
9131 new_dentry->d_name.name,
9132 new_dentry->d_name.len,
9134 btrfs_ino(BTRFS_I(new_dir)),
9140 /* And now for the dest. */
9141 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9142 /* force full log commit if subvolume involved. */
9143 btrfs_set_log_full_commit(trans);
9145 btrfs_pin_log_trans(dest);
9146 dest_log_pinned = true;
9147 ret = btrfs_insert_inode_ref(trans, root,
9148 old_dentry->d_name.name,
9149 old_dentry->d_name.len,
9151 btrfs_ino(BTRFS_I(old_dir)),
9157 /* Update inode version and ctime/mtime. */
9158 inode_inc_iversion(old_dir);
9159 inode_inc_iversion(new_dir);
9160 inode_inc_iversion(old_inode);
9161 inode_inc_iversion(new_inode);
9162 old_dir->i_ctime = old_dir->i_mtime = ctime;
9163 new_dir->i_ctime = new_dir->i_mtime = ctime;
9164 old_inode->i_ctime = ctime;
9165 new_inode->i_ctime = ctime;
9167 if (old_dentry->d_parent != new_dentry->d_parent) {
9168 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9169 BTRFS_I(old_inode), 1);
9170 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9171 BTRFS_I(new_inode), 1);
9174 /* src is a subvolume */
9175 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9176 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9177 } else { /* src is an inode */
9178 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9179 BTRFS_I(old_dentry->d_inode),
9180 old_dentry->d_name.name,
9181 old_dentry->d_name.len);
9183 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9186 btrfs_abort_transaction(trans, ret);
9190 /* dest is a subvolume */
9191 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9192 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9193 } else { /* dest is an inode */
9194 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9195 BTRFS_I(new_dentry->d_inode),
9196 new_dentry->d_name.name,
9197 new_dentry->d_name.len);
9199 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9202 btrfs_abort_transaction(trans, ret);
9206 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9207 new_dentry->d_name.name,
9208 new_dentry->d_name.len, 0, old_idx);
9210 btrfs_abort_transaction(trans, ret);
9214 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9215 old_dentry->d_name.name,
9216 old_dentry->d_name.len, 0, new_idx);
9218 btrfs_abort_transaction(trans, ret);
9222 if (old_inode->i_nlink == 1)
9223 BTRFS_I(old_inode)->dir_index = old_idx;
9224 if (new_inode->i_nlink == 1)
9225 BTRFS_I(new_inode)->dir_index = new_idx;
9227 if (root_log_pinned) {
9228 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9229 new_dentry->d_parent);
9230 btrfs_end_log_trans(root);
9231 root_log_pinned = false;
9233 if (dest_log_pinned) {
9234 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9235 old_dentry->d_parent);
9236 btrfs_end_log_trans(dest);
9237 dest_log_pinned = false;
9241 * If we have pinned a log and an error happened, we unpin tasks
9242 * trying to sync the log and force them to fallback to a transaction
9243 * commit if the log currently contains any of the inodes involved in
9244 * this rename operation (to ensure we do not persist a log with an
9245 * inconsistent state for any of these inodes or leading to any
9246 * inconsistencies when replayed). If the transaction was aborted, the
9247 * abortion reason is propagated to userspace when attempting to commit
9248 * the transaction. If the log does not contain any of these inodes, we
9249 * allow the tasks to sync it.
9251 if (ret && (root_log_pinned || dest_log_pinned)) {
9252 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9253 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9254 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9256 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9257 btrfs_set_log_full_commit(trans);
9259 if (root_log_pinned) {
9260 btrfs_end_log_trans(root);
9261 root_log_pinned = false;
9263 if (dest_log_pinned) {
9264 btrfs_end_log_trans(dest);
9265 dest_log_pinned = false;
9268 ret2 = btrfs_end_transaction(trans);
9269 ret = ret ? ret : ret2;
9271 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9272 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9273 up_read(&fs_info->subvol_sem);
9278 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9279 struct btrfs_root *root,
9281 struct dentry *dentry)
9284 struct inode *inode;
9288 ret = btrfs_get_free_objectid(root, &objectid);
9292 inode = btrfs_new_inode(trans, root, dir,
9293 dentry->d_name.name,
9295 btrfs_ino(BTRFS_I(dir)),
9297 S_IFCHR | WHITEOUT_MODE,
9300 if (IS_ERR(inode)) {
9301 ret = PTR_ERR(inode);
9305 inode->i_op = &btrfs_special_inode_operations;
9306 init_special_inode(inode, inode->i_mode,
9309 ret = btrfs_init_inode_security(trans, inode, dir,
9314 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9315 BTRFS_I(inode), 0, index);
9319 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9321 unlock_new_inode(inode);
9323 inode_dec_link_count(inode);
9329 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9330 struct inode *new_dir, struct dentry *new_dentry,
9333 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9334 struct btrfs_trans_handle *trans;
9335 unsigned int trans_num_items;
9336 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9337 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9338 struct inode *new_inode = d_inode(new_dentry);
9339 struct inode *old_inode = d_inode(old_dentry);
9343 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9344 bool log_pinned = false;
9346 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9349 /* we only allow rename subvolume link between subvolumes */
9350 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9353 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9354 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9357 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9358 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9362 /* check for collisions, even if the name isn't there */
9363 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9364 new_dentry->d_name.name,
9365 new_dentry->d_name.len);
9368 if (ret == -EEXIST) {
9370 * eexist without a new_inode */
9371 if (WARN_ON(!new_inode)) {
9375 /* maybe -EOVERFLOW */
9382 * we're using rename to replace one file with another. Start IO on it
9383 * now so we don't add too much work to the end of the transaction
9385 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9386 filemap_flush(old_inode->i_mapping);
9388 /* close the racy window with snapshot create/destroy ioctl */
9389 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9390 down_read(&fs_info->subvol_sem);
9392 * We want to reserve the absolute worst case amount of items. So if
9393 * both inodes are subvols and we need to unlink them then that would
9394 * require 4 item modifications, but if they are both normal inodes it
9395 * would require 5 item modifications, so we'll assume they are normal
9396 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9397 * should cover the worst case number of items we'll modify.
9398 * If our rename has the whiteout flag, we need more 5 units for the
9399 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9400 * when selinux is enabled).
9402 trans_num_items = 11;
9403 if (flags & RENAME_WHITEOUT)
9404 trans_num_items += 5;
9405 trans = btrfs_start_transaction(root, trans_num_items);
9406 if (IS_ERR(trans)) {
9407 ret = PTR_ERR(trans);
9412 btrfs_record_root_in_trans(trans, dest);
9414 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9418 BTRFS_I(old_inode)->dir_index = 0ULL;
9419 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9420 /* force full log commit if subvolume involved. */
9421 btrfs_set_log_full_commit(trans);
9423 btrfs_pin_log_trans(root);
9425 ret = btrfs_insert_inode_ref(trans, dest,
9426 new_dentry->d_name.name,
9427 new_dentry->d_name.len,
9429 btrfs_ino(BTRFS_I(new_dir)), index);
9434 inode_inc_iversion(old_dir);
9435 inode_inc_iversion(new_dir);
9436 inode_inc_iversion(old_inode);
9437 old_dir->i_ctime = old_dir->i_mtime =
9438 new_dir->i_ctime = new_dir->i_mtime =
9439 old_inode->i_ctime = current_time(old_dir);
9441 if (old_dentry->d_parent != new_dentry->d_parent)
9442 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9443 BTRFS_I(old_inode), 1);
9445 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9446 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9448 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9449 BTRFS_I(d_inode(old_dentry)),
9450 old_dentry->d_name.name,
9451 old_dentry->d_name.len);
9453 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9456 btrfs_abort_transaction(trans, ret);
9461 inode_inc_iversion(new_inode);
9462 new_inode->i_ctime = current_time(new_inode);
9463 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9464 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9465 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9466 BUG_ON(new_inode->i_nlink == 0);
9468 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9469 BTRFS_I(d_inode(new_dentry)),
9470 new_dentry->d_name.name,
9471 new_dentry->d_name.len);
9473 if (!ret && new_inode->i_nlink == 0)
9474 ret = btrfs_orphan_add(trans,
9475 BTRFS_I(d_inode(new_dentry)));
9477 btrfs_abort_transaction(trans, ret);
9482 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9483 new_dentry->d_name.name,
9484 new_dentry->d_name.len, 0, index);
9486 btrfs_abort_transaction(trans, ret);
9490 if (old_inode->i_nlink == 1)
9491 BTRFS_I(old_inode)->dir_index = index;
9494 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9495 new_dentry->d_parent);
9496 btrfs_end_log_trans(root);
9500 if (flags & RENAME_WHITEOUT) {
9501 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9505 btrfs_abort_transaction(trans, ret);
9511 * If we have pinned the log and an error happened, we unpin tasks
9512 * trying to sync the log and force them to fallback to a transaction
9513 * commit if the log currently contains any of the inodes involved in
9514 * this rename operation (to ensure we do not persist a log with an
9515 * inconsistent state for any of these inodes or leading to any
9516 * inconsistencies when replayed). If the transaction was aborted, the
9517 * abortion reason is propagated to userspace when attempting to commit
9518 * the transaction. If the log does not contain any of these inodes, we
9519 * allow the tasks to sync it.
9521 if (ret && log_pinned) {
9522 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9523 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9524 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9526 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9527 btrfs_set_log_full_commit(trans);
9529 btrfs_end_log_trans(root);
9532 ret2 = btrfs_end_transaction(trans);
9533 ret = ret ? ret : ret2;
9535 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9536 up_read(&fs_info->subvol_sem);
9541 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9542 struct dentry *old_dentry, struct inode *new_dir,
9543 struct dentry *new_dentry, unsigned int flags)
9545 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9548 if (flags & RENAME_EXCHANGE)
9549 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9552 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9555 struct btrfs_delalloc_work {
9556 struct inode *inode;
9557 struct completion completion;
9558 struct list_head list;
9559 struct btrfs_work work;
9562 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9564 struct btrfs_delalloc_work *delalloc_work;
9565 struct inode *inode;
9567 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9569 inode = delalloc_work->inode;
9570 filemap_flush(inode->i_mapping);
9571 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9572 &BTRFS_I(inode)->runtime_flags))
9573 filemap_flush(inode->i_mapping);
9576 complete(&delalloc_work->completion);
9579 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9581 struct btrfs_delalloc_work *work;
9583 work = kmalloc(sizeof(*work), GFP_NOFS);
9587 init_completion(&work->completion);
9588 INIT_LIST_HEAD(&work->list);
9589 work->inode = inode;
9590 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9596 * some fairly slow code that needs optimization. This walks the list
9597 * of all the inodes with pending delalloc and forces them to disk.
9599 static int start_delalloc_inodes(struct btrfs_root *root,
9600 struct writeback_control *wbc, bool snapshot,
9601 bool in_reclaim_context)
9603 struct btrfs_inode *binode;
9604 struct inode *inode;
9605 struct btrfs_delalloc_work *work, *next;
9606 struct list_head works;
9607 struct list_head splice;
9609 bool full_flush = wbc->nr_to_write == LONG_MAX;
9611 INIT_LIST_HEAD(&works);
9612 INIT_LIST_HEAD(&splice);
9614 mutex_lock(&root->delalloc_mutex);
9615 spin_lock(&root->delalloc_lock);
9616 list_splice_init(&root->delalloc_inodes, &splice);
9617 while (!list_empty(&splice)) {
9618 binode = list_entry(splice.next, struct btrfs_inode,
9621 list_move_tail(&binode->delalloc_inodes,
9622 &root->delalloc_inodes);
9624 if (in_reclaim_context &&
9625 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9628 inode = igrab(&binode->vfs_inode);
9630 cond_resched_lock(&root->delalloc_lock);
9633 spin_unlock(&root->delalloc_lock);
9636 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9637 &binode->runtime_flags);
9639 work = btrfs_alloc_delalloc_work(inode);
9645 list_add_tail(&work->list, &works);
9646 btrfs_queue_work(root->fs_info->flush_workers,
9649 ret = sync_inode(inode, wbc);
9651 test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9652 &BTRFS_I(inode)->runtime_flags))
9653 ret = sync_inode(inode, wbc);
9654 btrfs_add_delayed_iput(inode);
9655 if (ret || wbc->nr_to_write <= 0)
9659 spin_lock(&root->delalloc_lock);
9661 spin_unlock(&root->delalloc_lock);
9664 list_for_each_entry_safe(work, next, &works, list) {
9665 list_del_init(&work->list);
9666 wait_for_completion(&work->completion);
9670 if (!list_empty(&splice)) {
9671 spin_lock(&root->delalloc_lock);
9672 list_splice_tail(&splice, &root->delalloc_inodes);
9673 spin_unlock(&root->delalloc_lock);
9675 mutex_unlock(&root->delalloc_mutex);
9679 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9681 struct writeback_control wbc = {
9682 .nr_to_write = LONG_MAX,
9683 .sync_mode = WB_SYNC_NONE,
9685 .range_end = LLONG_MAX,
9687 struct btrfs_fs_info *fs_info = root->fs_info;
9689 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9692 return start_delalloc_inodes(root, &wbc, true, false);
9695 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9696 bool in_reclaim_context)
9698 struct writeback_control wbc = {
9700 .sync_mode = WB_SYNC_NONE,
9702 .range_end = LLONG_MAX,
9704 struct btrfs_root *root;
9705 struct list_head splice;
9708 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9711 INIT_LIST_HEAD(&splice);
9713 mutex_lock(&fs_info->delalloc_root_mutex);
9714 spin_lock(&fs_info->delalloc_root_lock);
9715 list_splice_init(&fs_info->delalloc_roots, &splice);
9716 while (!list_empty(&splice)) {
9718 * Reset nr_to_write here so we know that we're doing a full
9722 wbc.nr_to_write = LONG_MAX;
9724 root = list_first_entry(&splice, struct btrfs_root,
9726 root = btrfs_grab_root(root);
9728 list_move_tail(&root->delalloc_root,
9729 &fs_info->delalloc_roots);
9730 spin_unlock(&fs_info->delalloc_root_lock);
9732 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9733 btrfs_put_root(root);
9734 if (ret < 0 || wbc.nr_to_write <= 0)
9736 spin_lock(&fs_info->delalloc_root_lock);
9738 spin_unlock(&fs_info->delalloc_root_lock);
9742 if (!list_empty(&splice)) {
9743 spin_lock(&fs_info->delalloc_root_lock);
9744 list_splice_tail(&splice, &fs_info->delalloc_roots);
9745 spin_unlock(&fs_info->delalloc_root_lock);
9747 mutex_unlock(&fs_info->delalloc_root_mutex);
9751 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9752 struct dentry *dentry, const char *symname)
9754 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9755 struct btrfs_trans_handle *trans;
9756 struct btrfs_root *root = BTRFS_I(dir)->root;
9757 struct btrfs_path *path;
9758 struct btrfs_key key;
9759 struct inode *inode = NULL;
9766 struct btrfs_file_extent_item *ei;
9767 struct extent_buffer *leaf;
9769 name_len = strlen(symname);
9770 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9771 return -ENAMETOOLONG;
9774 * 2 items for inode item and ref
9775 * 2 items for dir items
9776 * 1 item for updating parent inode item
9777 * 1 item for the inline extent item
9778 * 1 item for xattr if selinux is on
9780 trans = btrfs_start_transaction(root, 7);
9782 return PTR_ERR(trans);
9784 err = btrfs_get_free_objectid(root, &objectid);
9788 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9789 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9790 objectid, S_IFLNK|S_IRWXUGO, &index);
9791 if (IS_ERR(inode)) {
9792 err = PTR_ERR(inode);
9798 * If the active LSM wants to access the inode during
9799 * d_instantiate it needs these. Smack checks to see
9800 * if the filesystem supports xattrs by looking at the
9803 inode->i_fop = &btrfs_file_operations;
9804 inode->i_op = &btrfs_file_inode_operations;
9805 inode->i_mapping->a_ops = &btrfs_aops;
9807 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9811 path = btrfs_alloc_path();
9816 key.objectid = btrfs_ino(BTRFS_I(inode));
9818 key.type = BTRFS_EXTENT_DATA_KEY;
9819 datasize = btrfs_file_extent_calc_inline_size(name_len);
9820 err = btrfs_insert_empty_item(trans, root, path, &key,
9823 btrfs_free_path(path);
9826 leaf = path->nodes[0];
9827 ei = btrfs_item_ptr(leaf, path->slots[0],
9828 struct btrfs_file_extent_item);
9829 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9830 btrfs_set_file_extent_type(leaf, ei,
9831 BTRFS_FILE_EXTENT_INLINE);
9832 btrfs_set_file_extent_encryption(leaf, ei, 0);
9833 btrfs_set_file_extent_compression(leaf, ei, 0);
9834 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9835 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9837 ptr = btrfs_file_extent_inline_start(ei);
9838 write_extent_buffer(leaf, symname, ptr, name_len);
9839 btrfs_mark_buffer_dirty(leaf);
9840 btrfs_free_path(path);
9842 inode->i_op = &btrfs_symlink_inode_operations;
9843 inode_nohighmem(inode);
9844 inode_set_bytes(inode, name_len);
9845 btrfs_i_size_write(BTRFS_I(inode), name_len);
9846 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
9848 * Last step, add directory indexes for our symlink inode. This is the
9849 * last step to avoid extra cleanup of these indexes if an error happens
9853 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9854 BTRFS_I(inode), 0, index);
9858 d_instantiate_new(dentry, inode);
9861 btrfs_end_transaction(trans);
9863 inode_dec_link_count(inode);
9864 discard_new_inode(inode);
9866 btrfs_btree_balance_dirty(fs_info);
9870 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9871 struct btrfs_trans_handle *trans_in,
9872 struct btrfs_inode *inode,
9873 struct btrfs_key *ins,
9876 struct btrfs_file_extent_item stack_fi;
9877 struct btrfs_replace_extent_info extent_info;
9878 struct btrfs_trans_handle *trans = trans_in;
9879 struct btrfs_path *path;
9880 u64 start = ins->objectid;
9881 u64 len = ins->offset;
9882 int qgroup_released;
9885 memset(&stack_fi, 0, sizeof(stack_fi));
9887 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9888 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9889 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9890 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9891 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9892 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9893 /* Encryption and other encoding is reserved and all 0 */
9895 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9896 if (qgroup_released < 0)
9897 return ERR_PTR(qgroup_released);
9900 ret = insert_reserved_file_extent(trans, inode,
9901 file_offset, &stack_fi,
9902 true, qgroup_released);
9908 extent_info.disk_offset = start;
9909 extent_info.disk_len = len;
9910 extent_info.data_offset = 0;
9911 extent_info.data_len = len;
9912 extent_info.file_offset = file_offset;
9913 extent_info.extent_buf = (char *)&stack_fi;
9914 extent_info.is_new_extent = true;
9915 extent_info.qgroup_reserved = qgroup_released;
9916 extent_info.insertions = 0;
9918 path = btrfs_alloc_path();
9924 ret = btrfs_replace_file_extents(inode, path, file_offset,
9925 file_offset + len - 1, &extent_info,
9927 btrfs_free_path(path);
9934 * We have released qgroup data range at the beginning of the function,
9935 * and normally qgroup_released bytes will be freed when committing
9937 * But if we error out early, we have to free what we have released
9938 * or we leak qgroup data reservation.
9940 btrfs_qgroup_free_refroot(inode->root->fs_info,
9941 inode->root->root_key.objectid, qgroup_released,
9942 BTRFS_QGROUP_RSV_DATA);
9943 return ERR_PTR(ret);
9946 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9947 u64 start, u64 num_bytes, u64 min_size,
9948 loff_t actual_len, u64 *alloc_hint,
9949 struct btrfs_trans_handle *trans)
9951 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9952 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9953 struct extent_map *em;
9954 struct btrfs_root *root = BTRFS_I(inode)->root;
9955 struct btrfs_key ins;
9956 u64 cur_offset = start;
9957 u64 clear_offset = start;
9960 u64 last_alloc = (u64)-1;
9962 bool own_trans = true;
9963 u64 end = start + num_bytes - 1;
9967 while (num_bytes > 0) {
9968 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9969 cur_bytes = max(cur_bytes, min_size);
9971 * If we are severely fragmented we could end up with really
9972 * small allocations, so if the allocator is returning small
9973 * chunks lets make its job easier by only searching for those
9976 cur_bytes = min(cur_bytes, last_alloc);
9977 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9978 min_size, 0, *alloc_hint, &ins, 1, 0);
9983 * We've reserved this space, and thus converted it from
9984 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9985 * from here on out we will only need to clear our reservation
9986 * for the remaining unreserved area, so advance our
9987 * clear_offset by our extent size.
9989 clear_offset += ins.offset;
9991 last_alloc = ins.offset;
9992 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9995 * Now that we inserted the prealloc extent we can finally
9996 * decrement the number of reservations in the block group.
9997 * If we did it before, we could race with relocation and have
9998 * relocation miss the reserved extent, making it fail later.
10000 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10001 if (IS_ERR(trans)) {
10002 ret = PTR_ERR(trans);
10003 btrfs_free_reserved_extent(fs_info, ins.objectid,
10008 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10009 cur_offset + ins.offset -1, 0);
10011 em = alloc_extent_map();
10013 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10014 &BTRFS_I(inode)->runtime_flags);
10018 em->start = cur_offset;
10019 em->orig_start = cur_offset;
10020 em->len = ins.offset;
10021 em->block_start = ins.objectid;
10022 em->block_len = ins.offset;
10023 em->orig_block_len = ins.offset;
10024 em->ram_bytes = ins.offset;
10025 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10026 em->generation = trans->transid;
10029 write_lock(&em_tree->lock);
10030 ret = add_extent_mapping(em_tree, em, 1);
10031 write_unlock(&em_tree->lock);
10032 if (ret != -EEXIST)
10034 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10035 cur_offset + ins.offset - 1,
10038 free_extent_map(em);
10040 num_bytes -= ins.offset;
10041 cur_offset += ins.offset;
10042 *alloc_hint = ins.objectid + ins.offset;
10044 inode_inc_iversion(inode);
10045 inode->i_ctime = current_time(inode);
10046 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10047 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10048 (actual_len > inode->i_size) &&
10049 (cur_offset > inode->i_size)) {
10050 if (cur_offset > actual_len)
10051 i_size = actual_len;
10053 i_size = cur_offset;
10054 i_size_write(inode, i_size);
10055 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10058 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10061 btrfs_abort_transaction(trans, ret);
10063 btrfs_end_transaction(trans);
10068 btrfs_end_transaction(trans);
10072 if (clear_offset < end)
10073 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10074 end - clear_offset + 1);
10078 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10079 u64 start, u64 num_bytes, u64 min_size,
10080 loff_t actual_len, u64 *alloc_hint)
10082 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10083 min_size, actual_len, alloc_hint,
10087 int btrfs_prealloc_file_range_trans(struct inode *inode,
10088 struct btrfs_trans_handle *trans, int mode,
10089 u64 start, u64 num_bytes, u64 min_size,
10090 loff_t actual_len, u64 *alloc_hint)
10092 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10093 min_size, actual_len, alloc_hint, trans);
10096 static int btrfs_set_page_dirty(struct page *page)
10098 return __set_page_dirty_nobuffers(page);
10101 static int btrfs_permission(struct user_namespace *mnt_userns,
10102 struct inode *inode, int mask)
10104 struct btrfs_root *root = BTRFS_I(inode)->root;
10105 umode_t mode = inode->i_mode;
10107 if (mask & MAY_WRITE &&
10108 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10109 if (btrfs_root_readonly(root))
10111 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10114 return generic_permission(&init_user_ns, inode, mask);
10117 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10118 struct dentry *dentry, umode_t mode)
10120 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10121 struct btrfs_trans_handle *trans;
10122 struct btrfs_root *root = BTRFS_I(dir)->root;
10123 struct inode *inode = NULL;
10129 * 5 units required for adding orphan entry
10131 trans = btrfs_start_transaction(root, 5);
10133 return PTR_ERR(trans);
10135 ret = btrfs_get_free_objectid(root, &objectid);
10139 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10140 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10141 if (IS_ERR(inode)) {
10142 ret = PTR_ERR(inode);
10147 inode->i_fop = &btrfs_file_operations;
10148 inode->i_op = &btrfs_file_inode_operations;
10150 inode->i_mapping->a_ops = &btrfs_aops;
10152 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10156 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10159 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10164 * We set number of links to 0 in btrfs_new_inode(), and here we set
10165 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10168 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10170 set_nlink(inode, 1);
10171 d_tmpfile(dentry, inode);
10172 unlock_new_inode(inode);
10173 mark_inode_dirty(inode);
10175 btrfs_end_transaction(trans);
10177 discard_new_inode(inode);
10178 btrfs_btree_balance_dirty(fs_info);
10182 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10184 struct inode *inode = tree->private_data;
10185 unsigned long index = start >> PAGE_SHIFT;
10186 unsigned long end_index = end >> PAGE_SHIFT;
10189 while (index <= end_index) {
10190 page = find_get_page(inode->i_mapping, index);
10191 ASSERT(page); /* Pages should be in the extent_io_tree */
10192 set_page_writeback(page);
10200 * Add an entry indicating a block group or device which is pinned by a
10201 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10202 * negative errno on failure.
10204 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10205 bool is_block_group)
10207 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10208 struct btrfs_swapfile_pin *sp, *entry;
10209 struct rb_node **p;
10210 struct rb_node *parent = NULL;
10212 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10217 sp->is_block_group = is_block_group;
10218 sp->bg_extent_count = 1;
10220 spin_lock(&fs_info->swapfile_pins_lock);
10221 p = &fs_info->swapfile_pins.rb_node;
10224 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10225 if (sp->ptr < entry->ptr ||
10226 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10227 p = &(*p)->rb_left;
10228 } else if (sp->ptr > entry->ptr ||
10229 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10230 p = &(*p)->rb_right;
10232 if (is_block_group)
10233 entry->bg_extent_count++;
10234 spin_unlock(&fs_info->swapfile_pins_lock);
10239 rb_link_node(&sp->node, parent, p);
10240 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10241 spin_unlock(&fs_info->swapfile_pins_lock);
10245 /* Free all of the entries pinned by this swapfile. */
10246 static void btrfs_free_swapfile_pins(struct inode *inode)
10248 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10249 struct btrfs_swapfile_pin *sp;
10250 struct rb_node *node, *next;
10252 spin_lock(&fs_info->swapfile_pins_lock);
10253 node = rb_first(&fs_info->swapfile_pins);
10255 next = rb_next(node);
10256 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10257 if (sp->inode == inode) {
10258 rb_erase(&sp->node, &fs_info->swapfile_pins);
10259 if (sp->is_block_group) {
10260 btrfs_dec_block_group_swap_extents(sp->ptr,
10261 sp->bg_extent_count);
10262 btrfs_put_block_group(sp->ptr);
10268 spin_unlock(&fs_info->swapfile_pins_lock);
10271 struct btrfs_swap_info {
10277 unsigned long nr_pages;
10281 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10282 struct btrfs_swap_info *bsi)
10284 unsigned long nr_pages;
10285 u64 first_ppage, first_ppage_reported, next_ppage;
10288 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10289 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10290 PAGE_SIZE) >> PAGE_SHIFT;
10292 if (first_ppage >= next_ppage)
10294 nr_pages = next_ppage - first_ppage;
10296 first_ppage_reported = first_ppage;
10297 if (bsi->start == 0)
10298 first_ppage_reported++;
10299 if (bsi->lowest_ppage > first_ppage_reported)
10300 bsi->lowest_ppage = first_ppage_reported;
10301 if (bsi->highest_ppage < (next_ppage - 1))
10302 bsi->highest_ppage = next_ppage - 1;
10304 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10307 bsi->nr_extents += ret;
10308 bsi->nr_pages += nr_pages;
10312 static void btrfs_swap_deactivate(struct file *file)
10314 struct inode *inode = file_inode(file);
10316 btrfs_free_swapfile_pins(inode);
10317 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10320 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10323 struct inode *inode = file_inode(file);
10324 struct btrfs_root *root = BTRFS_I(inode)->root;
10325 struct btrfs_fs_info *fs_info = root->fs_info;
10326 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10327 struct extent_state *cached_state = NULL;
10328 struct extent_map *em = NULL;
10329 struct btrfs_device *device = NULL;
10330 struct btrfs_swap_info bsi = {
10331 .lowest_ppage = (sector_t)-1ULL,
10338 * If the swap file was just created, make sure delalloc is done. If the
10339 * file changes again after this, the user is doing something stupid and
10340 * we don't really care.
10342 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10347 * The inode is locked, so these flags won't change after we check them.
10349 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10350 btrfs_warn(fs_info, "swapfile must not be compressed");
10353 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10354 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10357 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10358 btrfs_warn(fs_info, "swapfile must not be checksummed");
10363 * Balance or device remove/replace/resize can move stuff around from
10364 * under us. The exclop protection makes sure they aren't running/won't
10365 * run concurrently while we are mapping the swap extents, and
10366 * fs_info->swapfile_pins prevents them from running while the swap
10367 * file is active and moving the extents. Note that this also prevents
10368 * a concurrent device add which isn't actually necessary, but it's not
10369 * really worth the trouble to allow it.
10371 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10372 btrfs_warn(fs_info,
10373 "cannot activate swapfile while exclusive operation is running");
10378 * Prevent snapshot creation while we are activating the swap file.
10379 * We do not want to race with snapshot creation. If snapshot creation
10380 * already started before we bumped nr_swapfiles from 0 to 1 and
10381 * completes before the first write into the swap file after it is
10382 * activated, than that write would fallback to COW.
10384 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10385 btrfs_exclop_finish(fs_info);
10386 btrfs_warn(fs_info,
10387 "cannot activate swapfile because snapshot creation is in progress");
10391 * Snapshots can create extents which require COW even if NODATACOW is
10392 * set. We use this counter to prevent snapshots. We must increment it
10393 * before walking the extents because we don't want a concurrent
10394 * snapshot to run after we've already checked the extents.
10396 atomic_inc(&root->nr_swapfiles);
10398 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10400 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10402 while (start < isize) {
10403 u64 logical_block_start, physical_block_start;
10404 struct btrfs_block_group *bg;
10405 u64 len = isize - start;
10407 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10413 if (em->block_start == EXTENT_MAP_HOLE) {
10414 btrfs_warn(fs_info, "swapfile must not have holes");
10418 if (em->block_start == EXTENT_MAP_INLINE) {
10420 * It's unlikely we'll ever actually find ourselves
10421 * here, as a file small enough to fit inline won't be
10422 * big enough to store more than the swap header, but in
10423 * case something changes in the future, let's catch it
10424 * here rather than later.
10426 btrfs_warn(fs_info, "swapfile must not be inline");
10430 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10431 btrfs_warn(fs_info, "swapfile must not be compressed");
10436 logical_block_start = em->block_start + (start - em->start);
10437 len = min(len, em->len - (start - em->start));
10438 free_extent_map(em);
10441 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10447 btrfs_warn(fs_info,
10448 "swapfile must not be copy-on-write");
10453 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10459 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10460 btrfs_warn(fs_info,
10461 "swapfile must have single data profile");
10466 if (device == NULL) {
10467 device = em->map_lookup->stripes[0].dev;
10468 ret = btrfs_add_swapfile_pin(inode, device, false);
10473 } else if (device != em->map_lookup->stripes[0].dev) {
10474 btrfs_warn(fs_info, "swapfile must be on one device");
10479 physical_block_start = (em->map_lookup->stripes[0].physical +
10480 (logical_block_start - em->start));
10481 len = min(len, em->len - (logical_block_start - em->start));
10482 free_extent_map(em);
10485 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10487 btrfs_warn(fs_info,
10488 "could not find block group containing swapfile");
10493 if (!btrfs_inc_block_group_swap_extents(bg)) {
10494 btrfs_warn(fs_info,
10495 "block group for swapfile at %llu is read-only%s",
10497 atomic_read(&fs_info->scrubs_running) ?
10498 " (scrub running)" : "");
10499 btrfs_put_block_group(bg);
10504 ret = btrfs_add_swapfile_pin(inode, bg, true);
10506 btrfs_put_block_group(bg);
10513 if (bsi.block_len &&
10514 bsi.block_start + bsi.block_len == physical_block_start) {
10515 bsi.block_len += len;
10517 if (bsi.block_len) {
10518 ret = btrfs_add_swap_extent(sis, &bsi);
10523 bsi.block_start = physical_block_start;
10524 bsi.block_len = len;
10531 ret = btrfs_add_swap_extent(sis, &bsi);
10534 if (!IS_ERR_OR_NULL(em))
10535 free_extent_map(em);
10537 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10540 btrfs_swap_deactivate(file);
10542 btrfs_drew_write_unlock(&root->snapshot_lock);
10544 btrfs_exclop_finish(fs_info);
10550 sis->bdev = device->bdev;
10551 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10552 sis->max = bsi.nr_pages;
10553 sis->pages = bsi.nr_pages - 1;
10554 sis->highest_bit = bsi.nr_pages - 1;
10555 return bsi.nr_extents;
10558 static void btrfs_swap_deactivate(struct file *file)
10562 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10565 return -EOPNOTSUPP;
10570 * Update the number of bytes used in the VFS' inode. When we replace extents in
10571 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10572 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10573 * always get a correct value.
10575 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10576 const u64 add_bytes,
10577 const u64 del_bytes)
10579 if (add_bytes == del_bytes)
10582 spin_lock(&inode->lock);
10584 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10586 inode_add_bytes(&inode->vfs_inode, add_bytes);
10587 spin_unlock(&inode->lock);
10590 static const struct inode_operations btrfs_dir_inode_operations = {
10591 .getattr = btrfs_getattr,
10592 .lookup = btrfs_lookup,
10593 .create = btrfs_create,
10594 .unlink = btrfs_unlink,
10595 .link = btrfs_link,
10596 .mkdir = btrfs_mkdir,
10597 .rmdir = btrfs_rmdir,
10598 .rename = btrfs_rename2,
10599 .symlink = btrfs_symlink,
10600 .setattr = btrfs_setattr,
10601 .mknod = btrfs_mknod,
10602 .listxattr = btrfs_listxattr,
10603 .permission = btrfs_permission,
10604 .get_acl = btrfs_get_acl,
10605 .set_acl = btrfs_set_acl,
10606 .update_time = btrfs_update_time,
10607 .tmpfile = btrfs_tmpfile,
10610 static const struct file_operations btrfs_dir_file_operations = {
10611 .llseek = generic_file_llseek,
10612 .read = generic_read_dir,
10613 .iterate_shared = btrfs_real_readdir,
10614 .open = btrfs_opendir,
10615 .unlocked_ioctl = btrfs_ioctl,
10616 #ifdef CONFIG_COMPAT
10617 .compat_ioctl = btrfs_compat_ioctl,
10619 .release = btrfs_release_file,
10620 .fsync = btrfs_sync_file,
10624 * btrfs doesn't support the bmap operation because swapfiles
10625 * use bmap to make a mapping of extents in the file. They assume
10626 * these extents won't change over the life of the file and they
10627 * use the bmap result to do IO directly to the drive.
10629 * the btrfs bmap call would return logical addresses that aren't
10630 * suitable for IO and they also will change frequently as COW
10631 * operations happen. So, swapfile + btrfs == corruption.
10633 * For now we're avoiding this by dropping bmap.
10635 static const struct address_space_operations btrfs_aops = {
10636 .readpage = btrfs_readpage,
10637 .writepage = btrfs_writepage,
10638 .writepages = btrfs_writepages,
10639 .readahead = btrfs_readahead,
10640 .direct_IO = noop_direct_IO,
10641 .invalidatepage = btrfs_invalidatepage,
10642 .releasepage = btrfs_releasepage,
10643 #ifdef CONFIG_MIGRATION
10644 .migratepage = btrfs_migratepage,
10646 .set_page_dirty = btrfs_set_page_dirty,
10647 .error_remove_page = generic_error_remove_page,
10648 .swap_activate = btrfs_swap_activate,
10649 .swap_deactivate = btrfs_swap_deactivate,
10652 static const struct inode_operations btrfs_file_inode_operations = {
10653 .getattr = btrfs_getattr,
10654 .setattr = btrfs_setattr,
10655 .listxattr = btrfs_listxattr,
10656 .permission = btrfs_permission,
10657 .fiemap = btrfs_fiemap,
10658 .get_acl = btrfs_get_acl,
10659 .set_acl = btrfs_set_acl,
10660 .update_time = btrfs_update_time,
10662 static const struct inode_operations btrfs_special_inode_operations = {
10663 .getattr = btrfs_getattr,
10664 .setattr = btrfs_setattr,
10665 .permission = btrfs_permission,
10666 .listxattr = btrfs_listxattr,
10667 .get_acl = btrfs_get_acl,
10668 .set_acl = btrfs_set_acl,
10669 .update_time = btrfs_update_time,
10671 static const struct inode_operations btrfs_symlink_inode_operations = {
10672 .get_link = page_get_link,
10673 .getattr = btrfs_getattr,
10674 .setattr = btrfs_setattr,
10675 .permission = btrfs_permission,
10676 .listxattr = btrfs_listxattr,
10677 .update_time = btrfs_update_time,
10680 const struct dentry_operations btrfs_dentry_operations = {
10681 .d_delete = btrfs_dentry_delete,