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>
35 #include <linux/fsverity.h>
39 #include "transaction.h"
40 #include "btrfs_inode.h"
41 #include "print-tree.h"
42 #include "ordered-data.h"
46 #include "compression.h"
48 #include "free-space-cache.h"
51 #include "delalloc-space.h"
52 #include "block-group.h"
53 #include "space-info.h"
57 struct btrfs_iget_args {
59 struct btrfs_root *root;
62 struct btrfs_dio_data {
64 struct extent_changeset *data_reserved;
67 static const struct inode_operations btrfs_dir_inode_operations;
68 static const struct inode_operations btrfs_symlink_inode_operations;
69 static const struct inode_operations btrfs_special_inode_operations;
70 static const struct inode_operations btrfs_file_inode_operations;
71 static const struct address_space_operations btrfs_aops;
72 static const struct file_operations btrfs_dir_file_operations;
74 static struct kmem_cache *btrfs_inode_cachep;
75 struct kmem_cache *btrfs_trans_handle_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
78 struct kmem_cache *btrfs_free_space_bitmap_cachep;
80 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
81 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
82 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
83 static noinline int cow_file_range(struct btrfs_inode *inode,
84 struct page *locked_page,
85 u64 start, u64 end, int *page_started,
86 unsigned long *nr_written, int unlock);
87 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
88 u64 len, u64 orig_start, u64 block_start,
89 u64 block_len, u64 orig_block_len,
90 u64 ram_bytes, int compress_type,
93 static void __endio_write_update_ordered(struct btrfs_inode *inode,
94 const u64 offset, const u64 bytes,
98 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
100 * ilock_flags can have the following bit set:
102 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
103 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
105 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
107 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
109 if (ilock_flags & BTRFS_ILOCK_SHARED) {
110 if (ilock_flags & BTRFS_ILOCK_TRY) {
111 if (!inode_trylock_shared(inode))
116 inode_lock_shared(inode);
118 if (ilock_flags & BTRFS_ILOCK_TRY) {
119 if (!inode_trylock(inode))
126 if (ilock_flags & BTRFS_ILOCK_MMAP)
127 down_write(&BTRFS_I(inode)->i_mmap_lock);
132 * btrfs_inode_unlock - unock inode i_rwsem
134 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
135 * to decide whether the lock acquired is shared or exclusive.
137 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
139 if (ilock_flags & BTRFS_ILOCK_MMAP)
140 up_write(&BTRFS_I(inode)->i_mmap_lock);
141 if (ilock_flags & BTRFS_ILOCK_SHARED)
142 inode_unlock_shared(inode);
148 * Cleanup all submitted ordered extents in specified range to handle errors
149 * from the btrfs_run_delalloc_range() callback.
151 * NOTE: caller must ensure that when an error happens, it can not call
152 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
153 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
154 * to be released, which we want to happen only when finishing the ordered
155 * extent (btrfs_finish_ordered_io()).
157 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
158 struct page *locked_page,
159 u64 offset, u64 bytes)
161 unsigned long index = offset >> PAGE_SHIFT;
162 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
163 u64 page_start = page_offset(locked_page);
164 u64 page_end = page_start + PAGE_SIZE - 1;
168 while (index <= end_index) {
170 * For locked page, we will call end_extent_writepage() on it
171 * in run_delalloc_range() for the error handling. That
172 * end_extent_writepage() function will call
173 * btrfs_mark_ordered_io_finished() to clear page Ordered and
174 * run the ordered extent accounting.
176 * Here we can't just clear the Ordered bit, or
177 * btrfs_mark_ordered_io_finished() would skip the accounting
178 * for the page range, and the ordered extent will never finish.
180 if (index == (page_offset(locked_page) >> PAGE_SHIFT)) {
184 page = find_get_page(inode->vfs_inode.i_mapping, index);
190 * Here we just clear all Ordered bits for every page in the
191 * range, then __endio_write_update_ordered() will handle
192 * the ordered extent accounting for the range.
194 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
199 /* The locked page covers the full range, nothing needs to be done */
200 if (bytes + offset <= page_offset(locked_page) + PAGE_SIZE)
203 * In case this page belongs to the delalloc range being instantiated
204 * then skip it, since the first page of a range is going to be
205 * properly cleaned up by the caller of run_delalloc_range
207 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
208 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
209 offset = page_offset(locked_page) + PAGE_SIZE;
212 return __endio_write_update_ordered(inode, offset, bytes, false);
215 static int btrfs_dirty_inode(struct inode *inode);
217 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
218 struct inode *inode, struct inode *dir,
219 const struct qstr *qstr)
223 err = btrfs_init_acl(trans, inode, dir);
225 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
230 * this does all the hard work for inserting an inline extent into
231 * the btree. The caller should have done a btrfs_drop_extents so that
232 * no overlapping inline items exist in the btree
234 static int insert_inline_extent(struct btrfs_trans_handle *trans,
235 struct btrfs_path *path, bool extent_inserted,
236 struct btrfs_root *root, struct inode *inode,
237 u64 start, size_t size, size_t compressed_size,
239 struct page **compressed_pages)
241 struct extent_buffer *leaf;
242 struct page *page = NULL;
245 struct btrfs_file_extent_item *ei;
247 size_t cur_size = size;
248 unsigned long offset;
250 ASSERT((compressed_size > 0 && compressed_pages) ||
251 (compressed_size == 0 && !compressed_pages));
253 if (compressed_size && compressed_pages)
254 cur_size = compressed_size;
256 if (!extent_inserted) {
257 struct btrfs_key key;
260 key.objectid = btrfs_ino(BTRFS_I(inode));
262 key.type = BTRFS_EXTENT_DATA_KEY;
264 datasize = btrfs_file_extent_calc_inline_size(cur_size);
265 ret = btrfs_insert_empty_item(trans, root, path, &key,
270 leaf = path->nodes[0];
271 ei = btrfs_item_ptr(leaf, path->slots[0],
272 struct btrfs_file_extent_item);
273 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
274 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
275 btrfs_set_file_extent_encryption(leaf, ei, 0);
276 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
277 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
278 ptr = btrfs_file_extent_inline_start(ei);
280 if (compress_type != BTRFS_COMPRESS_NONE) {
283 while (compressed_size > 0) {
284 cpage = compressed_pages[i];
285 cur_size = min_t(unsigned long, compressed_size,
288 kaddr = kmap_atomic(cpage);
289 write_extent_buffer(leaf, kaddr, ptr, cur_size);
290 kunmap_atomic(kaddr);
294 compressed_size -= cur_size;
296 btrfs_set_file_extent_compression(leaf, ei,
299 page = find_get_page(inode->i_mapping,
300 start >> PAGE_SHIFT);
301 btrfs_set_file_extent_compression(leaf, ei, 0);
302 kaddr = kmap_atomic(page);
303 offset = offset_in_page(start);
304 write_extent_buffer(leaf, kaddr + offset, ptr, size);
305 kunmap_atomic(kaddr);
308 btrfs_mark_buffer_dirty(leaf);
309 btrfs_release_path(path);
312 * We align size to sectorsize for inline extents just for simplicity
315 size = ALIGN(size, root->fs_info->sectorsize);
316 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
321 * we're an inline extent, so nobody can
322 * extend the file past i_size without locking
323 * a page we already have locked.
325 * We must do any isize and inode updates
326 * before we unlock the pages. Otherwise we
327 * could end up racing with unlink.
329 BTRFS_I(inode)->disk_i_size = inode->i_size;
336 * conditionally insert an inline extent into the file. This
337 * does the checks required to make sure the data is small enough
338 * to fit as an inline extent.
340 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
341 u64 end, size_t compressed_size,
343 struct page **compressed_pages)
345 struct btrfs_drop_extents_args drop_args = { 0 };
346 struct btrfs_root *root = inode->root;
347 struct btrfs_fs_info *fs_info = root->fs_info;
348 struct btrfs_trans_handle *trans;
349 u64 isize = i_size_read(&inode->vfs_inode);
350 u64 actual_end = min(end + 1, isize);
351 u64 inline_len = actual_end - start;
352 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
353 u64 data_len = inline_len;
355 struct btrfs_path *path;
358 data_len = compressed_size;
361 actual_end > fs_info->sectorsize ||
362 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
364 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
366 data_len > fs_info->max_inline) {
370 path = btrfs_alloc_path();
374 trans = btrfs_join_transaction(root);
376 btrfs_free_path(path);
377 return PTR_ERR(trans);
379 trans->block_rsv = &inode->block_rsv;
381 drop_args.path = path;
382 drop_args.start = start;
383 drop_args.end = aligned_end;
384 drop_args.drop_cache = true;
385 drop_args.replace_extent = true;
387 if (compressed_size && compressed_pages)
388 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
391 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
394 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
396 btrfs_abort_transaction(trans, ret);
400 if (isize > actual_end)
401 inline_len = min_t(u64, isize, actual_end);
402 ret = insert_inline_extent(trans, path, drop_args.extent_inserted,
403 root, &inode->vfs_inode, start,
404 inline_len, compressed_size,
405 compress_type, compressed_pages);
406 if (ret && ret != -ENOSPC) {
407 btrfs_abort_transaction(trans, ret);
409 } else if (ret == -ENOSPC) {
414 btrfs_update_inode_bytes(inode, inline_len, drop_args.bytes_found);
415 ret = btrfs_update_inode(trans, root, inode);
416 if (ret && ret != -ENOSPC) {
417 btrfs_abort_transaction(trans, ret);
419 } else if (ret == -ENOSPC) {
424 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
427 * Don't forget to free the reserved space, as for inlined extent
428 * it won't count as data extent, free them directly here.
429 * And at reserve time, it's always aligned to page size, so
430 * just free one page here.
432 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
433 btrfs_free_path(path);
434 btrfs_end_transaction(trans);
438 struct async_extent {
443 unsigned long nr_pages;
445 struct list_head list;
450 struct page *locked_page;
453 unsigned int write_flags;
454 struct list_head extents;
455 struct cgroup_subsys_state *blkcg_css;
456 struct btrfs_work work;
461 /* Number of chunks in flight; must be first in the structure */
463 struct async_chunk chunks[];
466 static noinline int add_async_extent(struct async_chunk *cow,
467 u64 start, u64 ram_size,
470 unsigned long nr_pages,
473 struct async_extent *async_extent;
475 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
476 BUG_ON(!async_extent); /* -ENOMEM */
477 async_extent->start = start;
478 async_extent->ram_size = ram_size;
479 async_extent->compressed_size = compressed_size;
480 async_extent->pages = pages;
481 async_extent->nr_pages = nr_pages;
482 async_extent->compress_type = compress_type;
483 list_add_tail(&async_extent->list, &cow->extents);
488 * Check if the inode has flags compatible with compression
490 static inline bool inode_can_compress(struct btrfs_inode *inode)
492 /* Subpage doesn't support compression yet */
493 if (inode->root->fs_info->sectorsize < PAGE_SIZE)
495 if (inode->flags & BTRFS_INODE_NODATACOW ||
496 inode->flags & BTRFS_INODE_NODATASUM)
502 * Check if the inode needs to be submitted to compression, based on mount
503 * options, defragmentation, properties or heuristics.
505 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
508 struct btrfs_fs_info *fs_info = inode->root->fs_info;
510 if (!inode_can_compress(inode)) {
511 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
512 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
517 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
520 if (inode->defrag_compress)
522 /* bad compression ratios */
523 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
525 if (btrfs_test_opt(fs_info, COMPRESS) ||
526 inode->flags & BTRFS_INODE_COMPRESS ||
527 inode->prop_compress)
528 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
532 static inline void inode_should_defrag(struct btrfs_inode *inode,
533 u64 start, u64 end, u64 num_bytes, u64 small_write)
535 /* If this is a small write inside eof, kick off a defrag */
536 if (num_bytes < small_write &&
537 (start > 0 || end + 1 < inode->disk_i_size))
538 btrfs_add_inode_defrag(NULL, inode);
542 * we create compressed extents in two phases. The first
543 * phase compresses a range of pages that have already been
544 * locked (both pages and state bits are locked).
546 * This is done inside an ordered work queue, and the compression
547 * is spread across many cpus. The actual IO submission is step
548 * two, and the ordered work queue takes care of making sure that
549 * happens in the same order things were put onto the queue by
550 * writepages and friends.
552 * If this code finds it can't get good compression, it puts an
553 * entry onto the work queue to write the uncompressed bytes. This
554 * makes sure that both compressed inodes and uncompressed inodes
555 * are written in the same order that the flusher thread sent them
558 static noinline int compress_file_range(struct async_chunk *async_chunk)
560 struct inode *inode = async_chunk->inode;
561 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
562 u64 blocksize = fs_info->sectorsize;
563 u64 start = async_chunk->start;
564 u64 end = async_chunk->end;
568 struct page **pages = NULL;
569 unsigned long nr_pages;
570 unsigned long total_compressed = 0;
571 unsigned long total_in = 0;
574 int compress_type = fs_info->compress_type;
575 int compressed_extents = 0;
578 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
582 * We need to save i_size before now because it could change in between
583 * us evaluating the size and assigning it. This is because we lock and
584 * unlock the page in truncate and fallocate, and then modify the i_size
587 * The barriers are to emulate READ_ONCE, remove that once i_size_read
591 i_size = i_size_read(inode);
593 actual_end = min_t(u64, i_size, end + 1);
596 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
597 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
598 nr_pages = min_t(unsigned long, nr_pages,
599 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
602 * we don't want to send crud past the end of i_size through
603 * compression, that's just a waste of CPU time. So, if the
604 * end of the file is before the start of our current
605 * requested range of bytes, we bail out to the uncompressed
606 * cleanup code that can deal with all of this.
608 * It isn't really the fastest way to fix things, but this is a
609 * very uncommon corner.
611 if (actual_end <= start)
612 goto cleanup_and_bail_uncompressed;
614 total_compressed = actual_end - start;
617 * skip compression for a small file range(<=blocksize) that
618 * isn't an inline extent, since it doesn't save disk space at all.
620 if (total_compressed <= blocksize &&
621 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
622 goto cleanup_and_bail_uncompressed;
624 total_compressed = min_t(unsigned long, total_compressed,
625 BTRFS_MAX_UNCOMPRESSED);
630 * we do compression for mount -o compress and when the
631 * inode has not been flagged as nocompress. This flag can
632 * change at any time if we discover bad compression ratios.
634 if (inode_need_compress(BTRFS_I(inode), start, end)) {
636 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
638 /* just bail out to the uncompressed code */
643 if (BTRFS_I(inode)->defrag_compress)
644 compress_type = BTRFS_I(inode)->defrag_compress;
645 else if (BTRFS_I(inode)->prop_compress)
646 compress_type = BTRFS_I(inode)->prop_compress;
649 * we need to call clear_page_dirty_for_io on each
650 * page in the range. Otherwise applications with the file
651 * mmap'd can wander in and change the page contents while
652 * we are compressing them.
654 * If the compression fails for any reason, we set the pages
655 * dirty again later on.
657 * Note that the remaining part is redirtied, the start pointer
658 * has moved, the end is the original one.
661 extent_range_clear_dirty_for_io(inode, start, end);
665 /* Compression level is applied here and only here */
666 ret = btrfs_compress_pages(
667 compress_type | (fs_info->compress_level << 4),
668 inode->i_mapping, start,
675 unsigned long offset = offset_in_page(total_compressed);
676 struct page *page = pages[nr_pages - 1];
678 /* zero the tail end of the last page, we might be
679 * sending it down to disk
682 memzero_page(page, offset, PAGE_SIZE - offset);
688 * Check cow_file_range() for why we don't even try to create inline
689 * extent for subpage case.
691 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
692 /* lets try to make an inline extent */
693 if (ret || total_in < actual_end) {
694 /* we didn't compress the entire range, try
695 * to make an uncompressed inline extent.
697 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
698 0, BTRFS_COMPRESS_NONE,
701 /* try making a compressed inline extent */
702 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
704 compress_type, pages);
707 unsigned long clear_flags = EXTENT_DELALLOC |
708 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
709 EXTENT_DO_ACCOUNTING;
710 unsigned long page_error_op;
712 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
715 * inline extent creation worked or returned error,
716 * we don't need to create any more async work items.
717 * Unlock and free up our temp pages.
719 * We use DO_ACCOUNTING here because we need the
720 * delalloc_release_metadata to be done _after_ we drop
721 * our outstanding extent for clearing delalloc for this
724 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
728 PAGE_START_WRITEBACK |
733 * Ensure we only free the compressed pages if we have
734 * them allocated, as we can still reach here with
735 * inode_need_compress() == false.
738 for (i = 0; i < nr_pages; i++) {
739 WARN_ON(pages[i]->mapping);
750 * we aren't doing an inline extent round the compressed size
751 * up to a block size boundary so the allocator does sane
754 total_compressed = ALIGN(total_compressed, blocksize);
757 * one last check to make sure the compression is really a
758 * win, compare the page count read with the blocks on disk,
759 * compression must free at least one sector size
761 total_in = ALIGN(total_in, PAGE_SIZE);
762 if (total_compressed + blocksize <= total_in) {
763 compressed_extents++;
766 * The async work queues will take care of doing actual
767 * allocation on disk for these compressed pages, and
768 * will submit them to the elevator.
770 add_async_extent(async_chunk, start, total_in,
771 total_compressed, pages, nr_pages,
774 if (start + total_in < end) {
780 return compressed_extents;
785 * the compression code ran but failed to make things smaller,
786 * free any pages it allocated and our page pointer array
788 for (i = 0; i < nr_pages; i++) {
789 WARN_ON(pages[i]->mapping);
794 total_compressed = 0;
797 /* flag the file so we don't compress in the future */
798 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
799 !(BTRFS_I(inode)->prop_compress)) {
800 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
803 cleanup_and_bail_uncompressed:
805 * No compression, but we still need to write the pages in the file
806 * we've been given so far. redirty the locked page if it corresponds
807 * to our extent and set things up for the async work queue to run
808 * cow_file_range to do the normal delalloc dance.
810 if (async_chunk->locked_page &&
811 (page_offset(async_chunk->locked_page) >= start &&
812 page_offset(async_chunk->locked_page)) <= end) {
813 __set_page_dirty_nobuffers(async_chunk->locked_page);
814 /* unlocked later on in the async handlers */
818 extent_range_redirty_for_io(inode, start, end);
819 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
820 BTRFS_COMPRESS_NONE);
821 compressed_extents++;
823 return compressed_extents;
826 static void free_async_extent_pages(struct async_extent *async_extent)
830 if (!async_extent->pages)
833 for (i = 0; i < async_extent->nr_pages; i++) {
834 WARN_ON(async_extent->pages[i]->mapping);
835 put_page(async_extent->pages[i]);
837 kfree(async_extent->pages);
838 async_extent->nr_pages = 0;
839 async_extent->pages = NULL;
843 * phase two of compressed writeback. This is the ordered portion
844 * of the code, which only gets called in the order the work was
845 * queued. We walk all the async extents created by compress_file_range
846 * and send them down to the disk.
848 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
850 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
851 struct btrfs_fs_info *fs_info = inode->root->fs_info;
852 struct async_extent *async_extent;
854 struct btrfs_key ins;
855 struct extent_map *em;
856 struct btrfs_root *root = inode->root;
857 struct extent_io_tree *io_tree = &inode->io_tree;
861 while (!list_empty(&async_chunk->extents)) {
862 async_extent = list_entry(async_chunk->extents.next,
863 struct async_extent, list);
864 list_del(&async_extent->list);
867 lock_extent(io_tree, async_extent->start,
868 async_extent->start + async_extent->ram_size - 1);
869 /* did the compression code fall back to uncompressed IO? */
870 if (!async_extent->pages) {
871 int page_started = 0;
872 unsigned long nr_written = 0;
874 /* allocate blocks */
875 ret = cow_file_range(inode, async_chunk->locked_page,
877 async_extent->start +
878 async_extent->ram_size - 1,
879 &page_started, &nr_written, 0);
884 * if page_started, cow_file_range inserted an
885 * inline extent and took care of all the unlocking
886 * and IO for us. Otherwise, we need to submit
887 * all those pages down to the drive.
889 if (!page_started && !ret)
890 extent_write_locked_range(&inode->vfs_inode,
892 async_extent->start +
893 async_extent->ram_size - 1,
895 else if (ret && async_chunk->locked_page)
896 unlock_page(async_chunk->locked_page);
902 ret = btrfs_reserve_extent(root, async_extent->ram_size,
903 async_extent->compressed_size,
904 async_extent->compressed_size,
905 0, alloc_hint, &ins, 1, 1);
907 free_async_extent_pages(async_extent);
909 if (ret == -ENOSPC) {
910 unlock_extent(io_tree, async_extent->start,
911 async_extent->start +
912 async_extent->ram_size - 1);
915 * we need to redirty the pages if we decide to
916 * fallback to uncompressed IO, otherwise we
917 * will not submit these pages down to lower
920 extent_range_redirty_for_io(&inode->vfs_inode,
922 async_extent->start +
923 async_extent->ram_size - 1);
930 * here we're doing allocation and writeback of the
933 em = create_io_em(inode, async_extent->start,
934 async_extent->ram_size, /* len */
935 async_extent->start, /* orig_start */
936 ins.objectid, /* block_start */
937 ins.offset, /* block_len */
938 ins.offset, /* orig_block_len */
939 async_extent->ram_size, /* ram_bytes */
940 async_extent->compress_type,
941 BTRFS_ORDERED_COMPRESSED);
943 /* ret value is not necessary due to void function */
944 goto out_free_reserve;
947 ret = btrfs_add_ordered_extent_compress(inode,
950 async_extent->ram_size,
952 async_extent->compress_type);
954 btrfs_drop_extent_cache(inode, async_extent->start,
955 async_extent->start +
956 async_extent->ram_size - 1, 0);
957 goto out_free_reserve;
959 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
962 * clear dirty, set writeback and unlock the pages.
964 extent_clear_unlock_delalloc(inode, async_extent->start,
965 async_extent->start +
966 async_extent->ram_size - 1,
967 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
968 PAGE_UNLOCK | PAGE_START_WRITEBACK);
969 if (btrfs_submit_compressed_write(inode, async_extent->start,
970 async_extent->ram_size,
972 ins.offset, async_extent->pages,
973 async_extent->nr_pages,
974 async_chunk->write_flags,
975 async_chunk->blkcg_css)) {
976 struct page *p = async_extent->pages[0];
977 const u64 start = async_extent->start;
978 const u64 end = start + async_extent->ram_size - 1;
980 p->mapping = inode->vfs_inode.i_mapping;
981 btrfs_writepage_endio_finish_ordered(inode, p, start,
985 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
988 free_async_extent_pages(async_extent);
990 alloc_hint = ins.objectid + ins.offset;
996 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
997 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
999 extent_clear_unlock_delalloc(inode, async_extent->start,
1000 async_extent->start +
1001 async_extent->ram_size - 1,
1002 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1003 EXTENT_DELALLOC_NEW |
1004 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1005 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1006 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1007 free_async_extent_pages(async_extent);
1008 kfree(async_extent);
1012 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1015 struct extent_map_tree *em_tree = &inode->extent_tree;
1016 struct extent_map *em;
1019 read_lock(&em_tree->lock);
1020 em = search_extent_mapping(em_tree, start, num_bytes);
1023 * if block start isn't an actual block number then find the
1024 * first block in this inode and use that as a hint. If that
1025 * block is also bogus then just don't worry about it.
1027 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1028 free_extent_map(em);
1029 em = search_extent_mapping(em_tree, 0, 0);
1030 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1031 alloc_hint = em->block_start;
1033 free_extent_map(em);
1035 alloc_hint = em->block_start;
1036 free_extent_map(em);
1039 read_unlock(&em_tree->lock);
1045 * when extent_io.c finds a delayed allocation range in the file,
1046 * the call backs end up in this code. The basic idea is to
1047 * allocate extents on disk for the range, and create ordered data structs
1048 * in ram to track those extents.
1050 * locked_page is the page that writepage had locked already. We use
1051 * it to make sure we don't do extra locks or unlocks.
1053 * *page_started is set to one if we unlock locked_page and do everything
1054 * required to start IO on it. It may be clean and already done with
1055 * IO when we return.
1057 * When unlock == 1, we unlock the pages in successfully allocated regions.
1058 * When unlock == 0, we leave them locked for writing them out.
1060 * However, we unlock all the pages except @locked_page in case of failure.
1062 * In summary, page locking state will be as follow:
1064 * - page_started == 1 (return value)
1065 * - All the pages are unlocked. IO is started.
1066 * - Note that this can happen only on success
1068 * - All the pages except @locked_page are unlocked in any case
1070 * - On success, all the pages are locked for writing out them
1071 * - On failure, all the pages except @locked_page are unlocked
1073 * When a failure happens in the second or later iteration of the
1074 * while-loop, the ordered extents created in previous iterations are kept
1075 * intact. So, the caller must clean them up by calling
1076 * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
1079 static noinline int cow_file_range(struct btrfs_inode *inode,
1080 struct page *locked_page,
1081 u64 start, u64 end, int *page_started,
1082 unsigned long *nr_written, int unlock)
1084 struct btrfs_root *root = inode->root;
1085 struct btrfs_fs_info *fs_info = root->fs_info;
1087 u64 orig_start = start;
1089 unsigned long ram_size;
1090 u64 cur_alloc_size = 0;
1092 u64 blocksize = fs_info->sectorsize;
1093 struct btrfs_key ins;
1094 struct extent_map *em;
1095 unsigned clear_bits;
1096 unsigned long page_ops;
1097 bool extent_reserved = false;
1100 if (btrfs_is_free_space_inode(inode)) {
1105 num_bytes = ALIGN(end - start + 1, blocksize);
1106 num_bytes = max(blocksize, num_bytes);
1107 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1109 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1112 * Due to the page size limit, for subpage we can only trigger the
1113 * writeback for the dirty sectors of page, that means data writeback
1114 * is doing more writeback than what we want.
1116 * This is especially unexpected for some call sites like fallocate,
1117 * where we only increase i_size after everything is done.
1118 * This means we can trigger inline extent even if we didn't want to.
1119 * So here we skip inline extent creation completely.
1121 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
1122 /* lets try to make an inline extent */
1123 ret = cow_file_range_inline(inode, start, end, 0,
1124 BTRFS_COMPRESS_NONE, NULL);
1127 * We use DO_ACCOUNTING here because we need the
1128 * delalloc_release_metadata to be run _after_ we drop
1129 * our outstanding extent for clearing delalloc for this
1132 extent_clear_unlock_delalloc(inode, start, end,
1134 EXTENT_LOCKED | EXTENT_DELALLOC |
1135 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1136 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1137 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1138 *nr_written = *nr_written +
1139 (end - start + PAGE_SIZE) / PAGE_SIZE;
1142 * locked_page is locked by the caller of
1143 * writepage_delalloc(), not locked by
1144 * __process_pages_contig().
1146 * We can't let __process_pages_contig() to unlock it,
1147 * as it doesn't have any subpage::writers recorded.
1149 * Here we manually unlock the page, since the caller
1150 * can't use page_started to determine if it's an
1151 * inline extent or a compressed extent.
1153 unlock_page(locked_page);
1155 } else if (ret < 0) {
1160 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1161 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1164 * Relocation relies on the relocated extents to have exactly the same
1165 * size as the original extents. Normally writeback for relocation data
1166 * extents follows a NOCOW path because relocation preallocates the
1167 * extents. However, due to an operation such as scrub turning a block
1168 * group to RO mode, it may fallback to COW mode, so we must make sure
1169 * an extent allocated during COW has exactly the requested size and can
1170 * not be split into smaller extents, otherwise relocation breaks and
1171 * fails during the stage where it updates the bytenr of file extent
1174 if (btrfs_is_data_reloc_root(root))
1175 min_alloc_size = num_bytes;
1177 min_alloc_size = fs_info->sectorsize;
1179 while (num_bytes > 0) {
1180 cur_alloc_size = num_bytes;
1181 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1182 min_alloc_size, 0, alloc_hint,
1186 cur_alloc_size = ins.offset;
1187 extent_reserved = true;
1189 ram_size = ins.offset;
1190 em = create_io_em(inode, start, ins.offset, /* len */
1191 start, /* orig_start */
1192 ins.objectid, /* block_start */
1193 ins.offset, /* block_len */
1194 ins.offset, /* orig_block_len */
1195 ram_size, /* ram_bytes */
1196 BTRFS_COMPRESS_NONE, /* compress_type */
1197 BTRFS_ORDERED_REGULAR /* type */);
1202 free_extent_map(em);
1204 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1205 ram_size, cur_alloc_size,
1206 BTRFS_ORDERED_REGULAR);
1208 goto out_drop_extent_cache;
1210 if (btrfs_is_data_reloc_root(root)) {
1211 ret = btrfs_reloc_clone_csums(inode, start,
1214 * Only drop cache here, and process as normal.
1216 * We must not allow extent_clear_unlock_delalloc()
1217 * at out_unlock label to free meta of this ordered
1218 * extent, as its meta should be freed by
1219 * btrfs_finish_ordered_io().
1221 * So we must continue until @start is increased to
1222 * skip current ordered extent.
1225 btrfs_drop_extent_cache(inode, start,
1226 start + ram_size - 1, 0);
1229 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1232 * We're not doing compressed IO, don't unlock the first page
1233 * (which the caller expects to stay locked), don't clear any
1234 * dirty bits and don't set any writeback bits
1236 * Do set the Ordered (Private2) bit so we know this page was
1237 * properly setup for writepage.
1239 page_ops = unlock ? PAGE_UNLOCK : 0;
1240 page_ops |= PAGE_SET_ORDERED;
1242 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1244 EXTENT_LOCKED | EXTENT_DELALLOC,
1246 if (num_bytes < cur_alloc_size)
1249 num_bytes -= cur_alloc_size;
1250 alloc_hint = ins.objectid + ins.offset;
1251 start += cur_alloc_size;
1252 extent_reserved = false;
1255 * btrfs_reloc_clone_csums() error, since start is increased
1256 * extent_clear_unlock_delalloc() at out_unlock label won't
1257 * free metadata of current ordered extent, we're OK to exit.
1265 out_drop_extent_cache:
1266 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1268 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1269 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1272 * Now, we have three regions to clean up:
1274 * |-------(1)----|---(2)---|-------------(3)----------|
1275 * `- orig_start `- start `- start + cur_alloc_size `- end
1277 * We process each region below.
1280 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1281 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1282 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1285 * For the range (1). We have already instantiated the ordered extents
1286 * for this region. They are cleaned up by
1287 * btrfs_cleanup_ordered_extents() in e.g,
1288 * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
1289 * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
1290 * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
1293 * However, in case of unlock == 0, we still need to unlock the pages
1294 * (except @locked_page) to ensure all the pages are unlocked.
1296 if (!unlock && orig_start < start)
1297 extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1298 locked_page, 0, page_ops);
1301 * For the range (2). If we reserved an extent for our delalloc range
1302 * (or a subrange) and failed to create the respective ordered extent,
1303 * then it means that when we reserved the extent we decremented the
1304 * extent's size from the data space_info's bytes_may_use counter and
1305 * incremented the space_info's bytes_reserved counter by the same
1306 * amount. We must make sure extent_clear_unlock_delalloc() does not try
1307 * to decrement again the data space_info's bytes_may_use counter,
1308 * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
1310 if (extent_reserved) {
1311 extent_clear_unlock_delalloc(inode, start,
1312 start + cur_alloc_size - 1,
1316 start += cur_alloc_size;
1322 * For the range (3). We never touched the region. In addition to the
1323 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1324 * space_info's bytes_may_use counter, reserved in
1325 * btrfs_check_data_free_space().
1327 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1328 clear_bits | EXTENT_CLEAR_DATA_RESV,
1334 * work queue call back to started compression on a file and pages
1336 static noinline void async_cow_start(struct btrfs_work *work)
1338 struct async_chunk *async_chunk;
1339 int compressed_extents;
1341 async_chunk = container_of(work, struct async_chunk, work);
1343 compressed_extents = compress_file_range(async_chunk);
1344 if (compressed_extents == 0) {
1345 btrfs_add_delayed_iput(async_chunk->inode);
1346 async_chunk->inode = NULL;
1351 * work queue call back to submit previously compressed pages
1353 static noinline void async_cow_submit(struct btrfs_work *work)
1355 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1357 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1358 unsigned long nr_pages;
1360 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1364 * ->inode could be NULL if async_chunk_start has failed to compress,
1365 * in which case we don't have anything to submit, yet we need to
1366 * always adjust ->async_delalloc_pages as its paired with the init
1367 * happening in cow_file_range_async
1369 if (async_chunk->inode)
1370 submit_compressed_extents(async_chunk);
1372 /* atomic_sub_return implies a barrier */
1373 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1375 cond_wake_up_nomb(&fs_info->async_submit_wait);
1378 static noinline void async_cow_free(struct btrfs_work *work)
1380 struct async_chunk *async_chunk;
1382 async_chunk = container_of(work, struct async_chunk, work);
1383 if (async_chunk->inode)
1384 btrfs_add_delayed_iput(async_chunk->inode);
1385 if (async_chunk->blkcg_css)
1386 css_put(async_chunk->blkcg_css);
1388 * Since the pointer to 'pending' is at the beginning of the array of
1389 * async_chunk's, freeing it ensures the whole array has been freed.
1391 if (atomic_dec_and_test(async_chunk->pending))
1392 kvfree(async_chunk->pending);
1395 static int cow_file_range_async(struct btrfs_inode *inode,
1396 struct writeback_control *wbc,
1397 struct page *locked_page,
1398 u64 start, u64 end, int *page_started,
1399 unsigned long *nr_written)
1401 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1402 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1403 struct async_cow *ctx;
1404 struct async_chunk *async_chunk;
1405 unsigned long nr_pages;
1407 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1409 bool should_compress;
1411 const unsigned int write_flags = wbc_to_write_flags(wbc);
1413 unlock_extent(&inode->io_tree, start, end);
1415 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1416 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1418 should_compress = false;
1420 should_compress = true;
1423 nofs_flag = memalloc_nofs_save();
1424 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1425 memalloc_nofs_restore(nofs_flag);
1428 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1429 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1430 EXTENT_DO_ACCOUNTING;
1431 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1432 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1434 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1435 clear_bits, page_ops);
1439 async_chunk = ctx->chunks;
1440 atomic_set(&ctx->num_chunks, num_chunks);
1442 for (i = 0; i < num_chunks; i++) {
1443 if (should_compress)
1444 cur_end = min(end, start + SZ_512K - 1);
1449 * igrab is called higher up in the call chain, take only the
1450 * lightweight reference for the callback lifetime
1452 ihold(&inode->vfs_inode);
1453 async_chunk[i].pending = &ctx->num_chunks;
1454 async_chunk[i].inode = &inode->vfs_inode;
1455 async_chunk[i].start = start;
1456 async_chunk[i].end = cur_end;
1457 async_chunk[i].write_flags = write_flags;
1458 INIT_LIST_HEAD(&async_chunk[i].extents);
1461 * The locked_page comes all the way from writepage and its
1462 * the original page we were actually given. As we spread
1463 * this large delalloc region across multiple async_chunk
1464 * structs, only the first struct needs a pointer to locked_page
1466 * This way we don't need racey decisions about who is supposed
1471 * Depending on the compressibility, the pages might or
1472 * might not go through async. We want all of them to
1473 * be accounted against wbc once. Let's do it here
1474 * before the paths diverge. wbc accounting is used
1475 * only for foreign writeback detection and doesn't
1476 * need full accuracy. Just account the whole thing
1477 * against the first page.
1479 wbc_account_cgroup_owner(wbc, locked_page,
1481 async_chunk[i].locked_page = locked_page;
1484 async_chunk[i].locked_page = NULL;
1487 if (blkcg_css != blkcg_root_css) {
1489 async_chunk[i].blkcg_css = blkcg_css;
1491 async_chunk[i].blkcg_css = NULL;
1494 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1495 async_cow_submit, async_cow_free);
1497 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1498 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1500 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1502 *nr_written += nr_pages;
1503 start = cur_end + 1;
1509 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1510 struct page *locked_page, u64 start,
1511 u64 end, int *page_started,
1512 unsigned long *nr_written)
1516 ret = cow_file_range(inode, locked_page, start, end, page_started,
1524 __set_page_dirty_nobuffers(locked_page);
1525 account_page_redirty(locked_page);
1526 extent_write_locked_range(&inode->vfs_inode, start, end, WB_SYNC_ALL);
1532 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1533 u64 bytenr, u64 num_bytes)
1536 struct btrfs_ordered_sum *sums;
1539 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1540 bytenr + num_bytes - 1, &list, 0);
1541 if (ret == 0 && list_empty(&list))
1544 while (!list_empty(&list)) {
1545 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1546 list_del(&sums->list);
1554 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1555 const u64 start, const u64 end,
1556 int *page_started, unsigned long *nr_written)
1558 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1559 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1560 const u64 range_bytes = end + 1 - start;
1561 struct extent_io_tree *io_tree = &inode->io_tree;
1562 u64 range_start = start;
1566 * If EXTENT_NORESERVE is set it means that when the buffered write was
1567 * made we had not enough available data space and therefore we did not
1568 * reserve data space for it, since we though we could do NOCOW for the
1569 * respective file range (either there is prealloc extent or the inode
1570 * has the NOCOW bit set).
1572 * However when we need to fallback to COW mode (because for example the
1573 * block group for the corresponding extent was turned to RO mode by a
1574 * scrub or relocation) we need to do the following:
1576 * 1) We increment the bytes_may_use counter of the data space info.
1577 * If COW succeeds, it allocates a new data extent and after doing
1578 * that it decrements the space info's bytes_may_use counter and
1579 * increments its bytes_reserved counter by the same amount (we do
1580 * this at btrfs_add_reserved_bytes()). So we need to increment the
1581 * bytes_may_use counter to compensate (when space is reserved at
1582 * buffered write time, the bytes_may_use counter is incremented);
1584 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1585 * that if the COW path fails for any reason, it decrements (through
1586 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1587 * data space info, which we incremented in the step above.
1589 * If we need to fallback to cow and the inode corresponds to a free
1590 * space cache inode or an inode of the data relocation tree, we must
1591 * also increment bytes_may_use of the data space_info for the same
1592 * reason. Space caches and relocated data extents always get a prealloc
1593 * extent for them, however scrub or balance may have set the block
1594 * group that contains that extent to RO mode and therefore force COW
1595 * when starting writeback.
1597 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1598 EXTENT_NORESERVE, 0);
1599 if (count > 0 || is_space_ino || is_reloc_ino) {
1601 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1602 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1604 if (is_space_ino || is_reloc_ino)
1605 bytes = range_bytes;
1607 spin_lock(&sinfo->lock);
1608 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1609 spin_unlock(&sinfo->lock);
1612 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1616 return cow_file_range(inode, locked_page, start, end, page_started,
1621 * when nowcow writeback call back. This checks for snapshots or COW copies
1622 * of the extents that exist in the file, and COWs the file as required.
1624 * If no cow copies or snapshots exist, we write directly to the existing
1627 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1628 struct page *locked_page,
1629 const u64 start, const u64 end,
1631 unsigned long *nr_written)
1633 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1634 struct btrfs_root *root = inode->root;
1635 struct btrfs_path *path;
1636 u64 cow_start = (u64)-1;
1637 u64 cur_offset = start;
1639 bool check_prev = true;
1640 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1641 u64 ino = btrfs_ino(inode);
1643 u64 disk_bytenr = 0;
1644 const bool force = inode->flags & BTRFS_INODE_NODATACOW;
1646 path = btrfs_alloc_path();
1648 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1649 EXTENT_LOCKED | EXTENT_DELALLOC |
1650 EXTENT_DO_ACCOUNTING |
1651 EXTENT_DEFRAG, PAGE_UNLOCK |
1652 PAGE_START_WRITEBACK |
1653 PAGE_END_WRITEBACK);
1658 struct btrfs_key found_key;
1659 struct btrfs_file_extent_item *fi;
1660 struct extent_buffer *leaf;
1670 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1676 * If there is no extent for our range when doing the initial
1677 * search, then go back to the previous slot as it will be the
1678 * one containing the search offset
1680 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1681 leaf = path->nodes[0];
1682 btrfs_item_key_to_cpu(leaf, &found_key,
1683 path->slots[0] - 1);
1684 if (found_key.objectid == ino &&
1685 found_key.type == BTRFS_EXTENT_DATA_KEY)
1690 /* Go to next leaf if we have exhausted the current one */
1691 leaf = path->nodes[0];
1692 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1693 ret = btrfs_next_leaf(root, path);
1695 if (cow_start != (u64)-1)
1696 cur_offset = cow_start;
1701 leaf = path->nodes[0];
1704 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1706 /* Didn't find anything for our INO */
1707 if (found_key.objectid > ino)
1710 * Keep searching until we find an EXTENT_ITEM or there are no
1711 * more extents for this inode
1713 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1714 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1719 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1720 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1721 found_key.offset > end)
1725 * If the found extent starts after requested offset, then
1726 * adjust extent_end to be right before this extent begins
1728 if (found_key.offset > cur_offset) {
1729 extent_end = found_key.offset;
1735 * Found extent which begins before our range and potentially
1738 fi = btrfs_item_ptr(leaf, path->slots[0],
1739 struct btrfs_file_extent_item);
1740 extent_type = btrfs_file_extent_type(leaf, fi);
1742 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1743 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1744 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1745 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1746 extent_offset = btrfs_file_extent_offset(leaf, fi);
1747 extent_end = found_key.offset +
1748 btrfs_file_extent_num_bytes(leaf, fi);
1750 btrfs_file_extent_disk_num_bytes(leaf, fi);
1752 * If the extent we got ends before our current offset,
1753 * skip to the next extent.
1755 if (extent_end <= cur_offset) {
1760 if (disk_bytenr == 0)
1762 /* Skip compressed/encrypted/encoded extents */
1763 if (btrfs_file_extent_compression(leaf, fi) ||
1764 btrfs_file_extent_encryption(leaf, fi) ||
1765 btrfs_file_extent_other_encoding(leaf, fi))
1768 * If extent is created before the last volume's snapshot
1769 * this implies the extent is shared, hence we can't do
1770 * nocow. This is the same check as in
1771 * btrfs_cross_ref_exist but without calling
1772 * btrfs_search_slot.
1774 if (!freespace_inode &&
1775 btrfs_file_extent_generation(leaf, fi) <=
1776 btrfs_root_last_snapshot(&root->root_item))
1778 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1782 * The following checks can be expensive, as they need to
1783 * take other locks and do btree or rbtree searches, so
1784 * release the path to avoid blocking other tasks for too
1787 btrfs_release_path(path);
1789 ret = btrfs_cross_ref_exist(root, ino,
1791 extent_offset, disk_bytenr, false);
1794 * ret could be -EIO if the above fails to read
1798 if (cow_start != (u64)-1)
1799 cur_offset = cow_start;
1803 WARN_ON_ONCE(freespace_inode);
1806 disk_bytenr += extent_offset;
1807 disk_bytenr += cur_offset - found_key.offset;
1808 num_bytes = min(end + 1, extent_end) - cur_offset;
1810 * If there are pending snapshots for this root, we
1811 * fall into common COW way
1813 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1816 * force cow if csum exists in the range.
1817 * this ensure that csum for a given extent are
1818 * either valid or do not exist.
1820 ret = csum_exist_in_range(fs_info, disk_bytenr,
1824 * ret could be -EIO if the above fails to read
1828 if (cow_start != (u64)-1)
1829 cur_offset = cow_start;
1832 WARN_ON_ONCE(freespace_inode);
1835 /* If the extent's block group is RO, we must COW */
1836 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1839 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1840 extent_end = found_key.offset + ram_bytes;
1841 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1842 /* Skip extents outside of our requested range */
1843 if (extent_end <= start) {
1848 /* If this triggers then we have a memory corruption */
1853 * If nocow is false then record the beginning of the range
1854 * that needs to be COWed
1857 if (cow_start == (u64)-1)
1858 cow_start = cur_offset;
1859 cur_offset = extent_end;
1860 if (cur_offset > end)
1862 if (!path->nodes[0])
1869 * COW range from cow_start to found_key.offset - 1. As the key
1870 * will contain the beginning of the first extent that can be
1871 * NOCOW, following one which needs to be COW'ed
1873 if (cow_start != (u64)-1) {
1874 ret = fallback_to_cow(inode, locked_page,
1875 cow_start, found_key.offset - 1,
1876 page_started, nr_written);
1879 cow_start = (u64)-1;
1882 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1883 u64 orig_start = found_key.offset - extent_offset;
1884 struct extent_map *em;
1886 em = create_io_em(inode, cur_offset, num_bytes,
1888 disk_bytenr, /* block_start */
1889 num_bytes, /* block_len */
1890 disk_num_bytes, /* orig_block_len */
1891 ram_bytes, BTRFS_COMPRESS_NONE,
1892 BTRFS_ORDERED_PREALLOC);
1897 free_extent_map(em);
1898 ret = btrfs_add_ordered_extent(inode, cur_offset,
1899 disk_bytenr, num_bytes,
1901 BTRFS_ORDERED_PREALLOC);
1903 btrfs_drop_extent_cache(inode, cur_offset,
1904 cur_offset + num_bytes - 1,
1909 ret = btrfs_add_ordered_extent(inode, cur_offset,
1910 disk_bytenr, num_bytes,
1912 BTRFS_ORDERED_NOCOW);
1918 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1921 if (btrfs_is_data_reloc_root(root))
1923 * Error handled later, as we must prevent
1924 * extent_clear_unlock_delalloc() in error handler
1925 * from freeing metadata of created ordered extent.
1927 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1930 extent_clear_unlock_delalloc(inode, cur_offset,
1931 cur_offset + num_bytes - 1,
1932 locked_page, EXTENT_LOCKED |
1934 EXTENT_CLEAR_DATA_RESV,
1935 PAGE_UNLOCK | PAGE_SET_ORDERED);
1937 cur_offset = extent_end;
1940 * btrfs_reloc_clone_csums() error, now we're OK to call error
1941 * handler, as metadata for created ordered extent will only
1942 * be freed by btrfs_finish_ordered_io().
1946 if (cur_offset > end)
1949 btrfs_release_path(path);
1951 if (cur_offset <= end && cow_start == (u64)-1)
1952 cow_start = cur_offset;
1954 if (cow_start != (u64)-1) {
1956 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1957 page_started, nr_written);
1964 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1966 if (ret && cur_offset < end)
1967 extent_clear_unlock_delalloc(inode, cur_offset, end,
1968 locked_page, EXTENT_LOCKED |
1969 EXTENT_DELALLOC | EXTENT_DEFRAG |
1970 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1971 PAGE_START_WRITEBACK |
1972 PAGE_END_WRITEBACK);
1973 btrfs_free_path(path);
1977 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
1979 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
1980 if (inode->defrag_bytes &&
1981 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
1990 * Function to process delayed allocation (create CoW) for ranges which are
1991 * being touched for the first time.
1993 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1994 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1995 struct writeback_control *wbc)
1998 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2000 if (should_nocow(inode, start, end)) {
2002 * Normally on a zoned device we're only doing COW writes, but
2003 * in case of relocation on a zoned filesystem we have taken
2004 * precaution, that we're only writing sequentially. It's safe
2005 * to use run_delalloc_nocow() here, like for regular
2006 * preallocated inodes.
2009 (zoned && btrfs_is_data_reloc_root(inode->root)));
2010 ret = run_delalloc_nocow(inode, locked_page, start, end,
2011 page_started, nr_written);
2012 } else if (!inode_can_compress(inode) ||
2013 !inode_need_compress(inode, start, end)) {
2015 ret = run_delalloc_zoned(inode, locked_page, start, end,
2016 page_started, nr_written);
2018 ret = cow_file_range(inode, locked_page, start, end,
2019 page_started, nr_written, 1);
2021 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
2022 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
2023 page_started, nr_written);
2027 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2032 void btrfs_split_delalloc_extent(struct inode *inode,
2033 struct extent_state *orig, u64 split)
2035 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2038 /* not delalloc, ignore it */
2039 if (!(orig->state & EXTENT_DELALLOC))
2042 size = orig->end - orig->start + 1;
2043 if (size > fs_info->max_extent_size) {
2048 * See the explanation in btrfs_merge_delalloc_extent, the same
2049 * applies here, just in reverse.
2051 new_size = orig->end - split + 1;
2052 num_extents = count_max_extents(fs_info, new_size);
2053 new_size = split - orig->start;
2054 num_extents += count_max_extents(fs_info, new_size);
2055 if (count_max_extents(fs_info, size) >= num_extents)
2059 spin_lock(&BTRFS_I(inode)->lock);
2060 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
2061 spin_unlock(&BTRFS_I(inode)->lock);
2065 * Handle merged delayed allocation extents so we can keep track of new extents
2066 * that are just merged onto old extents, such as when we are doing sequential
2067 * writes, so we can properly account for the metadata space we'll need.
2069 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
2070 struct extent_state *other)
2072 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2073 u64 new_size, old_size;
2076 /* not delalloc, ignore it */
2077 if (!(other->state & EXTENT_DELALLOC))
2080 if (new->start > other->start)
2081 new_size = new->end - other->start + 1;
2083 new_size = other->end - new->start + 1;
2085 /* we're not bigger than the max, unreserve the space and go */
2086 if (new_size <= fs_info->max_extent_size) {
2087 spin_lock(&BTRFS_I(inode)->lock);
2088 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2089 spin_unlock(&BTRFS_I(inode)->lock);
2094 * We have to add up either side to figure out how many extents were
2095 * accounted for before we merged into one big extent. If the number of
2096 * extents we accounted for is <= the amount we need for the new range
2097 * then we can return, otherwise drop. Think of it like this
2101 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2102 * need 2 outstanding extents, on one side we have 1 and the other side
2103 * we have 1 so they are == and we can return. But in this case
2105 * [MAX_SIZE+4k][MAX_SIZE+4k]
2107 * Each range on their own accounts for 2 extents, but merged together
2108 * they are only 3 extents worth of accounting, so we need to drop in
2111 old_size = other->end - other->start + 1;
2112 num_extents = count_max_extents(fs_info, old_size);
2113 old_size = new->end - new->start + 1;
2114 num_extents += count_max_extents(fs_info, old_size);
2115 if (count_max_extents(fs_info, new_size) >= num_extents)
2118 spin_lock(&BTRFS_I(inode)->lock);
2119 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2120 spin_unlock(&BTRFS_I(inode)->lock);
2123 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2124 struct inode *inode)
2126 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2128 spin_lock(&root->delalloc_lock);
2129 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2130 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2131 &root->delalloc_inodes);
2132 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2133 &BTRFS_I(inode)->runtime_flags);
2134 root->nr_delalloc_inodes++;
2135 if (root->nr_delalloc_inodes == 1) {
2136 spin_lock(&fs_info->delalloc_root_lock);
2137 BUG_ON(!list_empty(&root->delalloc_root));
2138 list_add_tail(&root->delalloc_root,
2139 &fs_info->delalloc_roots);
2140 spin_unlock(&fs_info->delalloc_root_lock);
2143 spin_unlock(&root->delalloc_lock);
2147 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2148 struct btrfs_inode *inode)
2150 struct btrfs_fs_info *fs_info = root->fs_info;
2152 if (!list_empty(&inode->delalloc_inodes)) {
2153 list_del_init(&inode->delalloc_inodes);
2154 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2155 &inode->runtime_flags);
2156 root->nr_delalloc_inodes--;
2157 if (!root->nr_delalloc_inodes) {
2158 ASSERT(list_empty(&root->delalloc_inodes));
2159 spin_lock(&fs_info->delalloc_root_lock);
2160 BUG_ON(list_empty(&root->delalloc_root));
2161 list_del_init(&root->delalloc_root);
2162 spin_unlock(&fs_info->delalloc_root_lock);
2167 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2168 struct btrfs_inode *inode)
2170 spin_lock(&root->delalloc_lock);
2171 __btrfs_del_delalloc_inode(root, inode);
2172 spin_unlock(&root->delalloc_lock);
2176 * Properly track delayed allocation bytes in the inode and to maintain the
2177 * list of inodes that have pending delalloc work to be done.
2179 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2182 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2184 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2187 * set_bit and clear bit hooks normally require _irqsave/restore
2188 * but in this case, we are only testing for the DELALLOC
2189 * bit, which is only set or cleared with irqs on
2191 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2192 struct btrfs_root *root = BTRFS_I(inode)->root;
2193 u64 len = state->end + 1 - state->start;
2194 u32 num_extents = count_max_extents(fs_info, len);
2195 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2197 spin_lock(&BTRFS_I(inode)->lock);
2198 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2199 spin_unlock(&BTRFS_I(inode)->lock);
2201 /* For sanity tests */
2202 if (btrfs_is_testing(fs_info))
2205 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2206 fs_info->delalloc_batch);
2207 spin_lock(&BTRFS_I(inode)->lock);
2208 BTRFS_I(inode)->delalloc_bytes += len;
2209 if (*bits & EXTENT_DEFRAG)
2210 BTRFS_I(inode)->defrag_bytes += len;
2211 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2212 &BTRFS_I(inode)->runtime_flags))
2213 btrfs_add_delalloc_inodes(root, inode);
2214 spin_unlock(&BTRFS_I(inode)->lock);
2217 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2218 (*bits & EXTENT_DELALLOC_NEW)) {
2219 spin_lock(&BTRFS_I(inode)->lock);
2220 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2222 spin_unlock(&BTRFS_I(inode)->lock);
2227 * Once a range is no longer delalloc this function ensures that proper
2228 * accounting happens.
2230 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2231 struct extent_state *state, unsigned *bits)
2233 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2234 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2235 u64 len = state->end + 1 - state->start;
2236 u32 num_extents = count_max_extents(fs_info, len);
2238 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2239 spin_lock(&inode->lock);
2240 inode->defrag_bytes -= len;
2241 spin_unlock(&inode->lock);
2245 * set_bit and clear bit hooks normally require _irqsave/restore
2246 * but in this case, we are only testing for the DELALLOC
2247 * bit, which is only set or cleared with irqs on
2249 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2250 struct btrfs_root *root = inode->root;
2251 bool do_list = !btrfs_is_free_space_inode(inode);
2253 spin_lock(&inode->lock);
2254 btrfs_mod_outstanding_extents(inode, -num_extents);
2255 spin_unlock(&inode->lock);
2258 * We don't reserve metadata space for space cache inodes so we
2259 * don't need to call delalloc_release_metadata if there is an
2262 if (*bits & EXTENT_CLEAR_META_RESV &&
2263 root != fs_info->tree_root)
2264 btrfs_delalloc_release_metadata(inode, len, false);
2266 /* For sanity tests. */
2267 if (btrfs_is_testing(fs_info))
2270 if (!btrfs_is_data_reloc_root(root) &&
2271 do_list && !(state->state & EXTENT_NORESERVE) &&
2272 (*bits & EXTENT_CLEAR_DATA_RESV))
2273 btrfs_free_reserved_data_space_noquota(fs_info, len);
2275 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2276 fs_info->delalloc_batch);
2277 spin_lock(&inode->lock);
2278 inode->delalloc_bytes -= len;
2279 if (do_list && inode->delalloc_bytes == 0 &&
2280 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2281 &inode->runtime_flags))
2282 btrfs_del_delalloc_inode(root, inode);
2283 spin_unlock(&inode->lock);
2286 if ((state->state & EXTENT_DELALLOC_NEW) &&
2287 (*bits & EXTENT_DELALLOC_NEW)) {
2288 spin_lock(&inode->lock);
2289 ASSERT(inode->new_delalloc_bytes >= len);
2290 inode->new_delalloc_bytes -= len;
2291 if (*bits & EXTENT_ADD_INODE_BYTES)
2292 inode_add_bytes(&inode->vfs_inode, len);
2293 spin_unlock(&inode->lock);
2298 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2299 * in a chunk's stripe. This function ensures that bios do not span a
2302 * @page - The page we are about to add to the bio
2303 * @size - size we want to add to the bio
2304 * @bio - bio we want to ensure is smaller than a stripe
2305 * @bio_flags - flags of the bio
2307 * return 1 if page cannot be added to the bio
2308 * return 0 if page can be added to the bio
2309 * return error otherwise
2311 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2312 unsigned long bio_flags)
2314 struct inode *inode = page->mapping->host;
2315 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2316 u64 logical = bio->bi_iter.bi_sector << 9;
2317 u32 bio_len = bio->bi_iter.bi_size;
2318 struct extent_map *em;
2320 struct btrfs_io_geometry geom;
2322 if (bio_flags & EXTENT_BIO_COMPRESSED)
2325 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
2328 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), logical, &geom);
2332 if (geom.len < bio_len + size)
2335 free_extent_map(em);
2340 * in order to insert checksums into the metadata in large chunks,
2341 * we wait until bio submission time. All the pages in the bio are
2342 * checksummed and sums are attached onto the ordered extent record.
2344 * At IO completion time the cums attached on the ordered extent record
2345 * are inserted into the btree
2347 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2348 u64 dio_file_offset)
2350 return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2354 * Split an extent_map at [start, start + len]
2356 * This function is intended to be used only for extract_ordered_extent().
2358 static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2361 struct extent_map_tree *em_tree = &inode->extent_tree;
2362 struct extent_map *em;
2363 struct extent_map *split_pre = NULL;
2364 struct extent_map *split_mid = NULL;
2365 struct extent_map *split_post = NULL;
2367 unsigned long flags;
2370 if (pre == 0 && post == 0)
2373 split_pre = alloc_extent_map();
2375 split_mid = alloc_extent_map();
2377 split_post = alloc_extent_map();
2378 if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2383 ASSERT(pre + post < len);
2385 lock_extent(&inode->io_tree, start, start + len - 1);
2386 write_lock(&em_tree->lock);
2387 em = lookup_extent_mapping(em_tree, start, len);
2393 ASSERT(em->len == len);
2394 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2395 ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2396 ASSERT(test_bit(EXTENT_FLAG_PINNED, &em->flags));
2397 ASSERT(!test_bit(EXTENT_FLAG_LOGGING, &em->flags));
2398 ASSERT(!list_empty(&em->list));
2401 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2403 /* First, replace the em with a new extent_map starting from * em->start */
2404 split_pre->start = em->start;
2405 split_pre->len = (pre ? pre : em->len - post);
2406 split_pre->orig_start = split_pre->start;
2407 split_pre->block_start = em->block_start;
2408 split_pre->block_len = split_pre->len;
2409 split_pre->orig_block_len = split_pre->block_len;
2410 split_pre->ram_bytes = split_pre->len;
2411 split_pre->flags = flags;
2412 split_pre->compress_type = em->compress_type;
2413 split_pre->generation = em->generation;
2415 replace_extent_mapping(em_tree, em, split_pre, 1);
2418 * Now we only have an extent_map at:
2419 * [em->start, em->start + pre] if pre != 0
2420 * [em->start, em->start + em->len - post] if pre == 0
2424 /* Insert the middle extent_map */
2425 split_mid->start = em->start + pre;
2426 split_mid->len = em->len - pre - post;
2427 split_mid->orig_start = split_mid->start;
2428 split_mid->block_start = em->block_start + pre;
2429 split_mid->block_len = split_mid->len;
2430 split_mid->orig_block_len = split_mid->block_len;
2431 split_mid->ram_bytes = split_mid->len;
2432 split_mid->flags = flags;
2433 split_mid->compress_type = em->compress_type;
2434 split_mid->generation = em->generation;
2435 add_extent_mapping(em_tree, split_mid, 1);
2439 split_post->start = em->start + em->len - post;
2440 split_post->len = post;
2441 split_post->orig_start = split_post->start;
2442 split_post->block_start = em->block_start + em->len - post;
2443 split_post->block_len = split_post->len;
2444 split_post->orig_block_len = split_post->block_len;
2445 split_post->ram_bytes = split_post->len;
2446 split_post->flags = flags;
2447 split_post->compress_type = em->compress_type;
2448 split_post->generation = em->generation;
2449 add_extent_mapping(em_tree, split_post, 1);
2453 free_extent_map(em);
2454 /* Once for the tree */
2455 free_extent_map(em);
2458 write_unlock(&em_tree->lock);
2459 unlock_extent(&inode->io_tree, start, start + len - 1);
2461 free_extent_map(split_pre);
2462 free_extent_map(split_mid);
2463 free_extent_map(split_post);
2468 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2469 struct bio *bio, loff_t file_offset)
2471 struct btrfs_ordered_extent *ordered;
2472 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2474 u64 len = bio->bi_iter.bi_size;
2475 u64 end = start + len;
2480 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2481 if (WARN_ON_ONCE(!ordered))
2482 return BLK_STS_IOERR;
2484 /* No need to split */
2485 if (ordered->disk_num_bytes == len)
2488 /* We cannot split once end_bio'd ordered extent */
2489 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2494 /* We cannot split a compressed ordered extent */
2495 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2500 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2501 /* bio must be in one ordered extent */
2502 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2507 /* Checksum list should be empty */
2508 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2513 file_len = ordered->num_bytes;
2514 pre = start - ordered->disk_bytenr;
2515 post = ordered_end - end;
2517 ret = btrfs_split_ordered_extent(ordered, pre, post);
2520 ret = split_zoned_em(inode, file_offset, file_len, pre, post);
2523 btrfs_put_ordered_extent(ordered);
2525 return errno_to_blk_status(ret);
2529 * extent_io.c submission hook. This does the right thing for csum calculation
2530 * on write, or reading the csums from the tree before a read.
2532 * Rules about async/sync submit,
2533 * a) read: sync submit
2535 * b) write without checksum: sync submit
2537 * c) write with checksum:
2538 * c-1) if bio is issued by fsync: sync submit
2539 * (sync_writers != 0)
2541 * c-2) if root is reloc root: sync submit
2542 * (only in case of buffered IO)
2544 * c-3) otherwise: async submit
2546 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2547 int mirror_num, unsigned long bio_flags)
2550 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2551 struct btrfs_root *root = BTRFS_I(inode)->root;
2552 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2553 blk_status_t ret = 0;
2555 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2557 skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2558 !fs_info->csum_root;
2560 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2561 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2563 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2564 struct page *page = bio_first_bvec_all(bio)->bv_page;
2565 loff_t file_offset = page_offset(page);
2567 ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2572 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2573 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2577 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2578 ret = btrfs_submit_compressed_read(inode, bio,
2584 * Lookup bio sums does extra checks around whether we
2585 * need to csum or not, which is why we ignore skip_sum
2588 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2593 } else if (async && !skip_sum) {
2594 /* csum items have already been cloned */
2595 if (btrfs_is_data_reloc_root(root))
2597 /* we're doing a write, do the async checksumming */
2598 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2599 0, btrfs_submit_bio_start);
2601 } else if (!skip_sum) {
2602 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2608 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2612 bio->bi_status = ret;
2619 * given a list of ordered sums record them in the inode. This happens
2620 * at IO completion time based on sums calculated at bio submission time.
2622 static int add_pending_csums(struct btrfs_trans_handle *trans,
2623 struct list_head *list)
2625 struct btrfs_ordered_sum *sum;
2628 list_for_each_entry(sum, list, list) {
2629 trans->adding_csums = true;
2630 ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2631 trans->adding_csums = false;
2638 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2641 struct extent_state **cached_state)
2643 u64 search_start = start;
2644 const u64 end = start + len - 1;
2646 while (search_start < end) {
2647 const u64 search_len = end - search_start + 1;
2648 struct extent_map *em;
2652 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2656 if (em->block_start != EXTENT_MAP_HOLE)
2660 if (em->start < search_start)
2661 em_len -= search_start - em->start;
2662 if (em_len > search_len)
2663 em_len = search_len;
2665 ret = set_extent_bit(&inode->io_tree, search_start,
2666 search_start + em_len - 1,
2667 EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2670 search_start = extent_map_end(em);
2671 free_extent_map(em);
2678 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2679 unsigned int extra_bits,
2680 struct extent_state **cached_state)
2682 WARN_ON(PAGE_ALIGNED(end));
2684 if (start >= i_size_read(&inode->vfs_inode) &&
2685 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2687 * There can't be any extents following eof in this case so just
2688 * set the delalloc new bit for the range directly.
2690 extra_bits |= EXTENT_DELALLOC_NEW;
2694 ret = btrfs_find_new_delalloc_bytes(inode, start,
2701 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2705 /* see btrfs_writepage_start_hook for details on why this is required */
2706 struct btrfs_writepage_fixup {
2708 struct inode *inode;
2709 struct btrfs_work work;
2712 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2714 struct btrfs_writepage_fixup *fixup;
2715 struct btrfs_ordered_extent *ordered;
2716 struct extent_state *cached_state = NULL;
2717 struct extent_changeset *data_reserved = NULL;
2719 struct btrfs_inode *inode;
2723 bool free_delalloc_space = true;
2725 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2727 inode = BTRFS_I(fixup->inode);
2728 page_start = page_offset(page);
2729 page_end = page_offset(page) + PAGE_SIZE - 1;
2732 * This is similar to page_mkwrite, we need to reserve the space before
2733 * we take the page lock.
2735 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2741 * Before we queued this fixup, we took a reference on the page.
2742 * page->mapping may go NULL, but it shouldn't be moved to a different
2745 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2747 * Unfortunately this is a little tricky, either
2749 * 1) We got here and our page had already been dealt with and
2750 * we reserved our space, thus ret == 0, so we need to just
2751 * drop our space reservation and bail. This can happen the
2752 * first time we come into the fixup worker, or could happen
2753 * while waiting for the ordered extent.
2754 * 2) Our page was already dealt with, but we happened to get an
2755 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2756 * this case we obviously don't have anything to release, but
2757 * because the page was already dealt with we don't want to
2758 * mark the page with an error, so make sure we're resetting
2759 * ret to 0. This is why we have this check _before_ the ret
2760 * check, because we do not want to have a surprise ENOSPC
2761 * when the page was already properly dealt with.
2764 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2765 btrfs_delalloc_release_space(inode, data_reserved,
2766 page_start, PAGE_SIZE,
2774 * We can't mess with the page state unless it is locked, so now that
2775 * it is locked bail if we failed to make our space reservation.
2780 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2782 /* already ordered? We're done */
2783 if (PageOrdered(page))
2786 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2788 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2791 btrfs_start_ordered_extent(ordered, 1);
2792 btrfs_put_ordered_extent(ordered);
2796 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2802 * Everything went as planned, we're now the owner of a dirty page with
2803 * delayed allocation bits set and space reserved for our COW
2806 * The page was dirty when we started, nothing should have cleaned it.
2808 BUG_ON(!PageDirty(page));
2809 free_delalloc_space = false;
2811 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2812 if (free_delalloc_space)
2813 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2815 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2820 * We hit ENOSPC or other errors. Update the mapping and page
2821 * to reflect the errors and clean the page.
2823 mapping_set_error(page->mapping, ret);
2824 end_extent_writepage(page, ret, page_start, page_end);
2825 clear_page_dirty_for_io(page);
2828 ClearPageChecked(page);
2832 extent_changeset_free(data_reserved);
2834 * As a precaution, do a delayed iput in case it would be the last iput
2835 * that could need flushing space. Recursing back to fixup worker would
2838 btrfs_add_delayed_iput(&inode->vfs_inode);
2842 * There are a few paths in the higher layers of the kernel that directly
2843 * set the page dirty bit without asking the filesystem if it is a
2844 * good idea. This causes problems because we want to make sure COW
2845 * properly happens and the data=ordered rules are followed.
2847 * In our case any range that doesn't have the ORDERED bit set
2848 * hasn't been properly setup for IO. We kick off an async process
2849 * to fix it up. The async helper will wait for ordered extents, set
2850 * the delalloc bit and make it safe to write the page.
2852 int btrfs_writepage_cow_fixup(struct page *page)
2854 struct inode *inode = page->mapping->host;
2855 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2856 struct btrfs_writepage_fixup *fixup;
2858 /* This page has ordered extent covering it already */
2859 if (PageOrdered(page))
2863 * PageChecked is set below when we create a fixup worker for this page,
2864 * don't try to create another one if we're already PageChecked()
2866 * The extent_io writepage code will redirty the page if we send back
2869 if (PageChecked(page))
2872 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2877 * We are already holding a reference to this inode from
2878 * write_cache_pages. We need to hold it because the space reservation
2879 * takes place outside of the page lock, and we can't trust
2880 * page->mapping outside of the page lock.
2883 SetPageChecked(page);
2885 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2887 fixup->inode = inode;
2888 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2893 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2894 struct btrfs_inode *inode, u64 file_pos,
2895 struct btrfs_file_extent_item *stack_fi,
2896 const bool update_inode_bytes,
2897 u64 qgroup_reserved)
2899 struct btrfs_root *root = inode->root;
2900 const u64 sectorsize = root->fs_info->sectorsize;
2901 struct btrfs_path *path;
2902 struct extent_buffer *leaf;
2903 struct btrfs_key ins;
2904 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2905 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2906 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2907 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2908 struct btrfs_drop_extents_args drop_args = { 0 };
2911 path = btrfs_alloc_path();
2916 * we may be replacing one extent in the tree with another.
2917 * The new extent is pinned in the extent map, and we don't want
2918 * to drop it from the cache until it is completely in the btree.
2920 * So, tell btrfs_drop_extents to leave this extent in the cache.
2921 * the caller is expected to unpin it and allow it to be merged
2924 drop_args.path = path;
2925 drop_args.start = file_pos;
2926 drop_args.end = file_pos + num_bytes;
2927 drop_args.replace_extent = true;
2928 drop_args.extent_item_size = sizeof(*stack_fi);
2929 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2933 if (!drop_args.extent_inserted) {
2934 ins.objectid = btrfs_ino(inode);
2935 ins.offset = file_pos;
2936 ins.type = BTRFS_EXTENT_DATA_KEY;
2938 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2943 leaf = path->nodes[0];
2944 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2945 write_extent_buffer(leaf, stack_fi,
2946 btrfs_item_ptr_offset(leaf, path->slots[0]),
2947 sizeof(struct btrfs_file_extent_item));
2949 btrfs_mark_buffer_dirty(leaf);
2950 btrfs_release_path(path);
2953 * If we dropped an inline extent here, we know the range where it is
2954 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2955 * number of bytes only for that range containing the inline extent.
2956 * The remaining of the range will be processed when clearning the
2957 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2959 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2960 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2962 inline_size = drop_args.bytes_found - inline_size;
2963 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2964 drop_args.bytes_found -= inline_size;
2965 num_bytes -= sectorsize;
2968 if (update_inode_bytes)
2969 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2971 ins.objectid = disk_bytenr;
2972 ins.offset = disk_num_bytes;
2973 ins.type = BTRFS_EXTENT_ITEM_KEY;
2975 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2979 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2980 file_pos, qgroup_reserved, &ins);
2982 btrfs_free_path(path);
2987 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2990 struct btrfs_block_group *cache;
2992 cache = btrfs_lookup_block_group(fs_info, start);
2995 spin_lock(&cache->lock);
2996 cache->delalloc_bytes -= len;
2997 spin_unlock(&cache->lock);
2999 btrfs_put_block_group(cache);
3002 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
3003 struct btrfs_ordered_extent *oe)
3005 struct btrfs_file_extent_item stack_fi;
3007 bool update_inode_bytes;
3009 memset(&stack_fi, 0, sizeof(stack_fi));
3010 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
3011 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
3012 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
3013 oe->disk_num_bytes);
3014 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
3015 logical_len = oe->truncated_len;
3017 logical_len = oe->num_bytes;
3018 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
3019 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
3020 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3021 /* Encryption and other encoding is reserved and all 0 */
3024 * For delalloc, when completing an ordered extent we update the inode's
3025 * bytes when clearing the range in the inode's io tree, so pass false
3026 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3027 * except if the ordered extent was truncated.
3029 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3030 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3032 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3033 oe->file_offset, &stack_fi,
3034 update_inode_bytes, oe->qgroup_rsv);
3038 * As ordered data IO finishes, this gets called so we can finish
3039 * an ordered extent if the range of bytes in the file it covers are
3042 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3044 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3045 struct btrfs_root *root = inode->root;
3046 struct btrfs_fs_info *fs_info = root->fs_info;
3047 struct btrfs_trans_handle *trans = NULL;
3048 struct extent_io_tree *io_tree = &inode->io_tree;
3049 struct extent_state *cached_state = NULL;
3051 int compress_type = 0;
3053 u64 logical_len = ordered_extent->num_bytes;
3054 bool freespace_inode;
3055 bool truncated = false;
3056 bool clear_reserved_extent = true;
3057 unsigned int clear_bits = EXTENT_DEFRAG;
3059 start = ordered_extent->file_offset;
3060 end = start + ordered_extent->num_bytes - 1;
3062 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3063 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3064 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
3065 clear_bits |= EXTENT_DELALLOC_NEW;
3067 freespace_inode = btrfs_is_free_space_inode(inode);
3069 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3074 if (ordered_extent->bdev)
3075 btrfs_rewrite_logical_zoned(ordered_extent);
3077 btrfs_free_io_failure_record(inode, start, end);
3079 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3081 logical_len = ordered_extent->truncated_len;
3082 /* Truncated the entire extent, don't bother adding */
3087 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3088 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3090 btrfs_inode_safe_disk_i_size_write(inode, 0);
3091 if (freespace_inode)
3092 trans = btrfs_join_transaction_spacecache(root);
3094 trans = btrfs_join_transaction(root);
3095 if (IS_ERR(trans)) {
3096 ret = PTR_ERR(trans);
3100 trans->block_rsv = &inode->block_rsv;
3101 ret = btrfs_update_inode_fallback(trans, root, inode);
3102 if (ret) /* -ENOMEM or corruption */
3103 btrfs_abort_transaction(trans, ret);
3107 clear_bits |= EXTENT_LOCKED;
3108 lock_extent_bits(io_tree, start, end, &cached_state);
3110 if (freespace_inode)
3111 trans = btrfs_join_transaction_spacecache(root);
3113 trans = btrfs_join_transaction(root);
3114 if (IS_ERR(trans)) {
3115 ret = PTR_ERR(trans);
3120 trans->block_rsv = &inode->block_rsv;
3122 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3123 compress_type = ordered_extent->compress_type;
3124 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3125 BUG_ON(compress_type);
3126 ret = btrfs_mark_extent_written(trans, inode,
3127 ordered_extent->file_offset,
3128 ordered_extent->file_offset +
3130 btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3131 ordered_extent->disk_num_bytes);
3133 BUG_ON(root == fs_info->tree_root);
3134 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3136 clear_reserved_extent = false;
3137 btrfs_release_delalloc_bytes(fs_info,
3138 ordered_extent->disk_bytenr,
3139 ordered_extent->disk_num_bytes);
3142 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3143 ordered_extent->num_bytes, trans->transid);
3145 btrfs_abort_transaction(trans, ret);
3149 ret = add_pending_csums(trans, &ordered_extent->list);
3151 btrfs_abort_transaction(trans, ret);
3156 * If this is a new delalloc range, clear its new delalloc flag to
3157 * update the inode's number of bytes. This needs to be done first
3158 * before updating the inode item.
3160 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3161 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3162 clear_extent_bit(&inode->io_tree, start, end,
3163 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3164 0, 0, &cached_state);
3166 btrfs_inode_safe_disk_i_size_write(inode, 0);
3167 ret = btrfs_update_inode_fallback(trans, root, inode);
3168 if (ret) { /* -ENOMEM or corruption */
3169 btrfs_abort_transaction(trans, ret);
3174 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3175 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
3179 btrfs_end_transaction(trans);
3181 if (ret || truncated) {
3182 u64 unwritten_start = start;
3185 * If we failed to finish this ordered extent for any reason we
3186 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3187 * extent, and mark the inode with the error if it wasn't
3188 * already set. Any error during writeback would have already
3189 * set the mapping error, so we need to set it if we're the ones
3190 * marking this ordered extent as failed.
3192 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3193 &ordered_extent->flags))
3194 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3197 unwritten_start += logical_len;
3198 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3200 /* Drop the cache for the part of the extent we didn't write. */
3201 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3204 * If the ordered extent had an IOERR or something else went
3205 * wrong we need to return the space for this ordered extent
3206 * back to the allocator. We only free the extent in the
3207 * truncated case if we didn't write out the extent at all.
3209 * If we made it past insert_reserved_file_extent before we
3210 * errored out then we don't need to do this as the accounting
3211 * has already been done.
3213 if ((ret || !logical_len) &&
3214 clear_reserved_extent &&
3215 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3216 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3218 * Discard the range before returning it back to the
3221 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3222 btrfs_discard_extent(fs_info,
3223 ordered_extent->disk_bytenr,
3224 ordered_extent->disk_num_bytes,
3226 btrfs_free_reserved_extent(fs_info,
3227 ordered_extent->disk_bytenr,
3228 ordered_extent->disk_num_bytes, 1);
3233 * This needs to be done to make sure anybody waiting knows we are done
3234 * updating everything for this ordered extent.
3236 btrfs_remove_ordered_extent(inode, ordered_extent);
3239 btrfs_put_ordered_extent(ordered_extent);
3240 /* once for the tree */
3241 btrfs_put_ordered_extent(ordered_extent);
3246 static void finish_ordered_fn(struct btrfs_work *work)
3248 struct btrfs_ordered_extent *ordered_extent;
3249 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3250 btrfs_finish_ordered_io(ordered_extent);
3253 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3254 struct page *page, u64 start,
3255 u64 end, bool uptodate)
3257 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3259 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start,
3260 finish_ordered_fn, uptodate);
3264 * check_data_csum - verify checksum of one sector of uncompressed data
3266 * @io_bio: btrfs_io_bio which contains the csum
3267 * @bio_offset: offset to the beginning of the bio (in bytes)
3268 * @page: page where is the data to be verified
3269 * @pgoff: offset inside the page
3270 * @start: logical offset in the file
3272 * The length of such check is always one sector size.
3274 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
3275 u32 bio_offset, struct page *page, u32 pgoff,
3278 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3279 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3281 u32 len = fs_info->sectorsize;
3282 const u32 csum_size = fs_info->csum_size;
3283 unsigned int offset_sectors;
3285 u8 csum[BTRFS_CSUM_SIZE];
3287 ASSERT(pgoff + len <= PAGE_SIZE);
3289 offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3290 csum_expected = ((u8 *)io_bio->csum) + offset_sectors * csum_size;
3292 kaddr = kmap_atomic(page);
3293 shash->tfm = fs_info->csum_shash;
3295 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3297 if (memcmp(csum, csum_expected, csum_size))
3300 kunmap_atomic(kaddr);
3303 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3304 io_bio->mirror_num);
3306 btrfs_dev_stat_inc_and_print(io_bio->device,
3307 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3308 memset(kaddr + pgoff, 1, len);
3309 flush_dcache_page(page);
3310 kunmap_atomic(kaddr);
3315 * When reads are done, we need to check csums to verify the data is correct.
3316 * if there's a match, we allow the bio to finish. If not, the code in
3317 * extent_io.c will try to find good copies for us.
3319 * @bio_offset: offset to the beginning of the bio (in bytes)
3320 * @start: file offset of the range start
3321 * @end: file offset of the range end (inclusive)
3323 * Return a bitmap where bit set means a csum mismatch, and bit not set means
3326 unsigned int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u32 bio_offset,
3327 struct page *page, u64 start, u64 end)
3329 struct inode *inode = page->mapping->host;
3330 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3331 struct btrfs_root *root = BTRFS_I(inode)->root;
3332 const u32 sectorsize = root->fs_info->sectorsize;
3334 unsigned int result = 0;
3336 if (PageChecked(page)) {
3337 ClearPageChecked(page);
3342 * For subpage case, above PageChecked is not safe as it's not subpage
3344 * But for now only cow fixup and compressed read utilize PageChecked
3345 * flag, while in this context we can easily use io_bio->csum to
3346 * determine if we really need to do csum verification.
3348 * So for now, just exit if io_bio->csum is NULL, as it means it's
3349 * compressed read, and its compressed data csum has already been
3352 if (io_bio->csum == NULL)
3355 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3358 if (!root->fs_info->csum_root)
3361 ASSERT(page_offset(page) <= start &&
3362 end <= page_offset(page) + PAGE_SIZE - 1);
3363 for (pg_off = offset_in_page(start);
3364 pg_off < offset_in_page(end);
3365 pg_off += sectorsize, bio_offset += sectorsize) {
3366 u64 file_offset = pg_off + page_offset(page);
3369 if (btrfs_is_data_reloc_root(root) &&
3370 test_range_bit(io_tree, file_offset,
3371 file_offset + sectorsize - 1,
3372 EXTENT_NODATASUM, 1, NULL)) {
3373 /* Skip the range without csum for data reloc inode */
3374 clear_extent_bits(io_tree, file_offset,
3375 file_offset + sectorsize - 1,
3379 ret = check_data_csum(inode, io_bio, bio_offset, page, pg_off,
3380 page_offset(page) + pg_off);
3382 const int nr_bit = (pg_off - offset_in_page(start)) >>
3383 root->fs_info->sectorsize_bits;
3385 result |= (1U << nr_bit);
3392 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3394 * @inode: The inode we want to perform iput on
3396 * This function uses the generic vfs_inode::i_count to track whether we should
3397 * just decrement it (in case it's > 1) or if this is the last iput then link
3398 * the inode to the delayed iput machinery. Delayed iputs are processed at
3399 * transaction commit time/superblock commit/cleaner kthread.
3401 void btrfs_add_delayed_iput(struct inode *inode)
3403 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3404 struct btrfs_inode *binode = BTRFS_I(inode);
3406 if (atomic_add_unless(&inode->i_count, -1, 1))
3409 atomic_inc(&fs_info->nr_delayed_iputs);
3410 spin_lock(&fs_info->delayed_iput_lock);
3411 ASSERT(list_empty(&binode->delayed_iput));
3412 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3413 spin_unlock(&fs_info->delayed_iput_lock);
3414 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3415 wake_up_process(fs_info->cleaner_kthread);
3418 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3419 struct btrfs_inode *inode)
3421 list_del_init(&inode->delayed_iput);
3422 spin_unlock(&fs_info->delayed_iput_lock);
3423 iput(&inode->vfs_inode);
3424 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3425 wake_up(&fs_info->delayed_iputs_wait);
3426 spin_lock(&fs_info->delayed_iput_lock);
3429 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3430 struct btrfs_inode *inode)
3432 if (!list_empty(&inode->delayed_iput)) {
3433 spin_lock(&fs_info->delayed_iput_lock);
3434 if (!list_empty(&inode->delayed_iput))
3435 run_delayed_iput_locked(fs_info, inode);
3436 spin_unlock(&fs_info->delayed_iput_lock);
3440 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3443 spin_lock(&fs_info->delayed_iput_lock);
3444 while (!list_empty(&fs_info->delayed_iputs)) {
3445 struct btrfs_inode *inode;
3447 inode = list_first_entry(&fs_info->delayed_iputs,
3448 struct btrfs_inode, delayed_iput);
3449 run_delayed_iput_locked(fs_info, inode);
3450 cond_resched_lock(&fs_info->delayed_iput_lock);
3452 spin_unlock(&fs_info->delayed_iput_lock);
3456 * Wait for flushing all delayed iputs
3458 * @fs_info: the filesystem
3460 * This will wait on any delayed iputs that are currently running with KILLABLE
3461 * set. Once they are all done running we will return, unless we are killed in
3462 * which case we return EINTR. This helps in user operations like fallocate etc
3463 * that might get blocked on the iputs.
3465 * Return EINTR if we were killed, 0 if nothing's pending
3467 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3469 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3470 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3477 * This creates an orphan entry for the given inode in case something goes wrong
3478 * in the middle of an unlink.
3480 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3481 struct btrfs_inode *inode)
3485 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3486 if (ret && ret != -EEXIST) {
3487 btrfs_abort_transaction(trans, ret);
3495 * We have done the delete so we can go ahead and remove the orphan item for
3496 * this particular inode.
3498 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3499 struct btrfs_inode *inode)
3501 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3505 * this cleans up any orphans that may be left on the list from the last use
3508 int btrfs_orphan_cleanup(struct btrfs_root *root)
3510 struct btrfs_fs_info *fs_info = root->fs_info;
3511 struct btrfs_path *path;
3512 struct extent_buffer *leaf;
3513 struct btrfs_key key, found_key;
3514 struct btrfs_trans_handle *trans;
3515 struct inode *inode;
3516 u64 last_objectid = 0;
3517 int ret = 0, nr_unlink = 0;
3519 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3522 path = btrfs_alloc_path();
3527 path->reada = READA_BACK;
3529 key.objectid = BTRFS_ORPHAN_OBJECTID;
3530 key.type = BTRFS_ORPHAN_ITEM_KEY;
3531 key.offset = (u64)-1;
3534 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3539 * if ret == 0 means we found what we were searching for, which
3540 * is weird, but possible, so only screw with path if we didn't
3541 * find the key and see if we have stuff that matches
3545 if (path->slots[0] == 0)
3550 /* pull out the item */
3551 leaf = path->nodes[0];
3552 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3554 /* make sure the item matches what we want */
3555 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3557 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3560 /* release the path since we're done with it */
3561 btrfs_release_path(path);
3564 * this is where we are basically btrfs_lookup, without the
3565 * crossing root thing. we store the inode number in the
3566 * offset of the orphan item.
3569 if (found_key.offset == last_objectid) {
3571 "Error removing orphan entry, stopping orphan cleanup");
3576 last_objectid = found_key.offset;
3578 found_key.objectid = found_key.offset;
3579 found_key.type = BTRFS_INODE_ITEM_KEY;
3580 found_key.offset = 0;
3581 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3582 ret = PTR_ERR_OR_ZERO(inode);
3583 if (ret && ret != -ENOENT)
3586 if (ret == -ENOENT && root == fs_info->tree_root) {
3587 struct btrfs_root *dead_root;
3588 int is_dead_root = 0;
3591 * This is an orphan in the tree root. Currently these
3592 * could come from 2 sources:
3593 * a) a root (snapshot/subvolume) deletion in progress
3594 * b) a free space cache inode
3595 * We need to distinguish those two, as the orphan item
3596 * for a root must not get deleted before the deletion
3597 * of the snapshot/subvolume's tree completes.
3599 * btrfs_find_orphan_roots() ran before us, which has
3600 * found all deleted roots and loaded them into
3601 * fs_info->fs_roots_radix. So here we can find if an
3602 * orphan item corresponds to a deleted root by looking
3603 * up the root from that radix tree.
3606 spin_lock(&fs_info->fs_roots_radix_lock);
3607 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3608 (unsigned long)found_key.objectid);
3609 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3611 spin_unlock(&fs_info->fs_roots_radix_lock);
3614 /* prevent this orphan from being found again */
3615 key.offset = found_key.objectid - 1;
3622 * If we have an inode with links, there are a couple of
3625 * 1. We were halfway through creating fsverity metadata for the
3626 * file. In that case, the orphan item represents incomplete
3627 * fsverity metadata which must be cleaned up with
3628 * btrfs_drop_verity_items and deleting the orphan item.
3630 * 2. Old kernels (before v3.12) used to create an
3631 * orphan item for truncate indicating that there were possibly
3632 * extent items past i_size that needed to be deleted. In v3.12,
3633 * truncate was changed to update i_size in sync with the extent
3634 * items, but the (useless) orphan item was still created. Since
3635 * v4.18, we don't create the orphan item for truncate at all.
3637 * So, this item could mean that we need to do a truncate, but
3638 * only if this filesystem was last used on a pre-v3.12 kernel
3639 * and was not cleanly unmounted. The odds of that are quite
3640 * slim, and it's a pain to do the truncate now, so just delete
3643 * It's also possible that this orphan item was supposed to be
3644 * deleted but wasn't. The inode number may have been reused,
3645 * but either way, we can delete the orphan item.
3647 if (ret == -ENOENT || inode->i_nlink) {
3649 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3654 trans = btrfs_start_transaction(root, 1);
3655 if (IS_ERR(trans)) {
3656 ret = PTR_ERR(trans);
3659 btrfs_debug(fs_info, "auto deleting %Lu",
3660 found_key.objectid);
3661 ret = btrfs_del_orphan_item(trans, root,
3662 found_key.objectid);
3663 btrfs_end_transaction(trans);
3671 /* this will do delete_inode and everything for us */
3674 /* release the path since we're done with it */
3675 btrfs_release_path(path);
3677 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3679 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3680 trans = btrfs_join_transaction(root);
3682 btrfs_end_transaction(trans);
3686 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3690 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3691 btrfs_free_path(path);
3696 * very simple check to peek ahead in the leaf looking for xattrs. If we
3697 * don't find any xattrs, we know there can't be any acls.
3699 * slot is the slot the inode is in, objectid is the objectid of the inode
3701 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3702 int slot, u64 objectid,
3703 int *first_xattr_slot)
3705 u32 nritems = btrfs_header_nritems(leaf);
3706 struct btrfs_key found_key;
3707 static u64 xattr_access = 0;
3708 static u64 xattr_default = 0;
3711 if (!xattr_access) {
3712 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3713 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3714 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3715 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3719 *first_xattr_slot = -1;
3720 while (slot < nritems) {
3721 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3723 /* we found a different objectid, there must not be acls */
3724 if (found_key.objectid != objectid)
3727 /* we found an xattr, assume we've got an acl */
3728 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3729 if (*first_xattr_slot == -1)
3730 *first_xattr_slot = slot;
3731 if (found_key.offset == xattr_access ||
3732 found_key.offset == xattr_default)
3737 * we found a key greater than an xattr key, there can't
3738 * be any acls later on
3740 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3747 * it goes inode, inode backrefs, xattrs, extents,
3748 * so if there are a ton of hard links to an inode there can
3749 * be a lot of backrefs. Don't waste time searching too hard,
3750 * this is just an optimization
3755 /* we hit the end of the leaf before we found an xattr or
3756 * something larger than an xattr. We have to assume the inode
3759 if (*first_xattr_slot == -1)
3760 *first_xattr_slot = slot;
3765 * read an inode from the btree into the in-memory inode
3767 static int btrfs_read_locked_inode(struct inode *inode,
3768 struct btrfs_path *in_path)
3770 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3771 struct btrfs_path *path = in_path;
3772 struct extent_buffer *leaf;
3773 struct btrfs_inode_item *inode_item;
3774 struct btrfs_root *root = BTRFS_I(inode)->root;
3775 struct btrfs_key location;
3780 bool filled = false;
3781 int first_xattr_slot;
3783 ret = btrfs_fill_inode(inode, &rdev);
3788 path = btrfs_alloc_path();
3793 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3795 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3797 if (path != in_path)
3798 btrfs_free_path(path);
3802 leaf = path->nodes[0];
3807 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3808 struct btrfs_inode_item);
3809 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3810 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3811 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3812 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3813 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3814 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3815 round_up(i_size_read(inode), fs_info->sectorsize));
3817 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3818 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3820 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3821 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3823 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3824 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3826 BTRFS_I(inode)->i_otime.tv_sec =
3827 btrfs_timespec_sec(leaf, &inode_item->otime);
3828 BTRFS_I(inode)->i_otime.tv_nsec =
3829 btrfs_timespec_nsec(leaf, &inode_item->otime);
3831 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3832 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3833 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3835 inode_set_iversion_queried(inode,
3836 btrfs_inode_sequence(leaf, inode_item));
3837 inode->i_generation = BTRFS_I(inode)->generation;
3839 rdev = btrfs_inode_rdev(leaf, inode_item);
3841 BTRFS_I(inode)->index_cnt = (u64)-1;
3842 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
3843 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
3847 * If we were modified in the current generation and evicted from memory
3848 * and then re-read we need to do a full sync since we don't have any
3849 * idea about which extents were modified before we were evicted from
3852 * This is required for both inode re-read from disk and delayed inode
3853 * in delayed_nodes_tree.
3855 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3856 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3857 &BTRFS_I(inode)->runtime_flags);
3860 * We don't persist the id of the transaction where an unlink operation
3861 * against the inode was last made. So here we assume the inode might
3862 * have been evicted, and therefore the exact value of last_unlink_trans
3863 * lost, and set it to last_trans to avoid metadata inconsistencies
3864 * between the inode and its parent if the inode is fsync'ed and the log
3865 * replayed. For example, in the scenario:
3868 * ln mydir/foo mydir/bar
3871 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3872 * xfs_io -c fsync mydir/foo
3874 * mount fs, triggers fsync log replay
3876 * We must make sure that when we fsync our inode foo we also log its
3877 * parent inode, otherwise after log replay the parent still has the
3878 * dentry with the "bar" name but our inode foo has a link count of 1
3879 * and doesn't have an inode ref with the name "bar" anymore.
3881 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3882 * but it guarantees correctness at the expense of occasional full
3883 * transaction commits on fsync if our inode is a directory, or if our
3884 * inode is not a directory, logging its parent unnecessarily.
3886 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3889 * Same logic as for last_unlink_trans. We don't persist the generation
3890 * of the last transaction where this inode was used for a reflink
3891 * operation, so after eviction and reloading the inode we must be
3892 * pessimistic and assume the last transaction that modified the inode.
3894 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3897 if (inode->i_nlink != 1 ||
3898 path->slots[0] >= btrfs_header_nritems(leaf))
3901 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3902 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3905 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3906 if (location.type == BTRFS_INODE_REF_KEY) {
3907 struct btrfs_inode_ref *ref;
3909 ref = (struct btrfs_inode_ref *)ptr;
3910 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3911 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3912 struct btrfs_inode_extref *extref;
3914 extref = (struct btrfs_inode_extref *)ptr;
3915 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3920 * try to precache a NULL acl entry for files that don't have
3921 * any xattrs or acls
3923 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3924 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3925 if (first_xattr_slot != -1) {
3926 path->slots[0] = first_xattr_slot;
3927 ret = btrfs_load_inode_props(inode, path);
3930 "error loading props for ino %llu (root %llu): %d",
3931 btrfs_ino(BTRFS_I(inode)),
3932 root->root_key.objectid, ret);
3934 if (path != in_path)
3935 btrfs_free_path(path);
3938 cache_no_acl(inode);
3940 switch (inode->i_mode & S_IFMT) {
3942 inode->i_mapping->a_ops = &btrfs_aops;
3943 inode->i_fop = &btrfs_file_operations;
3944 inode->i_op = &btrfs_file_inode_operations;
3947 inode->i_fop = &btrfs_dir_file_operations;
3948 inode->i_op = &btrfs_dir_inode_operations;
3951 inode->i_op = &btrfs_symlink_inode_operations;
3952 inode_nohighmem(inode);
3953 inode->i_mapping->a_ops = &btrfs_aops;
3956 inode->i_op = &btrfs_special_inode_operations;
3957 init_special_inode(inode, inode->i_mode, rdev);
3961 btrfs_sync_inode_flags_to_i_flags(inode);
3966 * given a leaf and an inode, copy the inode fields into the leaf
3968 static void fill_inode_item(struct btrfs_trans_handle *trans,
3969 struct extent_buffer *leaf,
3970 struct btrfs_inode_item *item,
3971 struct inode *inode)
3973 struct btrfs_map_token token;
3976 btrfs_init_map_token(&token, leaf);
3978 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3979 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3980 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3981 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3982 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3984 btrfs_set_token_timespec_sec(&token, &item->atime,
3985 inode->i_atime.tv_sec);
3986 btrfs_set_token_timespec_nsec(&token, &item->atime,
3987 inode->i_atime.tv_nsec);
3989 btrfs_set_token_timespec_sec(&token, &item->mtime,
3990 inode->i_mtime.tv_sec);
3991 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3992 inode->i_mtime.tv_nsec);
3994 btrfs_set_token_timespec_sec(&token, &item->ctime,
3995 inode->i_ctime.tv_sec);
3996 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3997 inode->i_ctime.tv_nsec);
3999 btrfs_set_token_timespec_sec(&token, &item->otime,
4000 BTRFS_I(inode)->i_otime.tv_sec);
4001 btrfs_set_token_timespec_nsec(&token, &item->otime,
4002 BTRFS_I(inode)->i_otime.tv_nsec);
4004 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
4005 btrfs_set_token_inode_generation(&token, item,
4006 BTRFS_I(inode)->generation);
4007 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4008 btrfs_set_token_inode_transid(&token, item, trans->transid);
4009 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4010 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4011 BTRFS_I(inode)->ro_flags);
4012 btrfs_set_token_inode_flags(&token, item, flags);
4013 btrfs_set_token_inode_block_group(&token, item, 0);
4017 * copy everything in the in-memory inode into the btree.
4019 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4020 struct btrfs_root *root,
4021 struct btrfs_inode *inode)
4023 struct btrfs_inode_item *inode_item;
4024 struct btrfs_path *path;
4025 struct extent_buffer *leaf;
4028 path = btrfs_alloc_path();
4032 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4039 leaf = path->nodes[0];
4040 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4041 struct btrfs_inode_item);
4043 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4044 btrfs_mark_buffer_dirty(leaf);
4045 btrfs_set_inode_last_trans(trans, inode);
4048 btrfs_free_path(path);
4053 * copy everything in the in-memory inode into the btree.
4055 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4056 struct btrfs_root *root,
4057 struct btrfs_inode *inode)
4059 struct btrfs_fs_info *fs_info = root->fs_info;
4063 * If the inode is a free space inode, we can deadlock during commit
4064 * if we put it into the delayed code.
4066 * The data relocation inode should also be directly updated
4069 if (!btrfs_is_free_space_inode(inode)
4070 && !btrfs_is_data_reloc_root(root)
4071 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4072 btrfs_update_root_times(trans, root);
4074 ret = btrfs_delayed_update_inode(trans, root, inode);
4076 btrfs_set_inode_last_trans(trans, inode);
4080 return btrfs_update_inode_item(trans, root, inode);
4083 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4084 struct btrfs_root *root, struct btrfs_inode *inode)
4088 ret = btrfs_update_inode(trans, root, inode);
4090 return btrfs_update_inode_item(trans, root, inode);
4095 * unlink helper that gets used here in inode.c and in the tree logging
4096 * recovery code. It remove a link in a directory with a given name, and
4097 * also drops the back refs in the inode to the directory
4099 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4100 struct btrfs_inode *dir,
4101 struct btrfs_inode *inode,
4102 const char *name, int name_len)
4104 struct btrfs_root *root = dir->root;
4105 struct btrfs_fs_info *fs_info = root->fs_info;
4106 struct btrfs_path *path;
4108 struct btrfs_dir_item *di;
4110 u64 ino = btrfs_ino(inode);
4111 u64 dir_ino = btrfs_ino(dir);
4113 path = btrfs_alloc_path();
4119 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4120 name, name_len, -1);
4121 if (IS_ERR_OR_NULL(di)) {
4122 ret = di ? PTR_ERR(di) : -ENOENT;
4125 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4128 btrfs_release_path(path);
4131 * If we don't have dir index, we have to get it by looking up
4132 * the inode ref, since we get the inode ref, remove it directly,
4133 * it is unnecessary to do delayed deletion.
4135 * But if we have dir index, needn't search inode ref to get it.
4136 * Since the inode ref is close to the inode item, it is better
4137 * that we delay to delete it, and just do this deletion when
4138 * we update the inode item.
4140 if (inode->dir_index) {
4141 ret = btrfs_delayed_delete_inode_ref(inode);
4143 index = inode->dir_index;
4148 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4152 "failed to delete reference to %.*s, inode %llu parent %llu",
4153 name_len, name, ino, dir_ino);
4154 btrfs_abort_transaction(trans, ret);
4158 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4160 btrfs_abort_transaction(trans, ret);
4164 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4166 if (ret != 0 && ret != -ENOENT) {
4167 btrfs_abort_transaction(trans, ret);
4171 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4176 btrfs_abort_transaction(trans, ret);
4179 * If we have a pending delayed iput we could end up with the final iput
4180 * being run in btrfs-cleaner context. If we have enough of these built
4181 * up we can end up burning a lot of time in btrfs-cleaner without any
4182 * way to throttle the unlinks. Since we're currently holding a ref on
4183 * the inode we can run the delayed iput here without any issues as the
4184 * final iput won't be done until after we drop the ref we're currently
4187 btrfs_run_delayed_iput(fs_info, inode);
4189 btrfs_free_path(path);
4193 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4194 inode_inc_iversion(&inode->vfs_inode);
4195 inode_inc_iversion(&dir->vfs_inode);
4196 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4197 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4198 ret = btrfs_update_inode(trans, root, dir);
4203 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4204 struct btrfs_inode *dir, struct btrfs_inode *inode,
4205 const char *name, int name_len)
4208 ret = __btrfs_unlink_inode(trans, dir, inode, name, name_len);
4210 drop_nlink(&inode->vfs_inode);
4211 ret = btrfs_update_inode(trans, inode->root, inode);
4217 * helper to start transaction for unlink and rmdir.
4219 * unlink and rmdir are special in btrfs, they do not always free space, so
4220 * if we cannot make our reservations the normal way try and see if there is
4221 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4222 * allow the unlink to occur.
4224 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4226 struct btrfs_root *root = BTRFS_I(dir)->root;
4229 * 1 for the possible orphan item
4230 * 1 for the dir item
4231 * 1 for the dir index
4232 * 1 for the inode ref
4235 return btrfs_start_transaction_fallback_global_rsv(root, 5);
4238 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4240 struct btrfs_trans_handle *trans;
4241 struct inode *inode = d_inode(dentry);
4244 trans = __unlink_start_trans(dir);
4246 return PTR_ERR(trans);
4248 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4251 ret = btrfs_unlink_inode(trans, BTRFS_I(dir),
4252 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4253 dentry->d_name.len);
4257 if (inode->i_nlink == 0) {
4258 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4264 btrfs_end_transaction(trans);
4265 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4269 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4270 struct inode *dir, struct dentry *dentry)
4272 struct btrfs_root *root = BTRFS_I(dir)->root;
4273 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4274 struct btrfs_path *path;
4275 struct extent_buffer *leaf;
4276 struct btrfs_dir_item *di;
4277 struct btrfs_key key;
4278 const char *name = dentry->d_name.name;
4279 int name_len = dentry->d_name.len;
4283 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4285 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4286 objectid = inode->root->root_key.objectid;
4287 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4288 objectid = inode->location.objectid;
4294 path = btrfs_alloc_path();
4298 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4299 name, name_len, -1);
4300 if (IS_ERR_OR_NULL(di)) {
4301 ret = di ? PTR_ERR(di) : -ENOENT;
4305 leaf = path->nodes[0];
4306 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4307 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4308 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4310 btrfs_abort_transaction(trans, ret);
4313 btrfs_release_path(path);
4316 * This is a placeholder inode for a subvolume we didn't have a
4317 * reference to at the time of the snapshot creation. In the meantime
4318 * we could have renamed the real subvol link into our snapshot, so
4319 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4320 * Instead simply lookup the dir_index_item for this entry so we can
4321 * remove it. Otherwise we know we have a ref to the root and we can
4322 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4324 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4325 di = btrfs_search_dir_index_item(root, path, dir_ino,
4327 if (IS_ERR_OR_NULL(di)) {
4332 btrfs_abort_transaction(trans, ret);
4336 leaf = path->nodes[0];
4337 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4339 btrfs_release_path(path);
4341 ret = btrfs_del_root_ref(trans, objectid,
4342 root->root_key.objectid, dir_ino,
4343 &index, name, name_len);
4345 btrfs_abort_transaction(trans, ret);
4350 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4352 btrfs_abort_transaction(trans, ret);
4356 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4357 inode_inc_iversion(dir);
4358 dir->i_mtime = dir->i_ctime = current_time(dir);
4359 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4361 btrfs_abort_transaction(trans, ret);
4363 btrfs_free_path(path);
4368 * Helper to check if the subvolume references other subvolumes or if it's
4371 static noinline int may_destroy_subvol(struct btrfs_root *root)
4373 struct btrfs_fs_info *fs_info = root->fs_info;
4374 struct btrfs_path *path;
4375 struct btrfs_dir_item *di;
4376 struct btrfs_key key;
4380 path = btrfs_alloc_path();
4384 /* Make sure this root isn't set as the default subvol */
4385 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4386 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4387 dir_id, "default", 7, 0);
4388 if (di && !IS_ERR(di)) {
4389 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4390 if (key.objectid == root->root_key.objectid) {
4393 "deleting default subvolume %llu is not allowed",
4397 btrfs_release_path(path);
4400 key.objectid = root->root_key.objectid;
4401 key.type = BTRFS_ROOT_REF_KEY;
4402 key.offset = (u64)-1;
4404 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4410 if (path->slots[0] > 0) {
4412 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4413 if (key.objectid == root->root_key.objectid &&
4414 key.type == BTRFS_ROOT_REF_KEY)
4418 btrfs_free_path(path);
4422 /* Delete all dentries for inodes belonging to the root */
4423 static void btrfs_prune_dentries(struct btrfs_root *root)
4425 struct btrfs_fs_info *fs_info = root->fs_info;
4426 struct rb_node *node;
4427 struct rb_node *prev;
4428 struct btrfs_inode *entry;
4429 struct inode *inode;
4432 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4433 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4435 spin_lock(&root->inode_lock);
4437 node = root->inode_tree.rb_node;
4441 entry = rb_entry(node, struct btrfs_inode, rb_node);
4443 if (objectid < btrfs_ino(entry))
4444 node = node->rb_left;
4445 else if (objectid > btrfs_ino(entry))
4446 node = node->rb_right;
4452 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4453 if (objectid <= btrfs_ino(entry)) {
4457 prev = rb_next(prev);
4461 entry = rb_entry(node, struct btrfs_inode, rb_node);
4462 objectid = btrfs_ino(entry) + 1;
4463 inode = igrab(&entry->vfs_inode);
4465 spin_unlock(&root->inode_lock);
4466 if (atomic_read(&inode->i_count) > 1)
4467 d_prune_aliases(inode);
4469 * btrfs_drop_inode will have it removed from the inode
4470 * cache when its usage count hits zero.
4474 spin_lock(&root->inode_lock);
4478 if (cond_resched_lock(&root->inode_lock))
4481 node = rb_next(node);
4483 spin_unlock(&root->inode_lock);
4486 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4488 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4489 struct btrfs_root *root = BTRFS_I(dir)->root;
4490 struct inode *inode = d_inode(dentry);
4491 struct btrfs_root *dest = BTRFS_I(inode)->root;
4492 struct btrfs_trans_handle *trans;
4493 struct btrfs_block_rsv block_rsv;
4498 * Don't allow to delete a subvolume with send in progress. This is
4499 * inside the inode lock so the error handling that has to drop the bit
4500 * again is not run concurrently.
4502 spin_lock(&dest->root_item_lock);
4503 if (dest->send_in_progress) {
4504 spin_unlock(&dest->root_item_lock);
4506 "attempt to delete subvolume %llu during send",
4507 dest->root_key.objectid);
4510 if (atomic_read(&dest->nr_swapfiles)) {
4511 spin_unlock(&dest->root_item_lock);
4513 "attempt to delete subvolume %llu with active swapfile",
4514 root->root_key.objectid);
4517 root_flags = btrfs_root_flags(&dest->root_item);
4518 btrfs_set_root_flags(&dest->root_item,
4519 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4520 spin_unlock(&dest->root_item_lock);
4522 down_write(&fs_info->subvol_sem);
4524 ret = may_destroy_subvol(dest);
4528 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4530 * One for dir inode,
4531 * two for dir entries,
4532 * two for root ref/backref.
4534 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4538 trans = btrfs_start_transaction(root, 0);
4539 if (IS_ERR(trans)) {
4540 ret = PTR_ERR(trans);
4543 trans->block_rsv = &block_rsv;
4544 trans->bytes_reserved = block_rsv.size;
4546 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4548 ret = btrfs_unlink_subvol(trans, dir, dentry);
4550 btrfs_abort_transaction(trans, ret);
4554 ret = btrfs_record_root_in_trans(trans, dest);
4556 btrfs_abort_transaction(trans, ret);
4560 memset(&dest->root_item.drop_progress, 0,
4561 sizeof(dest->root_item.drop_progress));
4562 btrfs_set_root_drop_level(&dest->root_item, 0);
4563 btrfs_set_root_refs(&dest->root_item, 0);
4565 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4566 ret = btrfs_insert_orphan_item(trans,
4568 dest->root_key.objectid);
4570 btrfs_abort_transaction(trans, ret);
4575 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4576 BTRFS_UUID_KEY_SUBVOL,
4577 dest->root_key.objectid);
4578 if (ret && ret != -ENOENT) {
4579 btrfs_abort_transaction(trans, ret);
4582 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4583 ret = btrfs_uuid_tree_remove(trans,
4584 dest->root_item.received_uuid,
4585 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4586 dest->root_key.objectid);
4587 if (ret && ret != -ENOENT) {
4588 btrfs_abort_transaction(trans, ret);
4593 free_anon_bdev(dest->anon_dev);
4596 trans->block_rsv = NULL;
4597 trans->bytes_reserved = 0;
4598 ret = btrfs_end_transaction(trans);
4599 inode->i_flags |= S_DEAD;
4601 btrfs_subvolume_release_metadata(root, &block_rsv);
4603 up_write(&fs_info->subvol_sem);
4605 spin_lock(&dest->root_item_lock);
4606 root_flags = btrfs_root_flags(&dest->root_item);
4607 btrfs_set_root_flags(&dest->root_item,
4608 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4609 spin_unlock(&dest->root_item_lock);
4611 d_invalidate(dentry);
4612 btrfs_prune_dentries(dest);
4613 ASSERT(dest->send_in_progress == 0);
4619 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4621 struct inode *inode = d_inode(dentry);
4623 struct btrfs_trans_handle *trans;
4624 u64 last_unlink_trans;
4626 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4628 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4629 return btrfs_delete_subvolume(dir, dentry);
4631 trans = __unlink_start_trans(dir);
4633 return PTR_ERR(trans);
4635 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4636 err = btrfs_unlink_subvol(trans, dir, dentry);
4640 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4644 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4646 /* now the directory is empty */
4647 err = btrfs_unlink_inode(trans, BTRFS_I(dir),
4648 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4649 dentry->d_name.len);
4651 btrfs_i_size_write(BTRFS_I(inode), 0);
4653 * Propagate the last_unlink_trans value of the deleted dir to
4654 * its parent directory. This is to prevent an unrecoverable
4655 * log tree in the case we do something like this:
4657 * 2) create snapshot under dir foo
4658 * 3) delete the snapshot
4661 * 6) fsync foo or some file inside foo
4663 if (last_unlink_trans >= trans->transid)
4664 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4667 btrfs_end_transaction(trans);
4668 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4674 * Return this if we need to call truncate_block for the last bit of the
4677 #define NEED_TRUNCATE_BLOCK 1
4680 * Remove inode items from a given root.
4682 * @trans: A transaction handle.
4683 * @root: The root from which to remove items.
4684 * @inode: The inode whose items we want to remove.
4685 * @new_size: The new i_size for the inode. This is only applicable when
4686 * @min_type is BTRFS_EXTENT_DATA_KEY, must be 0 otherwise.
4687 * @min_type: The minimum key type to remove. All keys with a type
4688 * greater than this value are removed and all keys with
4689 * this type are removed only if their offset is >= @new_size.
4690 * @extents_found: Output parameter that will contain the number of file
4691 * extent items that were removed or adjusted to the new
4692 * inode i_size. The caller is responsible for initializing
4693 * the counter. Also, it can be NULL if the caller does not
4694 * need this counter.
4696 * Remove all keys associated with the inode from the given root that have a key
4697 * with a type greater than or equals to @min_type. When @min_type has a value of
4698 * BTRFS_EXTENT_DATA_KEY, only remove file extent items that have an offset value
4699 * greater than or equals to @new_size. If a file extent item that starts before
4700 * @new_size and ends after it is found, its length is adjusted.
4702 * Returns: 0 on success, < 0 on error and NEED_TRUNCATE_BLOCK when @min_type is
4703 * BTRFS_EXTENT_DATA_KEY and the caller must truncate the last block.
4705 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4706 struct btrfs_root *root,
4707 struct btrfs_inode *inode,
4708 u64 new_size, u32 min_type,
4711 struct btrfs_fs_info *fs_info = root->fs_info;
4712 struct btrfs_path *path;
4713 struct extent_buffer *leaf;
4714 struct btrfs_file_extent_item *fi;
4715 struct btrfs_key key;
4716 struct btrfs_key found_key;
4717 u64 extent_start = 0;
4718 u64 extent_num_bytes = 0;
4719 u64 extent_offset = 0;
4721 u64 last_size = new_size;
4722 u32 found_type = (u8)-1;
4725 int pending_del_nr = 0;
4726 int pending_del_slot = 0;
4727 int extent_type = -1;
4729 u64 ino = btrfs_ino(inode);
4730 u64 bytes_deleted = 0;
4731 bool be_nice = false;
4732 bool should_throttle = false;
4733 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4734 struct extent_state *cached_state = NULL;
4736 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4739 * For non-free space inodes and non-shareable roots, we want to back
4740 * off from time to time. This means all inodes in subvolume roots,
4741 * reloc roots, and data reloc roots.
4743 if (!btrfs_is_free_space_inode(inode) &&
4744 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4747 path = btrfs_alloc_path();
4750 path->reada = READA_BACK;
4752 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4753 lock_extent_bits(&inode->io_tree, lock_start, (u64)-1,
4757 * We want to drop from the next block forward in case this
4758 * new size is not block aligned since we will be keeping the
4759 * last block of the extent just the way it is.
4761 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4762 fs_info->sectorsize),
4767 * This function is also used to drop the items in the log tree before
4768 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4769 * it is used to drop the logged items. So we shouldn't kill the delayed
4772 if (min_type == 0 && root == inode->root)
4773 btrfs_kill_delayed_inode_items(inode);
4776 key.offset = (u64)-1;
4781 * with a 16K leaf size and 128MB extents, you can actually queue
4782 * up a huge file in a single leaf. Most of the time that
4783 * bytes_deleted is > 0, it will be huge by the time we get here
4785 if (be_nice && bytes_deleted > SZ_32M &&
4786 btrfs_should_end_transaction(trans)) {
4791 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4797 /* there are no items in the tree for us to truncate, we're
4800 if (path->slots[0] == 0)
4806 u64 clear_start = 0, clear_len = 0;
4809 leaf = path->nodes[0];
4810 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4811 found_type = found_key.type;
4813 if (found_key.objectid != ino)
4816 if (found_type < min_type)
4819 item_end = found_key.offset;
4820 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4821 fi = btrfs_item_ptr(leaf, path->slots[0],
4822 struct btrfs_file_extent_item);
4823 extent_type = btrfs_file_extent_type(leaf, fi);
4824 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4826 btrfs_file_extent_num_bytes(leaf, fi);
4828 trace_btrfs_truncate_show_fi_regular(
4829 inode, leaf, fi, found_key.offset);
4830 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4831 item_end += btrfs_file_extent_ram_bytes(leaf,
4834 trace_btrfs_truncate_show_fi_inline(
4835 inode, leaf, fi, path->slots[0],
4840 if (found_type > min_type) {
4843 if (item_end < new_size)
4845 if (found_key.offset >= new_size)
4851 /* FIXME, shrink the extent if the ref count is only 1 */
4852 if (found_type != BTRFS_EXTENT_DATA_KEY)
4855 if (extents_found != NULL)
4858 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4861 clear_start = found_key.offset;
4862 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4864 u64 orig_num_bytes =
4865 btrfs_file_extent_num_bytes(leaf, fi);
4866 extent_num_bytes = ALIGN(new_size -
4868 fs_info->sectorsize);
4869 clear_start = ALIGN(new_size, fs_info->sectorsize);
4870 btrfs_set_file_extent_num_bytes(leaf, fi,
4872 num_dec = (orig_num_bytes -
4874 if (test_bit(BTRFS_ROOT_SHAREABLE,
4877 inode_sub_bytes(&inode->vfs_inode,
4879 btrfs_mark_buffer_dirty(leaf);
4882 btrfs_file_extent_disk_num_bytes(leaf,
4884 extent_offset = found_key.offset -
4885 btrfs_file_extent_offset(leaf, fi);
4887 /* FIXME blocksize != 4096 */
4888 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4889 if (extent_start != 0) {
4891 if (test_bit(BTRFS_ROOT_SHAREABLE,
4893 inode_sub_bytes(&inode->vfs_inode,
4897 clear_len = num_dec;
4898 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4900 * we can't truncate inline items that have had
4904 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4905 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4906 btrfs_file_extent_compression(leaf, fi) == 0) {
4907 u32 size = (u32)(new_size - found_key.offset);
4909 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4910 size = btrfs_file_extent_calc_inline_size(size);
4911 btrfs_truncate_item(path, size, 1);
4912 } else if (!del_item) {
4914 * We have to bail so the last_size is set to
4915 * just before this extent.
4917 ret = NEED_TRUNCATE_BLOCK;
4921 * Inline extents are special, we just treat
4922 * them as a full sector worth in the file
4923 * extent tree just for simplicity sake.
4925 clear_len = fs_info->sectorsize;
4928 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4929 inode_sub_bytes(&inode->vfs_inode,
4930 item_end + 1 - new_size);
4934 * We use btrfs_truncate_inode_items() to clean up log trees for
4935 * multiple fsyncs, and in this case we don't want to clear the
4936 * file extent range because it's just the log.
4938 if (root == inode->root) {
4939 ret = btrfs_inode_clear_file_extent_range(inode,
4940 clear_start, clear_len);
4942 btrfs_abort_transaction(trans, ret);
4948 last_size = found_key.offset;
4950 last_size = new_size;
4952 if (!pending_del_nr) {
4953 /* no pending yet, add ourselves */
4954 pending_del_slot = path->slots[0];
4956 } else if (pending_del_nr &&
4957 path->slots[0] + 1 == pending_del_slot) {
4958 /* hop on the pending chunk */
4960 pending_del_slot = path->slots[0];
4967 should_throttle = false;
4970 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4971 struct btrfs_ref ref = { 0 };
4973 bytes_deleted += extent_num_bytes;
4975 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4976 extent_start, extent_num_bytes, 0);
4977 ref.real_root = root->root_key.objectid;
4978 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4980 root->root_key.objectid, false);
4981 ret = btrfs_free_extent(trans, &ref);
4983 btrfs_abort_transaction(trans, ret);
4987 if (btrfs_should_throttle_delayed_refs(trans))
4988 should_throttle = true;
4992 if (found_type == BTRFS_INODE_ITEM_KEY)
4995 if (path->slots[0] == 0 ||
4996 path->slots[0] != pending_del_slot ||
4998 if (pending_del_nr) {
4999 ret = btrfs_del_items(trans, root, path,
5003 btrfs_abort_transaction(trans, ret);
5008 btrfs_release_path(path);
5011 * We can generate a lot of delayed refs, so we need to
5012 * throttle every once and a while and make sure we're
5013 * adding enough space to keep up with the work we are
5014 * generating. Since we hold a transaction here we
5015 * can't flush, and we don't want to FLUSH_LIMIT because
5016 * we could have generated too many delayed refs to
5017 * actually allocate, so just bail if we're short and
5018 * let the normal reservation dance happen higher up.
5020 if (should_throttle) {
5021 ret = btrfs_delayed_refs_rsv_refill(fs_info,
5022 BTRFS_RESERVE_NO_FLUSH);
5034 if (ret >= 0 && pending_del_nr) {
5037 err = btrfs_del_items(trans, root, path, pending_del_slot,
5040 btrfs_abort_transaction(trans, err);
5044 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5045 ASSERT(last_size >= new_size);
5046 if (!ret && last_size > new_size)
5047 last_size = new_size;
5048 btrfs_inode_safe_disk_i_size_write(inode, last_size);
5049 unlock_extent_cached(&inode->io_tree, lock_start, (u64)-1,
5053 btrfs_free_path(path);
5058 * btrfs_truncate_block - read, zero a chunk and write a block
5059 * @inode - inode that we're zeroing
5060 * @from - the offset to start zeroing
5061 * @len - the length to zero, 0 to zero the entire range respective to the
5063 * @front - zero up to the offset instead of from the offset on
5065 * This will find the block for the "from" offset and cow the block and zero the
5066 * part we want to zero. This is used with truncate and hole punching.
5068 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
5071 struct btrfs_fs_info *fs_info = inode->root->fs_info;
5072 struct address_space *mapping = inode->vfs_inode.i_mapping;
5073 struct extent_io_tree *io_tree = &inode->io_tree;
5074 struct btrfs_ordered_extent *ordered;
5075 struct extent_state *cached_state = NULL;
5076 struct extent_changeset *data_reserved = NULL;
5077 bool only_release_metadata = false;
5078 u32 blocksize = fs_info->sectorsize;
5079 pgoff_t index = from >> PAGE_SHIFT;
5080 unsigned offset = from & (blocksize - 1);
5082 gfp_t mask = btrfs_alloc_write_mask(mapping);
5083 size_t write_bytes = blocksize;
5088 if (IS_ALIGNED(offset, blocksize) &&
5089 (!len || IS_ALIGNED(len, blocksize)))
5092 block_start = round_down(from, blocksize);
5093 block_end = block_start + blocksize - 1;
5095 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
5098 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
5099 /* For nocow case, no need to reserve data space */
5100 only_release_metadata = true;
5105 ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
5107 if (!only_release_metadata)
5108 btrfs_free_reserved_data_space(inode, data_reserved,
5109 block_start, blocksize);
5113 page = find_or_create_page(mapping, index, mask);
5115 btrfs_delalloc_release_space(inode, data_reserved, block_start,
5117 btrfs_delalloc_release_extents(inode, blocksize);
5121 ret = set_page_extent_mapped(page);
5125 if (!PageUptodate(page)) {
5126 ret = btrfs_readpage(NULL, page);
5128 if (page->mapping != mapping) {
5133 if (!PageUptodate(page)) {
5138 wait_on_page_writeback(page);
5140 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
5142 ordered = btrfs_lookup_ordered_extent(inode, block_start);
5144 unlock_extent_cached(io_tree, block_start, block_end,
5148 btrfs_start_ordered_extent(ordered, 1);
5149 btrfs_put_ordered_extent(ordered);
5153 clear_extent_bit(&inode->io_tree, block_start, block_end,
5154 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5155 0, 0, &cached_state);
5157 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5160 unlock_extent_cached(io_tree, block_start, block_end,
5165 if (offset != blocksize) {
5167 len = blocksize - offset;
5169 memzero_page(page, (block_start - page_offset(page)),
5172 memzero_page(page, (block_start - page_offset(page)) + offset,
5174 flush_dcache_page(page);
5176 ClearPageChecked(page);
5177 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
5178 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
5180 if (only_release_metadata)
5181 set_extent_bit(&inode->io_tree, block_start, block_end,
5182 EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
5186 if (only_release_metadata)
5187 btrfs_delalloc_release_metadata(inode, blocksize, true);
5189 btrfs_delalloc_release_space(inode, data_reserved,
5190 block_start, blocksize, true);
5192 btrfs_delalloc_release_extents(inode, blocksize);
5196 if (only_release_metadata)
5197 btrfs_check_nocow_unlock(inode);
5198 extent_changeset_free(data_reserved);
5202 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
5203 u64 offset, u64 len)
5205 struct btrfs_fs_info *fs_info = root->fs_info;
5206 struct btrfs_trans_handle *trans;
5207 struct btrfs_drop_extents_args drop_args = { 0 };
5211 * If NO_HOLES is enabled, we don't need to do anything.
5212 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5213 * or btrfs_update_inode() will be called, which guarantee that the next
5214 * fsync will know this inode was changed and needs to be logged.
5216 if (btrfs_fs_incompat(fs_info, NO_HOLES))
5220 * 1 - for the one we're dropping
5221 * 1 - for the one we're adding
5222 * 1 - for updating the inode.
5224 trans = btrfs_start_transaction(root, 3);
5226 return PTR_ERR(trans);
5228 drop_args.start = offset;
5229 drop_args.end = offset + len;
5230 drop_args.drop_cache = true;
5232 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5234 btrfs_abort_transaction(trans, ret);
5235 btrfs_end_transaction(trans);
5239 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
5240 offset, 0, 0, len, 0, len, 0, 0, 0);
5242 btrfs_abort_transaction(trans, ret);
5244 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5245 btrfs_update_inode(trans, root, inode);
5247 btrfs_end_transaction(trans);
5252 * This function puts in dummy file extents for the area we're creating a hole
5253 * for. So if we are truncating this file to a larger size we need to insert
5254 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5255 * the range between oldsize and size
5257 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5259 struct btrfs_root *root = inode->root;
5260 struct btrfs_fs_info *fs_info = root->fs_info;
5261 struct extent_io_tree *io_tree = &inode->io_tree;
5262 struct extent_map *em = NULL;
5263 struct extent_state *cached_state = NULL;
5264 struct extent_map_tree *em_tree = &inode->extent_tree;
5265 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5266 u64 block_end = ALIGN(size, fs_info->sectorsize);
5273 * If our size started in the middle of a block we need to zero out the
5274 * rest of the block before we expand the i_size, otherwise we could
5275 * expose stale data.
5277 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5281 if (size <= hole_start)
5284 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5286 cur_offset = hole_start;
5288 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5289 block_end - cur_offset);
5295 last_byte = min(extent_map_end(em), block_end);
5296 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5297 hole_size = last_byte - cur_offset;
5299 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5300 struct extent_map *hole_em;
5302 err = maybe_insert_hole(root, inode, cur_offset,
5307 err = btrfs_inode_set_file_extent_range(inode,
5308 cur_offset, hole_size);
5312 btrfs_drop_extent_cache(inode, cur_offset,
5313 cur_offset + hole_size - 1, 0);
5314 hole_em = alloc_extent_map();
5316 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5317 &inode->runtime_flags);
5320 hole_em->start = cur_offset;
5321 hole_em->len = hole_size;
5322 hole_em->orig_start = cur_offset;
5324 hole_em->block_start = EXTENT_MAP_HOLE;
5325 hole_em->block_len = 0;
5326 hole_em->orig_block_len = 0;
5327 hole_em->ram_bytes = hole_size;
5328 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5329 hole_em->generation = fs_info->generation;
5332 write_lock(&em_tree->lock);
5333 err = add_extent_mapping(em_tree, hole_em, 1);
5334 write_unlock(&em_tree->lock);
5337 btrfs_drop_extent_cache(inode, cur_offset,
5341 free_extent_map(hole_em);
5343 err = btrfs_inode_set_file_extent_range(inode,
5344 cur_offset, hole_size);
5349 free_extent_map(em);
5351 cur_offset = last_byte;
5352 if (cur_offset >= block_end)
5355 free_extent_map(em);
5356 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5360 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5362 struct btrfs_root *root = BTRFS_I(inode)->root;
5363 struct btrfs_trans_handle *trans;
5364 loff_t oldsize = i_size_read(inode);
5365 loff_t newsize = attr->ia_size;
5366 int mask = attr->ia_valid;
5370 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5371 * special case where we need to update the times despite not having
5372 * these flags set. For all other operations the VFS set these flags
5373 * explicitly if it wants a timestamp update.
5375 if (newsize != oldsize) {
5376 inode_inc_iversion(inode);
5377 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5378 inode->i_ctime = inode->i_mtime =
5379 current_time(inode);
5382 if (newsize > oldsize) {
5384 * Don't do an expanding truncate while snapshotting is ongoing.
5385 * This is to ensure the snapshot captures a fully consistent
5386 * state of this file - if the snapshot captures this expanding
5387 * truncation, it must capture all writes that happened before
5390 btrfs_drew_write_lock(&root->snapshot_lock);
5391 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5393 btrfs_drew_write_unlock(&root->snapshot_lock);
5397 trans = btrfs_start_transaction(root, 1);
5398 if (IS_ERR(trans)) {
5399 btrfs_drew_write_unlock(&root->snapshot_lock);
5400 return PTR_ERR(trans);
5403 i_size_write(inode, newsize);
5404 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5405 pagecache_isize_extended(inode, oldsize, newsize);
5406 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5407 btrfs_drew_write_unlock(&root->snapshot_lock);
5408 btrfs_end_transaction(trans);
5410 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5412 if (btrfs_is_zoned(fs_info)) {
5413 ret = btrfs_wait_ordered_range(inode,
5414 ALIGN(newsize, fs_info->sectorsize),
5421 * We're truncating a file that used to have good data down to
5422 * zero. Make sure any new writes to the file get on disk
5426 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5427 &BTRFS_I(inode)->runtime_flags);
5429 truncate_setsize(inode, newsize);
5431 inode_dio_wait(inode);
5433 ret = btrfs_truncate(inode, newsize == oldsize);
5434 if (ret && inode->i_nlink) {
5438 * Truncate failed, so fix up the in-memory size. We
5439 * adjusted disk_i_size down as we removed extents, so
5440 * wait for disk_i_size to be stable and then update the
5441 * in-memory size to match.
5443 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5446 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5453 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5456 struct inode *inode = d_inode(dentry);
5457 struct btrfs_root *root = BTRFS_I(inode)->root;
5460 if (btrfs_root_readonly(root))
5463 err = setattr_prepare(mnt_userns, dentry, attr);
5467 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5468 err = btrfs_setsize(inode, attr);
5473 if (attr->ia_valid) {
5474 setattr_copy(mnt_userns, inode, attr);
5475 inode_inc_iversion(inode);
5476 err = btrfs_dirty_inode(inode);
5478 if (!err && attr->ia_valid & ATTR_MODE)
5479 err = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5486 * While truncating the inode pages during eviction, we get the VFS calling
5487 * btrfs_invalidatepage() against each page of the inode. This is slow because
5488 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5489 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5490 * extent_state structures over and over, wasting lots of time.
5492 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5493 * those expensive operations on a per page basis and do only the ordered io
5494 * finishing, while we release here the extent_map and extent_state structures,
5495 * without the excessive merging and splitting.
5497 static void evict_inode_truncate_pages(struct inode *inode)
5499 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5500 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5501 struct rb_node *node;
5503 ASSERT(inode->i_state & I_FREEING);
5504 truncate_inode_pages_final(&inode->i_data);
5506 write_lock(&map_tree->lock);
5507 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5508 struct extent_map *em;
5510 node = rb_first_cached(&map_tree->map);
5511 em = rb_entry(node, struct extent_map, rb_node);
5512 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5513 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5514 remove_extent_mapping(map_tree, em);
5515 free_extent_map(em);
5516 if (need_resched()) {
5517 write_unlock(&map_tree->lock);
5519 write_lock(&map_tree->lock);
5522 write_unlock(&map_tree->lock);
5525 * Keep looping until we have no more ranges in the io tree.
5526 * We can have ongoing bios started by readahead that have
5527 * their endio callback (extent_io.c:end_bio_extent_readpage)
5528 * still in progress (unlocked the pages in the bio but did not yet
5529 * unlocked the ranges in the io tree). Therefore this means some
5530 * ranges can still be locked and eviction started because before
5531 * submitting those bios, which are executed by a separate task (work
5532 * queue kthread), inode references (inode->i_count) were not taken
5533 * (which would be dropped in the end io callback of each bio).
5534 * Therefore here we effectively end up waiting for those bios and
5535 * anyone else holding locked ranges without having bumped the inode's
5536 * reference count - if we don't do it, when they access the inode's
5537 * io_tree to unlock a range it may be too late, leading to an
5538 * use-after-free issue.
5540 spin_lock(&io_tree->lock);
5541 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5542 struct extent_state *state;
5543 struct extent_state *cached_state = NULL;
5546 unsigned state_flags;
5548 node = rb_first(&io_tree->state);
5549 state = rb_entry(node, struct extent_state, rb_node);
5550 start = state->start;
5552 state_flags = state->state;
5553 spin_unlock(&io_tree->lock);
5555 lock_extent_bits(io_tree, start, end, &cached_state);
5558 * If still has DELALLOC flag, the extent didn't reach disk,
5559 * and its reserved space won't be freed by delayed_ref.
5560 * So we need to free its reserved space here.
5561 * (Refer to comment in btrfs_invalidatepage, case 2)
5563 * Note, end is the bytenr of last byte, so we need + 1 here.
5565 if (state_flags & EXTENT_DELALLOC)
5566 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5569 clear_extent_bit(io_tree, start, end,
5570 EXTENT_LOCKED | EXTENT_DELALLOC |
5571 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5575 spin_lock(&io_tree->lock);
5577 spin_unlock(&io_tree->lock);
5580 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5581 struct btrfs_block_rsv *rsv)
5583 struct btrfs_fs_info *fs_info = root->fs_info;
5584 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5585 struct btrfs_trans_handle *trans;
5586 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5590 * Eviction should be taking place at some place safe because of our
5591 * delayed iputs. However the normal flushing code will run delayed
5592 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5594 * We reserve the delayed_refs_extra here again because we can't use
5595 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5596 * above. We reserve our extra bit here because we generate a ton of
5597 * delayed refs activity by truncating.
5599 * If we cannot make our reservation we'll attempt to steal from the
5600 * global reserve, because we really want to be able to free up space.
5602 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5603 BTRFS_RESERVE_FLUSH_EVICT);
5606 * Try to steal from the global reserve if there is space for
5609 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5610 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5612 "could not allocate space for delete; will truncate on mount");
5613 return ERR_PTR(-ENOSPC);
5615 delayed_refs_extra = 0;
5618 trans = btrfs_join_transaction(root);
5622 if (delayed_refs_extra) {
5623 trans->block_rsv = &fs_info->trans_block_rsv;
5624 trans->bytes_reserved = delayed_refs_extra;
5625 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5626 delayed_refs_extra, 1);
5631 void btrfs_evict_inode(struct inode *inode)
5633 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5634 struct btrfs_trans_handle *trans;
5635 struct btrfs_root *root = BTRFS_I(inode)->root;
5636 struct btrfs_block_rsv *rsv;
5639 trace_btrfs_inode_evict(inode);
5642 fsverity_cleanup_inode(inode);
5647 evict_inode_truncate_pages(inode);
5649 if (inode->i_nlink &&
5650 ((btrfs_root_refs(&root->root_item) != 0 &&
5651 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5652 btrfs_is_free_space_inode(BTRFS_I(inode))))
5655 if (is_bad_inode(inode))
5658 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5660 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5663 if (inode->i_nlink > 0) {
5664 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5665 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5669 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5673 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5676 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5679 btrfs_i_size_write(BTRFS_I(inode), 0);
5682 trans = evict_refill_and_join(root, rsv);
5686 trans->block_rsv = rsv;
5688 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
5690 trans->block_rsv = &fs_info->trans_block_rsv;
5691 btrfs_end_transaction(trans);
5692 btrfs_btree_balance_dirty(fs_info);
5693 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5700 * Errors here aren't a big deal, it just means we leave orphan items in
5701 * the tree. They will be cleaned up on the next mount. If the inode
5702 * number gets reused, cleanup deletes the orphan item without doing
5703 * anything, and unlink reuses the existing orphan item.
5705 * If it turns out that we are dropping too many of these, we might want
5706 * to add a mechanism for retrying these after a commit.
5708 trans = evict_refill_and_join(root, rsv);
5709 if (!IS_ERR(trans)) {
5710 trans->block_rsv = rsv;
5711 btrfs_orphan_del(trans, BTRFS_I(inode));
5712 trans->block_rsv = &fs_info->trans_block_rsv;
5713 btrfs_end_transaction(trans);
5717 btrfs_free_block_rsv(fs_info, rsv);
5720 * If we didn't successfully delete, the orphan item will still be in
5721 * the tree and we'll retry on the next mount. Again, we might also want
5722 * to retry these periodically in the future.
5724 btrfs_remove_delayed_node(BTRFS_I(inode));
5725 fsverity_cleanup_inode(inode);
5730 * Return the key found in the dir entry in the location pointer, fill @type
5731 * with BTRFS_FT_*, and return 0.
5733 * If no dir entries were found, returns -ENOENT.
5734 * If found a corrupted location in dir entry, returns -EUCLEAN.
5736 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5737 struct btrfs_key *location, u8 *type)
5739 const char *name = dentry->d_name.name;
5740 int namelen = dentry->d_name.len;
5741 struct btrfs_dir_item *di;
5742 struct btrfs_path *path;
5743 struct btrfs_root *root = BTRFS_I(dir)->root;
5746 path = btrfs_alloc_path();
5750 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5752 if (IS_ERR_OR_NULL(di)) {
5753 ret = di ? PTR_ERR(di) : -ENOENT;
5757 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5758 if (location->type != BTRFS_INODE_ITEM_KEY &&
5759 location->type != BTRFS_ROOT_ITEM_KEY) {
5761 btrfs_warn(root->fs_info,
5762 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5763 __func__, name, btrfs_ino(BTRFS_I(dir)),
5764 location->objectid, location->type, location->offset);
5767 *type = btrfs_dir_type(path->nodes[0], di);
5769 btrfs_free_path(path);
5774 * when we hit a tree root in a directory, the btrfs part of the inode
5775 * needs to be changed to reflect the root directory of the tree root. This
5776 * is kind of like crossing a mount point.
5778 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5780 struct dentry *dentry,
5781 struct btrfs_key *location,
5782 struct btrfs_root **sub_root)
5784 struct btrfs_path *path;
5785 struct btrfs_root *new_root;
5786 struct btrfs_root_ref *ref;
5787 struct extent_buffer *leaf;
5788 struct btrfs_key key;
5792 path = btrfs_alloc_path();
5799 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5800 key.type = BTRFS_ROOT_REF_KEY;
5801 key.offset = location->objectid;
5803 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5810 leaf = path->nodes[0];
5811 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5812 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5813 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5816 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5817 (unsigned long)(ref + 1),
5818 dentry->d_name.len);
5822 btrfs_release_path(path);
5824 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5825 if (IS_ERR(new_root)) {
5826 err = PTR_ERR(new_root);
5830 *sub_root = new_root;
5831 location->objectid = btrfs_root_dirid(&new_root->root_item);
5832 location->type = BTRFS_INODE_ITEM_KEY;
5833 location->offset = 0;
5836 btrfs_free_path(path);
5840 static void inode_tree_add(struct inode *inode)
5842 struct btrfs_root *root = BTRFS_I(inode)->root;
5843 struct btrfs_inode *entry;
5845 struct rb_node *parent;
5846 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5847 u64 ino = btrfs_ino(BTRFS_I(inode));
5849 if (inode_unhashed(inode))
5852 spin_lock(&root->inode_lock);
5853 p = &root->inode_tree.rb_node;
5856 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5858 if (ino < btrfs_ino(entry))
5859 p = &parent->rb_left;
5860 else if (ino > btrfs_ino(entry))
5861 p = &parent->rb_right;
5863 WARN_ON(!(entry->vfs_inode.i_state &
5864 (I_WILL_FREE | I_FREEING)));
5865 rb_replace_node(parent, new, &root->inode_tree);
5866 RB_CLEAR_NODE(parent);
5867 spin_unlock(&root->inode_lock);
5871 rb_link_node(new, parent, p);
5872 rb_insert_color(new, &root->inode_tree);
5873 spin_unlock(&root->inode_lock);
5876 static void inode_tree_del(struct btrfs_inode *inode)
5878 struct btrfs_root *root = inode->root;
5881 spin_lock(&root->inode_lock);
5882 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5883 rb_erase(&inode->rb_node, &root->inode_tree);
5884 RB_CLEAR_NODE(&inode->rb_node);
5885 empty = RB_EMPTY_ROOT(&root->inode_tree);
5887 spin_unlock(&root->inode_lock);
5889 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5890 spin_lock(&root->inode_lock);
5891 empty = RB_EMPTY_ROOT(&root->inode_tree);
5892 spin_unlock(&root->inode_lock);
5894 btrfs_add_dead_root(root);
5899 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5901 struct btrfs_iget_args *args = p;
5903 inode->i_ino = args->ino;
5904 BTRFS_I(inode)->location.objectid = args->ino;
5905 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5906 BTRFS_I(inode)->location.offset = 0;
5907 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5908 BUG_ON(args->root && !BTRFS_I(inode)->root);
5912 static int btrfs_find_actor(struct inode *inode, void *opaque)
5914 struct btrfs_iget_args *args = opaque;
5916 return args->ino == BTRFS_I(inode)->location.objectid &&
5917 args->root == BTRFS_I(inode)->root;
5920 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5921 struct btrfs_root *root)
5923 struct inode *inode;
5924 struct btrfs_iget_args args;
5925 unsigned long hashval = btrfs_inode_hash(ino, root);
5930 inode = iget5_locked(s, hashval, btrfs_find_actor,
5931 btrfs_init_locked_inode,
5937 * Get an inode object given its inode number and corresponding root.
5938 * Path can be preallocated to prevent recursing back to iget through
5939 * allocator. NULL is also valid but may require an additional allocation
5942 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5943 struct btrfs_root *root, struct btrfs_path *path)
5945 struct inode *inode;
5947 inode = btrfs_iget_locked(s, ino, root);
5949 return ERR_PTR(-ENOMEM);
5951 if (inode->i_state & I_NEW) {
5954 ret = btrfs_read_locked_inode(inode, path);
5956 inode_tree_add(inode);
5957 unlock_new_inode(inode);
5961 * ret > 0 can come from btrfs_search_slot called by
5962 * btrfs_read_locked_inode, this means the inode item
5967 inode = ERR_PTR(ret);
5974 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5976 return btrfs_iget_path(s, ino, root, NULL);
5979 static struct inode *new_simple_dir(struct super_block *s,
5980 struct btrfs_key *key,
5981 struct btrfs_root *root)
5983 struct inode *inode = new_inode(s);
5986 return ERR_PTR(-ENOMEM);
5988 BTRFS_I(inode)->root = btrfs_grab_root(root);
5989 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5990 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5992 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5994 * We only need lookup, the rest is read-only and there's no inode
5995 * associated with the dentry
5997 inode->i_op = &simple_dir_inode_operations;
5998 inode->i_opflags &= ~IOP_XATTR;
5999 inode->i_fop = &simple_dir_operations;
6000 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
6001 inode->i_mtime = current_time(inode);
6002 inode->i_atime = inode->i_mtime;
6003 inode->i_ctime = inode->i_mtime;
6004 BTRFS_I(inode)->i_otime = inode->i_mtime;
6009 static inline u8 btrfs_inode_type(struct inode *inode)
6012 * Compile-time asserts that generic FT_* types still match
6015 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
6016 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
6017 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
6018 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
6019 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
6020 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
6021 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
6022 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
6024 return fs_umode_to_ftype(inode->i_mode);
6027 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
6029 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6030 struct inode *inode;
6031 struct btrfs_root *root = BTRFS_I(dir)->root;
6032 struct btrfs_root *sub_root = root;
6033 struct btrfs_key location;
6037 if (dentry->d_name.len > BTRFS_NAME_LEN)
6038 return ERR_PTR(-ENAMETOOLONG);
6040 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
6042 return ERR_PTR(ret);
6044 if (location.type == BTRFS_INODE_ITEM_KEY) {
6045 inode = btrfs_iget(dir->i_sb, location.objectid, root);
6049 /* Do extra check against inode mode with di_type */
6050 if (btrfs_inode_type(inode) != di_type) {
6052 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
6053 inode->i_mode, btrfs_inode_type(inode),
6056 return ERR_PTR(-EUCLEAN);
6061 ret = fixup_tree_root_location(fs_info, dir, dentry,
6062 &location, &sub_root);
6065 inode = ERR_PTR(ret);
6067 inode = new_simple_dir(dir->i_sb, &location, sub_root);
6069 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
6071 if (root != sub_root)
6072 btrfs_put_root(sub_root);
6074 if (!IS_ERR(inode) && root != sub_root) {
6075 down_read(&fs_info->cleanup_work_sem);
6076 if (!sb_rdonly(inode->i_sb))
6077 ret = btrfs_orphan_cleanup(sub_root);
6078 up_read(&fs_info->cleanup_work_sem);
6081 inode = ERR_PTR(ret);
6088 static int btrfs_dentry_delete(const struct dentry *dentry)
6090 struct btrfs_root *root;
6091 struct inode *inode = d_inode(dentry);
6093 if (!inode && !IS_ROOT(dentry))
6094 inode = d_inode(dentry->d_parent);
6097 root = BTRFS_I(inode)->root;
6098 if (btrfs_root_refs(&root->root_item) == 0)
6101 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6107 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
6110 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
6112 if (inode == ERR_PTR(-ENOENT))
6114 return d_splice_alias(inode, dentry);
6118 * All this infrastructure exists because dir_emit can fault, and we are holding
6119 * the tree lock when doing readdir. For now just allocate a buffer and copy
6120 * our information into that, and then dir_emit from the buffer. This is
6121 * similar to what NFS does, only we don't keep the buffer around in pagecache
6122 * because I'm afraid I'll mess that up. Long term we need to make filldir do
6123 * copy_to_user_inatomic so we don't have to worry about page faulting under the
6126 static int btrfs_opendir(struct inode *inode, struct file *file)
6128 struct btrfs_file_private *private;
6130 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
6133 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6134 if (!private->filldir_buf) {
6138 file->private_data = private;
6149 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6152 struct dir_entry *entry = addr;
6153 char *name = (char *)(entry + 1);
6155 ctx->pos = get_unaligned(&entry->offset);
6156 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6157 get_unaligned(&entry->ino),
6158 get_unaligned(&entry->type)))
6160 addr += sizeof(struct dir_entry) +
6161 get_unaligned(&entry->name_len);
6167 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6169 struct inode *inode = file_inode(file);
6170 struct btrfs_root *root = BTRFS_I(inode)->root;
6171 struct btrfs_file_private *private = file->private_data;
6172 struct btrfs_dir_item *di;
6173 struct btrfs_key key;
6174 struct btrfs_key found_key;
6175 struct btrfs_path *path;
6177 struct list_head ins_list;
6178 struct list_head del_list;
6180 struct extent_buffer *leaf;
6187 struct btrfs_key location;
6189 if (!dir_emit_dots(file, ctx))
6192 path = btrfs_alloc_path();
6196 addr = private->filldir_buf;
6197 path->reada = READA_FORWARD;
6199 INIT_LIST_HEAD(&ins_list);
6200 INIT_LIST_HEAD(&del_list);
6201 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6204 key.type = BTRFS_DIR_INDEX_KEY;
6205 key.offset = ctx->pos;
6206 key.objectid = btrfs_ino(BTRFS_I(inode));
6208 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6213 struct dir_entry *entry;
6215 leaf = path->nodes[0];
6216 slot = path->slots[0];
6217 if (slot >= btrfs_header_nritems(leaf)) {
6218 ret = btrfs_next_leaf(root, path);
6226 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6228 if (found_key.objectid != key.objectid)
6230 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6232 if (found_key.offset < ctx->pos)
6234 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6236 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6237 name_len = btrfs_dir_name_len(leaf, di);
6238 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6240 btrfs_release_path(path);
6241 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6244 addr = private->filldir_buf;
6251 put_unaligned(name_len, &entry->name_len);
6252 name_ptr = (char *)(entry + 1);
6253 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6255 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6257 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6258 put_unaligned(location.objectid, &entry->ino);
6259 put_unaligned(found_key.offset, &entry->offset);
6261 addr += sizeof(struct dir_entry) + name_len;
6262 total_len += sizeof(struct dir_entry) + name_len;
6266 btrfs_release_path(path);
6268 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6272 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6277 * Stop new entries from being returned after we return the last
6280 * New directory entries are assigned a strictly increasing
6281 * offset. This means that new entries created during readdir
6282 * are *guaranteed* to be seen in the future by that readdir.
6283 * This has broken buggy programs which operate on names as
6284 * they're returned by readdir. Until we re-use freed offsets
6285 * we have this hack to stop new entries from being returned
6286 * under the assumption that they'll never reach this huge
6289 * This is being careful not to overflow 32bit loff_t unless the
6290 * last entry requires it because doing so has broken 32bit apps
6293 if (ctx->pos >= INT_MAX)
6294 ctx->pos = LLONG_MAX;
6301 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6302 btrfs_free_path(path);
6307 * This is somewhat expensive, updating the tree every time the
6308 * inode changes. But, it is most likely to find the inode in cache.
6309 * FIXME, needs more benchmarking...there are no reasons other than performance
6310 * to keep or drop this code.
6312 static int btrfs_dirty_inode(struct inode *inode)
6314 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6315 struct btrfs_root *root = BTRFS_I(inode)->root;
6316 struct btrfs_trans_handle *trans;
6319 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6322 trans = btrfs_join_transaction(root);
6324 return PTR_ERR(trans);
6326 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6327 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6328 /* whoops, lets try again with the full transaction */
6329 btrfs_end_transaction(trans);
6330 trans = btrfs_start_transaction(root, 1);
6332 return PTR_ERR(trans);
6334 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6336 btrfs_end_transaction(trans);
6337 if (BTRFS_I(inode)->delayed_node)
6338 btrfs_balance_delayed_items(fs_info);
6344 * This is a copy of file_update_time. We need this so we can return error on
6345 * ENOSPC for updating the inode in the case of file write and mmap writes.
6347 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6350 struct btrfs_root *root = BTRFS_I(inode)->root;
6351 bool dirty = flags & ~S_VERSION;
6353 if (btrfs_root_readonly(root))
6356 if (flags & S_VERSION)
6357 dirty |= inode_maybe_inc_iversion(inode, dirty);
6358 if (flags & S_CTIME)
6359 inode->i_ctime = *now;
6360 if (flags & S_MTIME)
6361 inode->i_mtime = *now;
6362 if (flags & S_ATIME)
6363 inode->i_atime = *now;
6364 return dirty ? btrfs_dirty_inode(inode) : 0;
6368 * find the highest existing sequence number in a directory
6369 * and then set the in-memory index_cnt variable to reflect
6370 * free sequence numbers
6372 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6374 struct btrfs_root *root = inode->root;
6375 struct btrfs_key key, found_key;
6376 struct btrfs_path *path;
6377 struct extent_buffer *leaf;
6380 key.objectid = btrfs_ino(inode);
6381 key.type = BTRFS_DIR_INDEX_KEY;
6382 key.offset = (u64)-1;
6384 path = btrfs_alloc_path();
6388 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6391 /* FIXME: we should be able to handle this */
6396 if (path->slots[0] == 0) {
6397 inode->index_cnt = BTRFS_DIR_START_INDEX;
6403 leaf = path->nodes[0];
6404 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6406 if (found_key.objectid != btrfs_ino(inode) ||
6407 found_key.type != BTRFS_DIR_INDEX_KEY) {
6408 inode->index_cnt = BTRFS_DIR_START_INDEX;
6412 inode->index_cnt = found_key.offset + 1;
6414 btrfs_free_path(path);
6419 * helper to find a free sequence number in a given directory. This current
6420 * code is very simple, later versions will do smarter things in the btree
6422 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6426 if (dir->index_cnt == (u64)-1) {
6427 ret = btrfs_inode_delayed_dir_index_count(dir);
6429 ret = btrfs_set_inode_index_count(dir);
6435 *index = dir->index_cnt;
6441 static int btrfs_insert_inode_locked(struct inode *inode)
6443 struct btrfs_iget_args args;
6445 args.ino = BTRFS_I(inode)->location.objectid;
6446 args.root = BTRFS_I(inode)->root;
6448 return insert_inode_locked4(inode,
6449 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6450 btrfs_find_actor, &args);
6454 * Inherit flags from the parent inode.
6456 * Currently only the compression flags and the cow flags are inherited.
6458 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6465 flags = BTRFS_I(dir)->flags;
6467 if (flags & BTRFS_INODE_NOCOMPRESS) {
6468 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6469 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6470 } else if (flags & BTRFS_INODE_COMPRESS) {
6471 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6472 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6475 if (flags & BTRFS_INODE_NODATACOW) {
6476 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6477 if (S_ISREG(inode->i_mode))
6478 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6481 btrfs_sync_inode_flags_to_i_flags(inode);
6484 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6485 struct btrfs_root *root,
6486 struct user_namespace *mnt_userns,
6488 const char *name, int name_len,
6489 u64 ref_objectid, u64 objectid,
6490 umode_t mode, u64 *index)
6492 struct btrfs_fs_info *fs_info = root->fs_info;
6493 struct inode *inode;
6494 struct btrfs_inode_item *inode_item;
6495 struct btrfs_key *location;
6496 struct btrfs_path *path;
6497 struct btrfs_inode_ref *ref;
6498 struct btrfs_key key[2];
6500 int nitems = name ? 2 : 1;
6502 unsigned int nofs_flag;
6505 path = btrfs_alloc_path();
6507 return ERR_PTR(-ENOMEM);
6509 nofs_flag = memalloc_nofs_save();
6510 inode = new_inode(fs_info->sb);
6511 memalloc_nofs_restore(nofs_flag);
6513 btrfs_free_path(path);
6514 return ERR_PTR(-ENOMEM);
6518 * O_TMPFILE, set link count to 0, so that after this point,
6519 * we fill in an inode item with the correct link count.
6522 set_nlink(inode, 0);
6525 * we have to initialize this early, so we can reclaim the inode
6526 * number if we fail afterwards in this function.
6528 inode->i_ino = objectid;
6531 trace_btrfs_inode_request(dir);
6533 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6535 btrfs_free_path(path);
6537 return ERR_PTR(ret);
6543 * index_cnt is ignored for everything but a dir,
6544 * btrfs_set_inode_index_count has an explanation for the magic
6547 BTRFS_I(inode)->index_cnt = 2;
6548 BTRFS_I(inode)->dir_index = *index;
6549 BTRFS_I(inode)->root = btrfs_grab_root(root);
6550 BTRFS_I(inode)->generation = trans->transid;
6551 inode->i_generation = BTRFS_I(inode)->generation;
6554 * We could have gotten an inode number from somebody who was fsynced
6555 * and then removed in this same transaction, so let's just set full
6556 * sync since it will be a full sync anyway and this will blow away the
6557 * old info in the log.
6559 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6561 key[0].objectid = objectid;
6562 key[0].type = BTRFS_INODE_ITEM_KEY;
6565 sizes[0] = sizeof(struct btrfs_inode_item);
6569 * Start new inodes with an inode_ref. This is slightly more
6570 * efficient for small numbers of hard links since they will
6571 * be packed into one item. Extended refs will kick in if we
6572 * add more hard links than can fit in the ref item.
6574 key[1].objectid = objectid;
6575 key[1].type = BTRFS_INODE_REF_KEY;
6576 key[1].offset = ref_objectid;
6578 sizes[1] = name_len + sizeof(*ref);
6581 location = &BTRFS_I(inode)->location;
6582 location->objectid = objectid;
6583 location->offset = 0;
6584 location->type = BTRFS_INODE_ITEM_KEY;
6586 ret = btrfs_insert_inode_locked(inode);
6592 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6596 inode_init_owner(mnt_userns, inode, dir, mode);
6597 inode_set_bytes(inode, 0);
6599 inode->i_mtime = current_time(inode);
6600 inode->i_atime = inode->i_mtime;
6601 inode->i_ctime = inode->i_mtime;
6602 BTRFS_I(inode)->i_otime = inode->i_mtime;
6604 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6605 struct btrfs_inode_item);
6606 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6607 sizeof(*inode_item));
6608 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6611 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6612 struct btrfs_inode_ref);
6613 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6614 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6615 ptr = (unsigned long)(ref + 1);
6616 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6619 btrfs_mark_buffer_dirty(path->nodes[0]);
6620 btrfs_free_path(path);
6622 btrfs_inherit_iflags(inode, dir);
6624 if (S_ISREG(mode)) {
6625 if (btrfs_test_opt(fs_info, NODATASUM))
6626 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6627 if (btrfs_test_opt(fs_info, NODATACOW))
6628 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6629 BTRFS_INODE_NODATASUM;
6632 inode_tree_add(inode);
6634 trace_btrfs_inode_new(inode);
6635 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6637 btrfs_update_root_times(trans, root);
6639 ret = btrfs_inode_inherit_props(trans, inode, dir);
6642 "error inheriting props for ino %llu (root %llu): %d",
6643 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6648 discard_new_inode(inode);
6651 BTRFS_I(dir)->index_cnt--;
6652 btrfs_free_path(path);
6653 return ERR_PTR(ret);
6657 * utility function to add 'inode' into 'parent_inode' with
6658 * a give name and a given sequence number.
6659 * if 'add_backref' is true, also insert a backref from the
6660 * inode to the parent directory.
6662 int btrfs_add_link(struct btrfs_trans_handle *trans,
6663 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6664 const char *name, int name_len, int add_backref, u64 index)
6667 struct btrfs_key key;
6668 struct btrfs_root *root = parent_inode->root;
6669 u64 ino = btrfs_ino(inode);
6670 u64 parent_ino = btrfs_ino(parent_inode);
6672 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6673 memcpy(&key, &inode->root->root_key, sizeof(key));
6676 key.type = BTRFS_INODE_ITEM_KEY;
6680 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6681 ret = btrfs_add_root_ref(trans, key.objectid,
6682 root->root_key.objectid, parent_ino,
6683 index, name, name_len);
6684 } else if (add_backref) {
6685 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6689 /* Nothing to clean up yet */
6693 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6694 btrfs_inode_type(&inode->vfs_inode), index);
6695 if (ret == -EEXIST || ret == -EOVERFLOW)
6698 btrfs_abort_transaction(trans, ret);
6702 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6704 inode_inc_iversion(&parent_inode->vfs_inode);
6706 * If we are replaying a log tree, we do not want to update the mtime
6707 * and ctime of the parent directory with the current time, since the
6708 * log replay procedure is responsible for setting them to their correct
6709 * values (the ones it had when the fsync was done).
6711 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6712 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6714 parent_inode->vfs_inode.i_mtime = now;
6715 parent_inode->vfs_inode.i_ctime = now;
6717 ret = btrfs_update_inode(trans, root, parent_inode);
6719 btrfs_abort_transaction(trans, ret);
6723 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6726 err = btrfs_del_root_ref(trans, key.objectid,
6727 root->root_key.objectid, parent_ino,
6728 &local_index, name, name_len);
6730 btrfs_abort_transaction(trans, err);
6731 } else if (add_backref) {
6735 err = btrfs_del_inode_ref(trans, root, name, name_len,
6736 ino, parent_ino, &local_index);
6738 btrfs_abort_transaction(trans, err);
6741 /* Return the original error code */
6745 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6746 struct btrfs_inode *dir, struct dentry *dentry,
6747 struct btrfs_inode *inode, int backref, u64 index)
6749 int err = btrfs_add_link(trans, dir, inode,
6750 dentry->d_name.name, dentry->d_name.len,
6757 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6758 struct dentry *dentry, umode_t mode, dev_t rdev)
6760 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6761 struct btrfs_trans_handle *trans;
6762 struct btrfs_root *root = BTRFS_I(dir)->root;
6763 struct inode *inode = NULL;
6769 * 2 for inode item and ref
6771 * 1 for xattr if selinux is on
6773 trans = btrfs_start_transaction(root, 5);
6775 return PTR_ERR(trans);
6777 err = btrfs_get_free_objectid(root, &objectid);
6781 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6782 dentry->d_name.name, dentry->d_name.len,
6783 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
6784 if (IS_ERR(inode)) {
6785 err = PTR_ERR(inode);
6791 * If the active LSM wants to access the inode during
6792 * d_instantiate it needs these. Smack checks to see
6793 * if the filesystem supports xattrs by looking at the
6796 inode->i_op = &btrfs_special_inode_operations;
6797 init_special_inode(inode, inode->i_mode, rdev);
6799 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6803 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6808 btrfs_update_inode(trans, root, BTRFS_I(inode));
6809 d_instantiate_new(dentry, inode);
6812 btrfs_end_transaction(trans);
6813 btrfs_btree_balance_dirty(fs_info);
6815 inode_dec_link_count(inode);
6816 discard_new_inode(inode);
6821 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6822 struct dentry *dentry, umode_t mode, bool excl)
6824 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6825 struct btrfs_trans_handle *trans;
6826 struct btrfs_root *root = BTRFS_I(dir)->root;
6827 struct inode *inode = NULL;
6833 * 2 for inode item and ref
6835 * 1 for xattr if selinux is on
6837 trans = btrfs_start_transaction(root, 5);
6839 return PTR_ERR(trans);
6841 err = btrfs_get_free_objectid(root, &objectid);
6845 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6846 dentry->d_name.name, dentry->d_name.len,
6847 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
6848 if (IS_ERR(inode)) {
6849 err = PTR_ERR(inode);
6854 * If the active LSM wants to access the inode during
6855 * d_instantiate it needs these. Smack checks to see
6856 * if the filesystem supports xattrs by looking at the
6859 inode->i_fop = &btrfs_file_operations;
6860 inode->i_op = &btrfs_file_inode_operations;
6861 inode->i_mapping->a_ops = &btrfs_aops;
6863 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6867 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6871 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6876 d_instantiate_new(dentry, inode);
6879 btrfs_end_transaction(trans);
6881 inode_dec_link_count(inode);
6882 discard_new_inode(inode);
6884 btrfs_btree_balance_dirty(fs_info);
6888 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6889 struct dentry *dentry)
6891 struct btrfs_trans_handle *trans = NULL;
6892 struct btrfs_root *root = BTRFS_I(dir)->root;
6893 struct inode *inode = d_inode(old_dentry);
6894 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6899 /* do not allow sys_link's with other subvols of the same device */
6900 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6903 if (inode->i_nlink >= BTRFS_LINK_MAX)
6906 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6911 * 2 items for inode and inode ref
6912 * 2 items for dir items
6913 * 1 item for parent inode
6914 * 1 item for orphan item deletion if O_TMPFILE
6916 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6917 if (IS_ERR(trans)) {
6918 err = PTR_ERR(trans);
6923 /* There are several dir indexes for this inode, clear the cache. */
6924 BTRFS_I(inode)->dir_index = 0ULL;
6926 inode_inc_iversion(inode);
6927 inode->i_ctime = current_time(inode);
6929 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6931 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6937 struct dentry *parent = dentry->d_parent;
6939 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6942 if (inode->i_nlink == 1) {
6944 * If new hard link count is 1, it's a file created
6945 * with open(2) O_TMPFILE flag.
6947 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6951 d_instantiate(dentry, inode);
6952 btrfs_log_new_name(trans, old_dentry, NULL, parent);
6957 btrfs_end_transaction(trans);
6959 inode_dec_link_count(inode);
6962 btrfs_btree_balance_dirty(fs_info);
6966 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6967 struct dentry *dentry, umode_t mode)
6969 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6970 struct inode *inode = NULL;
6971 struct btrfs_trans_handle *trans;
6972 struct btrfs_root *root = BTRFS_I(dir)->root;
6978 * 2 items for inode and ref
6979 * 2 items for dir items
6980 * 1 for xattr if selinux is on
6982 trans = btrfs_start_transaction(root, 5);
6984 return PTR_ERR(trans);
6986 err = btrfs_get_free_objectid(root, &objectid);
6990 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6991 dentry->d_name.name, dentry->d_name.len,
6992 btrfs_ino(BTRFS_I(dir)), objectid,
6993 S_IFDIR | mode, &index);
6994 if (IS_ERR(inode)) {
6995 err = PTR_ERR(inode);
7000 /* these must be set before we unlock the inode */
7001 inode->i_op = &btrfs_dir_inode_operations;
7002 inode->i_fop = &btrfs_dir_file_operations;
7004 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7008 btrfs_i_size_write(BTRFS_I(inode), 0);
7009 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
7013 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
7014 dentry->d_name.name,
7015 dentry->d_name.len, 0, index);
7019 d_instantiate_new(dentry, inode);
7022 btrfs_end_transaction(trans);
7024 inode_dec_link_count(inode);
7025 discard_new_inode(inode);
7027 btrfs_btree_balance_dirty(fs_info);
7031 static noinline int uncompress_inline(struct btrfs_path *path,
7033 size_t pg_offset, u64 extent_offset,
7034 struct btrfs_file_extent_item *item)
7037 struct extent_buffer *leaf = path->nodes[0];
7040 unsigned long inline_size;
7044 WARN_ON(pg_offset != 0);
7045 compress_type = btrfs_file_extent_compression(leaf, item);
7046 max_size = btrfs_file_extent_ram_bytes(leaf, item);
7047 inline_size = btrfs_file_extent_inline_item_len(leaf,
7048 btrfs_item_nr(path->slots[0]));
7049 tmp = kmalloc(inline_size, GFP_NOFS);
7052 ptr = btrfs_file_extent_inline_start(item);
7054 read_extent_buffer(leaf, tmp, ptr, inline_size);
7056 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
7057 ret = btrfs_decompress(compress_type, tmp, page,
7058 extent_offset, inline_size, max_size);
7061 * decompression code contains a memset to fill in any space between the end
7062 * of the uncompressed data and the end of max_size in case the decompressed
7063 * data ends up shorter than ram_bytes. That doesn't cover the hole between
7064 * the end of an inline extent and the beginning of the next block, so we
7065 * cover that region here.
7068 if (max_size + pg_offset < PAGE_SIZE)
7069 memzero_page(page, pg_offset + max_size,
7070 PAGE_SIZE - max_size - pg_offset);
7076 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
7077 * @inode: file to search in
7078 * @page: page to read extent data into if the extent is inline
7079 * @pg_offset: offset into @page to copy to
7080 * @start: file offset
7081 * @len: length of range starting at @start
7083 * This returns the first &struct extent_map which overlaps with the given
7084 * range, reading it from the B-tree and caching it if necessary. Note that
7085 * there may be more extents which overlap the given range after the returned
7088 * If @page is not NULL and the extent is inline, this also reads the extent
7089 * data directly into the page and marks the extent up to date in the io_tree.
7091 * Return: ERR_PTR on error, non-NULL extent_map on success.
7093 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
7094 struct page *page, size_t pg_offset,
7097 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7099 u64 extent_start = 0;
7101 u64 objectid = btrfs_ino(inode);
7102 int extent_type = -1;
7103 struct btrfs_path *path = NULL;
7104 struct btrfs_root *root = inode->root;
7105 struct btrfs_file_extent_item *item;
7106 struct extent_buffer *leaf;
7107 struct btrfs_key found_key;
7108 struct extent_map *em = NULL;
7109 struct extent_map_tree *em_tree = &inode->extent_tree;
7110 struct extent_io_tree *io_tree = &inode->io_tree;
7112 read_lock(&em_tree->lock);
7113 em = lookup_extent_mapping(em_tree, start, len);
7114 read_unlock(&em_tree->lock);
7117 if (em->start > start || em->start + em->len <= start)
7118 free_extent_map(em);
7119 else if (em->block_start == EXTENT_MAP_INLINE && page)
7120 free_extent_map(em);
7124 em = alloc_extent_map();
7129 em->start = EXTENT_MAP_HOLE;
7130 em->orig_start = EXTENT_MAP_HOLE;
7132 em->block_len = (u64)-1;
7134 path = btrfs_alloc_path();
7140 /* Chances are we'll be called again, so go ahead and do readahead */
7141 path->reada = READA_FORWARD;
7144 * The same explanation in load_free_space_cache applies here as well,
7145 * we only read when we're loading the free space cache, and at that
7146 * point the commit_root has everything we need.
7148 if (btrfs_is_free_space_inode(inode)) {
7149 path->search_commit_root = 1;
7150 path->skip_locking = 1;
7153 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7156 } else if (ret > 0) {
7157 if (path->slots[0] == 0)
7163 leaf = path->nodes[0];
7164 item = btrfs_item_ptr(leaf, path->slots[0],
7165 struct btrfs_file_extent_item);
7166 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7167 if (found_key.objectid != objectid ||
7168 found_key.type != BTRFS_EXTENT_DATA_KEY) {
7170 * If we backup past the first extent we want to move forward
7171 * and see if there is an extent in front of us, otherwise we'll
7172 * say there is a hole for our whole search range which can
7179 extent_type = btrfs_file_extent_type(leaf, item);
7180 extent_start = found_key.offset;
7181 extent_end = btrfs_file_extent_end(path);
7182 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7183 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7184 /* Only regular file could have regular/prealloc extent */
7185 if (!S_ISREG(inode->vfs_inode.i_mode)) {
7188 "regular/prealloc extent found for non-regular inode %llu",
7192 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7194 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7195 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7200 if (start >= extent_end) {
7202 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7203 ret = btrfs_next_leaf(root, path);
7209 leaf = path->nodes[0];
7211 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7212 if (found_key.objectid != objectid ||
7213 found_key.type != BTRFS_EXTENT_DATA_KEY)
7215 if (start + len <= found_key.offset)
7217 if (start > found_key.offset)
7220 /* New extent overlaps with existing one */
7222 em->orig_start = start;
7223 em->len = found_key.offset - start;
7224 em->block_start = EXTENT_MAP_HOLE;
7228 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
7230 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7231 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7233 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7237 size_t extent_offset;
7243 size = btrfs_file_extent_ram_bytes(leaf, item);
7244 extent_offset = page_offset(page) + pg_offset - extent_start;
7245 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7246 size - extent_offset);
7247 em->start = extent_start + extent_offset;
7248 em->len = ALIGN(copy_size, fs_info->sectorsize);
7249 em->orig_block_len = em->len;
7250 em->orig_start = em->start;
7251 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7253 if (!PageUptodate(page)) {
7254 if (btrfs_file_extent_compression(leaf, item) !=
7255 BTRFS_COMPRESS_NONE) {
7256 ret = uncompress_inline(path, page, pg_offset,
7257 extent_offset, item);
7261 map = kmap_local_page(page);
7262 read_extent_buffer(leaf, map + pg_offset, ptr,
7264 if (pg_offset + copy_size < PAGE_SIZE) {
7265 memset(map + pg_offset + copy_size, 0,
7266 PAGE_SIZE - pg_offset -
7271 flush_dcache_page(page);
7273 set_extent_uptodate(io_tree, em->start,
7274 extent_map_end(em) - 1, NULL, GFP_NOFS);
7279 em->orig_start = start;
7281 em->block_start = EXTENT_MAP_HOLE;
7284 btrfs_release_path(path);
7285 if (em->start > start || extent_map_end(em) <= start) {
7287 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7288 em->start, em->len, start, len);
7293 write_lock(&em_tree->lock);
7294 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7295 write_unlock(&em_tree->lock);
7297 btrfs_free_path(path);
7299 trace_btrfs_get_extent(root, inode, em);
7302 free_extent_map(em);
7303 return ERR_PTR(ret);
7308 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7311 struct extent_map *em;
7312 struct extent_map *hole_em = NULL;
7313 u64 delalloc_start = start;
7319 em = btrfs_get_extent(inode, NULL, 0, start, len);
7323 * If our em maps to:
7325 * - a pre-alloc extent,
7326 * there might actually be delalloc bytes behind it.
7328 if (em->block_start != EXTENT_MAP_HOLE &&
7329 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7334 /* check to see if we've wrapped (len == -1 or similar) */
7343 /* ok, we didn't find anything, lets look for delalloc */
7344 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7345 end, len, EXTENT_DELALLOC, 1);
7346 delalloc_end = delalloc_start + delalloc_len;
7347 if (delalloc_end < delalloc_start)
7348 delalloc_end = (u64)-1;
7351 * We didn't find anything useful, return the original results from
7354 if (delalloc_start > end || delalloc_end <= start) {
7361 * Adjust the delalloc_start to make sure it doesn't go backwards from
7362 * the start they passed in
7364 delalloc_start = max(start, delalloc_start);
7365 delalloc_len = delalloc_end - delalloc_start;
7367 if (delalloc_len > 0) {
7370 const u64 hole_end = extent_map_end(hole_em);
7372 em = alloc_extent_map();
7380 * When btrfs_get_extent can't find anything it returns one
7383 * Make sure what it found really fits our range, and adjust to
7384 * make sure it is based on the start from the caller
7386 if (hole_end <= start || hole_em->start > end) {
7387 free_extent_map(hole_em);
7390 hole_start = max(hole_em->start, start);
7391 hole_len = hole_end - hole_start;
7394 if (hole_em && delalloc_start > hole_start) {
7396 * Our hole starts before our delalloc, so we have to
7397 * return just the parts of the hole that go until the
7400 em->len = min(hole_len, delalloc_start - hole_start);
7401 em->start = hole_start;
7402 em->orig_start = hole_start;
7404 * Don't adjust block start at all, it is fixed at
7407 em->block_start = hole_em->block_start;
7408 em->block_len = hole_len;
7409 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7410 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7413 * Hole is out of passed range or it starts after
7416 em->start = delalloc_start;
7417 em->len = delalloc_len;
7418 em->orig_start = delalloc_start;
7419 em->block_start = EXTENT_MAP_DELALLOC;
7420 em->block_len = delalloc_len;
7427 free_extent_map(hole_em);
7429 free_extent_map(em);
7430 return ERR_PTR(err);
7435 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7438 const u64 orig_start,
7439 const u64 block_start,
7440 const u64 block_len,
7441 const u64 orig_block_len,
7442 const u64 ram_bytes,
7445 struct extent_map *em = NULL;
7448 if (type != BTRFS_ORDERED_NOCOW) {
7449 em = create_io_em(inode, start, len, orig_start, block_start,
7450 block_len, orig_block_len, ram_bytes,
7451 BTRFS_COMPRESS_NONE, /* compress_type */
7456 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7460 free_extent_map(em);
7461 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7470 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7473 struct btrfs_root *root = inode->root;
7474 struct btrfs_fs_info *fs_info = root->fs_info;
7475 struct extent_map *em;
7476 struct btrfs_key ins;
7480 alloc_hint = get_extent_allocation_hint(inode, start, len);
7481 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7482 0, alloc_hint, &ins, 1, 1);
7484 return ERR_PTR(ret);
7486 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7487 ins.objectid, ins.offset, ins.offset,
7488 ins.offset, BTRFS_ORDERED_REGULAR);
7489 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7491 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7497 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7499 struct btrfs_block_group *block_group;
7500 bool readonly = false;
7502 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7503 if (!block_group || block_group->ro)
7506 btrfs_put_block_group(block_group);
7511 * Check if we can do nocow write into the range [@offset, @offset + @len)
7513 * @offset: File offset
7514 * @len: The length to write, will be updated to the nocow writeable
7516 * @orig_start: (optional) Return the original file offset of the file extent
7517 * @orig_len: (optional) Return the original on-disk length of the file extent
7518 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7519 * @strict: if true, omit optimizations that might force us into unnecessary
7520 * cow. e.g., don't trust generation number.
7523 * >0 and update @len if we can do nocow write
7524 * 0 if we can't do nocow write
7525 * <0 if error happened
7527 * NOTE: This only checks the file extents, caller is responsible to wait for
7528 * any ordered extents.
7530 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7531 u64 *orig_start, u64 *orig_block_len,
7532 u64 *ram_bytes, bool strict)
7534 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7535 struct btrfs_path *path;
7537 struct extent_buffer *leaf;
7538 struct btrfs_root *root = BTRFS_I(inode)->root;
7539 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7540 struct btrfs_file_extent_item *fi;
7541 struct btrfs_key key;
7548 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7550 path = btrfs_alloc_path();
7554 ret = btrfs_lookup_file_extent(NULL, root, path,
7555 btrfs_ino(BTRFS_I(inode)), offset, 0);
7559 slot = path->slots[0];
7562 /* can't find the item, must cow */
7569 leaf = path->nodes[0];
7570 btrfs_item_key_to_cpu(leaf, &key, slot);
7571 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7572 key.type != BTRFS_EXTENT_DATA_KEY) {
7573 /* not our file or wrong item type, must cow */
7577 if (key.offset > offset) {
7578 /* Wrong offset, must cow */
7582 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7583 found_type = btrfs_file_extent_type(leaf, fi);
7584 if (found_type != BTRFS_FILE_EXTENT_REG &&
7585 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7586 /* not a regular extent, must cow */
7590 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7593 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7594 if (extent_end <= offset)
7597 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7598 if (disk_bytenr == 0)
7601 if (btrfs_file_extent_compression(leaf, fi) ||
7602 btrfs_file_extent_encryption(leaf, fi) ||
7603 btrfs_file_extent_other_encoding(leaf, fi))
7607 * Do the same check as in btrfs_cross_ref_exist but without the
7608 * unnecessary search.
7611 (btrfs_file_extent_generation(leaf, fi) <=
7612 btrfs_root_last_snapshot(&root->root_item)))
7615 backref_offset = btrfs_file_extent_offset(leaf, fi);
7618 *orig_start = key.offset - backref_offset;
7619 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7620 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7623 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7626 num_bytes = min(offset + *len, extent_end) - offset;
7627 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7630 range_end = round_up(offset + num_bytes,
7631 root->fs_info->sectorsize) - 1;
7632 ret = test_range_bit(io_tree, offset, range_end,
7633 EXTENT_DELALLOC, 0, NULL);
7640 btrfs_release_path(path);
7643 * look for other files referencing this extent, if we
7644 * find any we must cow
7647 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7648 key.offset - backref_offset, disk_bytenr,
7656 * adjust disk_bytenr and num_bytes to cover just the bytes
7657 * in this extent we are about to write. If there
7658 * are any csums in that range we have to cow in order
7659 * to keep the csums correct
7661 disk_bytenr += backref_offset;
7662 disk_bytenr += offset - key.offset;
7663 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7666 * all of the above have passed, it is safe to overwrite this extent
7672 btrfs_free_path(path);
7676 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7677 struct extent_state **cached_state, bool writing)
7679 struct btrfs_ordered_extent *ordered;
7683 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7686 * We're concerned with the entire range that we're going to be
7687 * doing DIO to, so we need to make sure there's no ordered
7688 * extents in this range.
7690 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7691 lockend - lockstart + 1);
7694 * We need to make sure there are no buffered pages in this
7695 * range either, we could have raced between the invalidate in
7696 * generic_file_direct_write and locking the extent. The
7697 * invalidate needs to happen so that reads after a write do not
7701 (!writing || !filemap_range_has_page(inode->i_mapping,
7702 lockstart, lockend)))
7705 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7710 * If we are doing a DIO read and the ordered extent we
7711 * found is for a buffered write, we can not wait for it
7712 * to complete and retry, because if we do so we can
7713 * deadlock with concurrent buffered writes on page
7714 * locks. This happens only if our DIO read covers more
7715 * than one extent map, if at this point has already
7716 * created an ordered extent for a previous extent map
7717 * and locked its range in the inode's io tree, and a
7718 * concurrent write against that previous extent map's
7719 * range and this range started (we unlock the ranges
7720 * in the io tree only when the bios complete and
7721 * buffered writes always lock pages before attempting
7722 * to lock range in the io tree).
7725 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7726 btrfs_start_ordered_extent(ordered, 1);
7729 btrfs_put_ordered_extent(ordered);
7732 * We could trigger writeback for this range (and wait
7733 * for it to complete) and then invalidate the pages for
7734 * this range (through invalidate_inode_pages2_range()),
7735 * but that can lead us to a deadlock with a concurrent
7736 * call to readahead (a buffered read or a defrag call
7737 * triggered a readahead) on a page lock due to an
7738 * ordered dio extent we created before but did not have
7739 * yet a corresponding bio submitted (whence it can not
7740 * complete), which makes readahead wait for that
7741 * ordered extent to complete while holding a lock on
7756 /* The callers of this must take lock_extent() */
7757 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7758 u64 len, u64 orig_start, u64 block_start,
7759 u64 block_len, u64 orig_block_len,
7760 u64 ram_bytes, int compress_type,
7763 struct extent_map_tree *em_tree;
7764 struct extent_map *em;
7767 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7768 type == BTRFS_ORDERED_COMPRESSED ||
7769 type == BTRFS_ORDERED_NOCOW ||
7770 type == BTRFS_ORDERED_REGULAR);
7772 em_tree = &inode->extent_tree;
7773 em = alloc_extent_map();
7775 return ERR_PTR(-ENOMEM);
7778 em->orig_start = orig_start;
7780 em->block_len = block_len;
7781 em->block_start = block_start;
7782 em->orig_block_len = orig_block_len;
7783 em->ram_bytes = ram_bytes;
7784 em->generation = -1;
7785 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7786 if (type == BTRFS_ORDERED_PREALLOC) {
7787 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7788 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7789 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7790 em->compress_type = compress_type;
7794 btrfs_drop_extent_cache(inode, em->start,
7795 em->start + em->len - 1, 0);
7796 write_lock(&em_tree->lock);
7797 ret = add_extent_mapping(em_tree, em, 1);
7798 write_unlock(&em_tree->lock);
7800 * The caller has taken lock_extent(), who could race with us
7803 } while (ret == -EEXIST);
7806 free_extent_map(em);
7807 return ERR_PTR(ret);
7810 /* em got 2 refs now, callers needs to do free_extent_map once. */
7815 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7816 struct inode *inode,
7817 struct btrfs_dio_data *dio_data,
7820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7821 struct extent_map *em = *map;
7823 u64 block_start, orig_start, orig_block_len, ram_bytes;
7824 bool can_nocow = false;
7825 bool space_reserved = false;
7830 * We don't allocate a new extent in the following cases
7832 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7834 * 2) The extent is marked as PREALLOC. We're good to go here and can
7835 * just use the extent.
7838 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7839 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7840 em->block_start != EXTENT_MAP_HOLE)) {
7841 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7842 type = BTRFS_ORDERED_PREALLOC;
7844 type = BTRFS_ORDERED_NOCOW;
7845 len = min(len, em->len - (start - em->start));
7846 block_start = em->block_start + (start - em->start);
7848 if (can_nocow_extent(inode, start, &len, &orig_start,
7849 &orig_block_len, &ram_bytes, false) == 1 &&
7850 btrfs_inc_nocow_writers(fs_info, block_start))
7856 struct extent_map *em2;
7858 /* We can NOCOW, so only need to reserve metadata space. */
7859 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
7861 /* Our caller expects us to free the input extent map. */
7862 free_extent_map(em);
7864 btrfs_dec_nocow_writers(fs_info, block_start);
7867 space_reserved = true;
7869 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7870 orig_start, block_start,
7871 len, orig_block_len,
7873 btrfs_dec_nocow_writers(fs_info, block_start);
7874 if (type == BTRFS_ORDERED_PREALLOC) {
7875 free_extent_map(em);
7884 /* Our caller expects us to free the input extent map. */
7885 free_extent_map(em);
7888 /* We have to COW, so need to reserve metadata and data space. */
7889 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7890 &dio_data->data_reserved,
7894 space_reserved = true;
7896 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7902 len = min(len, em->len - (start - em->start));
7904 btrfs_delalloc_release_space(BTRFS_I(inode),
7905 dio_data->data_reserved,
7906 start + len, prev_len - len,
7911 * We have created our ordered extent, so we can now release our reservation
7912 * for an outstanding extent.
7914 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7917 * Need to update the i_size under the extent lock so buffered
7918 * readers will get the updated i_size when we unlock.
7920 if (start + len > i_size_read(inode))
7921 i_size_write(inode, start + len);
7923 if (ret && space_reserved) {
7924 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7926 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7928 btrfs_delalloc_release_space(BTRFS_I(inode),
7929 dio_data->data_reserved,
7931 extent_changeset_free(dio_data->data_reserved);
7932 dio_data->data_reserved = NULL;
7938 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7939 loff_t length, unsigned int flags, struct iomap *iomap,
7940 struct iomap *srcmap)
7942 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7943 struct extent_map *em;
7944 struct extent_state *cached_state = NULL;
7945 struct btrfs_dio_data *dio_data = NULL;
7946 u64 lockstart, lockend;
7947 const bool write = !!(flags & IOMAP_WRITE);
7950 bool unlock_extents = false;
7953 len = min_t(u64, len, fs_info->sectorsize);
7956 lockend = start + len - 1;
7959 * The generic stuff only does filemap_write_and_wait_range, which
7960 * isn't enough if we've written compressed pages to this area, so we
7961 * need to flush the dirty pages again to make absolutely sure that any
7962 * outstanding dirty pages are on disk.
7964 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7965 &BTRFS_I(inode)->runtime_flags)) {
7966 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7967 start + length - 1);
7972 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7976 iomap->private = dio_data;
7980 * If this errors out it's because we couldn't invalidate pagecache for
7981 * this range and we need to fallback to buffered.
7983 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7988 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7995 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7996 * io. INLINE is special, and we could probably kludge it in here, but
7997 * it's still buffered so for safety lets just fall back to the generic
8000 * For COMPRESSED we _have_ to read the entire extent in so we can
8001 * decompress it, so there will be buffering required no matter what we
8002 * do, so go ahead and fallback to buffered.
8004 * We return -ENOTBLK because that's what makes DIO go ahead and go back
8005 * to buffered IO. Don't blame me, this is the price we pay for using
8008 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
8009 em->block_start == EXTENT_MAP_INLINE) {
8010 free_extent_map(em);
8012 * If we are in a NOWAIT context, return -EAGAIN in order to
8013 * fallback to buffered IO. This is not only because we can
8014 * block with buffered IO (no support for NOWAIT semantics at
8015 * the moment) but also to avoid returning short reads to user
8016 * space - this happens if we were able to read some data from
8017 * previous non-compressed extents and then when we fallback to
8018 * buffered IO, at btrfs_file_read_iter() by calling
8019 * filemap_read(), we fail to fault in pages for the read buffer,
8020 * in which case filemap_read() returns a short read (the number
8021 * of bytes previously read is > 0, so it does not return -EFAULT).
8023 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
8027 len = min(len, em->len - (start - em->start));
8030 * If we have a NOWAIT request and the range contains multiple extents
8031 * (or a mix of extents and holes), then we return -EAGAIN to make the
8032 * caller fallback to a context where it can do a blocking (without
8033 * NOWAIT) request. This way we avoid doing partial IO and returning
8034 * success to the caller, which is not optimal for writes and for reads
8035 * it can result in unexpected behaviour for an application.
8037 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
8038 * iomap_dio_rw(), we can end up returning less data then what the caller
8039 * asked for, resulting in an unexpected, and incorrect, short read.
8040 * That is, the caller asked to read N bytes and we return less than that,
8041 * which is wrong unless we are crossing EOF. This happens if we get a
8042 * page fault error when trying to fault in pages for the buffer that is
8043 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
8044 * have previously submitted bios for other extents in the range, in
8045 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
8046 * those bios have completed by the time we get the page fault error,
8047 * which we return back to our caller - we should only return EIOCBQUEUED
8048 * after we have submitted bios for all the extents in the range.
8050 if ((flags & IOMAP_NOWAIT) && len < length) {
8051 free_extent_map(em);
8057 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
8061 unlock_extents = true;
8062 /* Recalc len in case the new em is smaller than requested */
8063 len = min(len, em->len - (start - em->start));
8066 * We need to unlock only the end area that we aren't using.
8067 * The rest is going to be unlocked by the endio routine.
8069 lockstart = start + len;
8070 if (lockstart < lockend)
8071 unlock_extents = true;
8075 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
8076 lockstart, lockend, &cached_state);
8078 free_extent_state(cached_state);
8081 * Translate extent map information to iomap.
8082 * We trim the extents (and move the addr) even though iomap code does
8083 * that, since we have locked only the parts we are performing I/O in.
8085 if ((em->block_start == EXTENT_MAP_HOLE) ||
8086 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
8087 iomap->addr = IOMAP_NULL_ADDR;
8088 iomap->type = IOMAP_HOLE;
8090 iomap->addr = em->block_start + (start - em->start);
8091 iomap->type = IOMAP_MAPPED;
8093 iomap->offset = start;
8094 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
8095 iomap->length = len;
8097 if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
8098 iomap->flags |= IOMAP_F_ZONE_APPEND;
8100 free_extent_map(em);
8105 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
8113 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
8114 ssize_t written, unsigned int flags, struct iomap *iomap)
8117 struct btrfs_dio_data *dio_data = iomap->private;
8118 size_t submitted = dio_data->submitted;
8119 const bool write = !!(flags & IOMAP_WRITE);
8121 if (!write && (iomap->type == IOMAP_HOLE)) {
8122 /* If reading from a hole, unlock and return */
8123 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
8127 if (submitted < length) {
8129 length -= submitted;
8131 __endio_write_update_ordered(BTRFS_I(inode), pos,
8134 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
8140 extent_changeset_free(dio_data->data_reserved);
8143 iomap->private = NULL;
8148 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
8151 * This implies a barrier so that stores to dio_bio->bi_status before
8152 * this and loads of dio_bio->bi_status after this are fully ordered.
8154 if (!refcount_dec_and_test(&dip->refs))
8157 if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
8158 __endio_write_update_ordered(BTRFS_I(dip->inode),
8159 dip->logical_offset,
8161 !dip->dio_bio->bi_status);
8163 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
8164 dip->logical_offset,
8165 dip->logical_offset + dip->bytes - 1);
8168 bio_endio(dip->dio_bio);
8172 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
8174 unsigned long bio_flags)
8176 struct btrfs_dio_private *dip = bio->bi_private;
8177 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8180 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
8182 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8186 refcount_inc(&dip->refs);
8187 ret = btrfs_map_bio(fs_info, bio, mirror_num);
8189 refcount_dec(&dip->refs);
8193 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
8194 struct btrfs_io_bio *io_bio,
8195 const bool uptodate)
8197 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
8198 const u32 sectorsize = fs_info->sectorsize;
8199 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
8200 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8201 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8202 struct bio_vec bvec;
8203 struct bvec_iter iter;
8204 u64 start = io_bio->logical;
8206 blk_status_t err = BLK_STS_OK;
8208 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
8209 unsigned int i, nr_sectors, pgoff;
8211 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8212 pgoff = bvec.bv_offset;
8213 for (i = 0; i < nr_sectors; i++) {
8214 ASSERT(pgoff < PAGE_SIZE);
8216 (!csum || !check_data_csum(inode, io_bio,
8217 bio_offset, bvec.bv_page,
8219 clean_io_failure(fs_info, failure_tree, io_tree,
8220 start, bvec.bv_page,
8221 btrfs_ino(BTRFS_I(inode)),
8226 ASSERT((start - io_bio->logical) < UINT_MAX);
8227 ret = btrfs_repair_one_sector(inode,
8229 start - io_bio->logical,
8230 bvec.bv_page, pgoff,
8231 start, io_bio->mirror_num,
8232 submit_dio_repair_bio);
8234 err = errno_to_blk_status(ret);
8236 start += sectorsize;
8237 ASSERT(bio_offset + sectorsize > bio_offset);
8238 bio_offset += sectorsize;
8239 pgoff += sectorsize;
8245 static void __endio_write_update_ordered(struct btrfs_inode *inode,
8246 const u64 offset, const u64 bytes,
8247 const bool uptodate)
8249 btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes,
8250 finish_ordered_fn, uptodate);
8253 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
8255 u64 dio_file_offset)
8257 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, 1);
8260 static void btrfs_end_dio_bio(struct bio *bio)
8262 struct btrfs_dio_private *dip = bio->bi_private;
8263 blk_status_t err = bio->bi_status;
8266 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8267 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8268 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8269 bio->bi_opf, bio->bi_iter.bi_sector,
8270 bio->bi_iter.bi_size, err);
8272 if (bio_op(bio) == REQ_OP_READ) {
8273 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
8278 dip->dio_bio->bi_status = err;
8280 btrfs_record_physical_zoned(dip->inode, dip->logical_offset, bio);
8283 btrfs_dio_private_put(dip);
8286 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8287 struct inode *inode, u64 file_offset, int async_submit)
8289 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8290 struct btrfs_dio_private *dip = bio->bi_private;
8291 bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
8294 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8296 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8299 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8304 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8307 if (write && async_submit) {
8308 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
8309 btrfs_submit_bio_start_direct_io);
8313 * If we aren't doing async submit, calculate the csum of the
8316 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
8322 csum_offset = file_offset - dip->logical_offset;
8323 csum_offset >>= fs_info->sectorsize_bits;
8324 csum_offset *= fs_info->csum_size;
8325 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
8328 ret = btrfs_map_bio(fs_info, bio, 0);
8334 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
8335 * or ordered extents whether or not we submit any bios.
8337 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
8338 struct inode *inode,
8341 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8342 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8344 struct btrfs_dio_private *dip;
8346 dip_size = sizeof(*dip);
8347 if (!write && csum) {
8348 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8351 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
8352 dip_size += fs_info->csum_size * nblocks;
8355 dip = kzalloc(dip_size, GFP_NOFS);
8360 dip->logical_offset = file_offset;
8361 dip->bytes = dio_bio->bi_iter.bi_size;
8362 dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
8363 dip->dio_bio = dio_bio;
8364 refcount_set(&dip->refs, 1);
8368 static blk_qc_t btrfs_submit_direct(const struct iomap_iter *iter,
8369 struct bio *dio_bio, loff_t file_offset)
8371 struct inode *inode = iter->inode;
8372 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8373 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8374 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8375 BTRFS_BLOCK_GROUP_RAID56_MASK);
8376 struct btrfs_dio_private *dip;
8379 int async_submit = 0;
8381 u64 clone_offset = 0;
8385 blk_status_t status;
8386 struct btrfs_io_geometry geom;
8387 struct btrfs_dio_data *dio_data = iter->iomap.private;
8388 struct extent_map *em = NULL;
8390 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
8393 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8394 file_offset + dio_bio->bi_iter.bi_size - 1);
8396 dio_bio->bi_status = BLK_STS_RESOURCE;
8398 return BLK_QC_T_NONE;
8403 * Load the csums up front to reduce csum tree searches and
8404 * contention when submitting bios.
8406 * If we have csums disabled this will do nothing.
8408 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8409 if (status != BLK_STS_OK)
8413 start_sector = dio_bio->bi_iter.bi_sector;
8414 submit_len = dio_bio->bi_iter.bi_size;
8417 logical = start_sector << 9;
8418 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8420 status = errno_to_blk_status(PTR_ERR(em));
8424 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8427 status = errno_to_blk_status(ret);
8431 clone_len = min(submit_len, geom.len);
8432 ASSERT(clone_len <= UINT_MAX);
8435 * This will never fail as it's passing GPF_NOFS and
8436 * the allocation is backed by btrfs_bioset.
8438 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8439 bio->bi_private = dip;
8440 bio->bi_end_io = btrfs_end_dio_bio;
8441 btrfs_io_bio(bio)->logical = file_offset;
8443 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8444 status = extract_ordered_extent(BTRFS_I(inode), bio,
8452 ASSERT(submit_len >= clone_len);
8453 submit_len -= clone_len;
8456 * Increase the count before we submit the bio so we know
8457 * the end IO handler won't happen before we increase the
8458 * count. Otherwise, the dip might get freed before we're
8459 * done setting it up.
8461 * We transfer the initial reference to the last bio, so we
8462 * don't need to increment the reference count for the last one.
8464 if (submit_len > 0) {
8465 refcount_inc(&dip->refs);
8467 * If we are submitting more than one bio, submit them
8468 * all asynchronously. The exception is RAID 5 or 6, as
8469 * asynchronous checksums make it difficult to collect
8470 * full stripe writes.
8476 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8481 refcount_dec(&dip->refs);
8485 dio_data->submitted += clone_len;
8486 clone_offset += clone_len;
8487 start_sector += clone_len >> 9;
8488 file_offset += clone_len;
8490 free_extent_map(em);
8491 } while (submit_len > 0);
8492 return BLK_QC_T_NONE;
8495 free_extent_map(em);
8497 dip->dio_bio->bi_status = status;
8498 btrfs_dio_private_put(dip);
8500 return BLK_QC_T_NONE;
8503 const struct iomap_ops btrfs_dio_iomap_ops = {
8504 .iomap_begin = btrfs_dio_iomap_begin,
8505 .iomap_end = btrfs_dio_iomap_end,
8508 const struct iomap_dio_ops btrfs_dio_ops = {
8509 .submit_io = btrfs_submit_direct,
8512 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8517 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8521 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8524 int btrfs_readpage(struct file *file, struct page *page)
8526 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8527 u64 start = page_offset(page);
8528 u64 end = start + PAGE_SIZE - 1;
8529 struct btrfs_bio_ctrl bio_ctrl = { 0 };
8532 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8534 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
8536 ret = submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags);
8540 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8542 struct inode *inode = page->mapping->host;
8545 if (current->flags & PF_MEMALLOC) {
8546 redirty_page_for_writepage(wbc, page);
8552 * If we are under memory pressure we will call this directly from the
8553 * VM, we need to make sure we have the inode referenced for the ordered
8554 * extent. If not just return like we didn't do anything.
8556 if (!igrab(inode)) {
8557 redirty_page_for_writepage(wbc, page);
8558 return AOP_WRITEPAGE_ACTIVATE;
8560 ret = extent_write_full_page(page, wbc);
8561 btrfs_add_delayed_iput(inode);
8565 static int btrfs_writepages(struct address_space *mapping,
8566 struct writeback_control *wbc)
8568 return extent_writepages(mapping, wbc);
8571 static void btrfs_readahead(struct readahead_control *rac)
8573 extent_readahead(rac);
8577 * For releasepage() and invalidatepage() we have a race window where
8578 * end_page_writeback() is called but the subpage spinlock is not yet released.
8579 * If we continue to release/invalidate the page, we could cause use-after-free
8580 * for subpage spinlock. So this function is to spin and wait for subpage
8583 static void wait_subpage_spinlock(struct page *page)
8585 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
8586 struct btrfs_subpage *subpage;
8588 if (fs_info->sectorsize == PAGE_SIZE)
8591 ASSERT(PagePrivate(page) && page->private);
8592 subpage = (struct btrfs_subpage *)page->private;
8595 * This may look insane as we just acquire the spinlock and release it,
8596 * without doing anything. But we just want to make sure no one is
8597 * still holding the subpage spinlock.
8598 * And since the page is not dirty nor writeback, and we have page
8599 * locked, the only possible way to hold a spinlock is from the endio
8600 * function to clear page writeback.
8602 * Here we just acquire the spinlock so that all existing callers
8603 * should exit and we're safe to release/invalidate the page.
8605 spin_lock_irq(&subpage->lock);
8606 spin_unlock_irq(&subpage->lock);
8609 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8611 int ret = try_release_extent_mapping(page, gfp_flags);
8614 wait_subpage_spinlock(page);
8615 clear_page_extent_mapped(page);
8620 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8622 if (PageWriteback(page) || PageDirty(page))
8624 return __btrfs_releasepage(page, gfp_flags);
8627 #ifdef CONFIG_MIGRATION
8628 static int btrfs_migratepage(struct address_space *mapping,
8629 struct page *newpage, struct page *page,
8630 enum migrate_mode mode)
8634 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8635 if (ret != MIGRATEPAGE_SUCCESS)
8638 if (page_has_private(page))
8639 attach_page_private(newpage, detach_page_private(page));
8641 if (PageOrdered(page)) {
8642 ClearPageOrdered(page);
8643 SetPageOrdered(newpage);
8646 if (mode != MIGRATE_SYNC_NO_COPY)
8647 migrate_page_copy(newpage, page);
8649 migrate_page_states(newpage, page);
8650 return MIGRATEPAGE_SUCCESS;
8654 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8655 unsigned int length)
8657 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8658 struct btrfs_fs_info *fs_info = inode->root->fs_info;
8659 struct extent_io_tree *tree = &inode->io_tree;
8660 struct extent_state *cached_state = NULL;
8661 u64 page_start = page_offset(page);
8662 u64 page_end = page_start + PAGE_SIZE - 1;
8664 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8667 * We have page locked so no new ordered extent can be created on this
8668 * page, nor bio can be submitted for this page.
8670 * But already submitted bio can still be finished on this page.
8671 * Furthermore, endio function won't skip page which has Ordered
8672 * (Private2) already cleared, so it's possible for endio and
8673 * invalidatepage to do the same ordered extent accounting twice
8676 * So here we wait for any submitted bios to finish, so that we won't
8677 * do double ordered extent accounting on the same page.
8679 wait_on_page_writeback(page);
8680 wait_subpage_spinlock(page);
8683 * For subpage case, we have call sites like
8684 * btrfs_punch_hole_lock_range() which passes range not aligned to
8686 * If the range doesn't cover the full page, we don't need to and
8687 * shouldn't clear page extent mapped, as page->private can still
8688 * record subpage dirty bits for other part of the range.
8690 * For cases that can invalidate the full even the range doesn't
8691 * cover the full page, like invalidating the last page, we're
8692 * still safe to wait for ordered extent to finish.
8694 if (!(offset == 0 && length == PAGE_SIZE)) {
8695 btrfs_releasepage(page, GFP_NOFS);
8699 if (!inode_evicting)
8700 lock_extent_bits(tree, page_start, page_end, &cached_state);
8703 while (cur < page_end) {
8704 struct btrfs_ordered_extent *ordered;
8709 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8710 page_end + 1 - cur);
8712 range_end = page_end;
8714 * No ordered extent covering this range, we are safe
8715 * to delete all extent states in the range.
8717 delete_states = true;
8720 if (ordered->file_offset > cur) {
8722 * There is a range between [cur, oe->file_offset) not
8723 * covered by any ordered extent.
8724 * We are safe to delete all extent states, and handle
8725 * the ordered extent in the next iteration.
8727 range_end = ordered->file_offset - 1;
8728 delete_states = true;
8732 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8734 ASSERT(range_end + 1 - cur < U32_MAX);
8735 range_len = range_end + 1 - cur;
8736 if (!btrfs_page_test_ordered(fs_info, page, cur, range_len)) {
8738 * If Ordered (Private2) is cleared, it means endio has
8739 * already been executed for the range.
8740 * We can't delete the extent states as
8741 * btrfs_finish_ordered_io() may still use some of them.
8743 delete_states = false;
8746 btrfs_page_clear_ordered(fs_info, page, cur, range_len);
8749 * IO on this page will never be started, so we need to account
8750 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8751 * here, must leave that up for the ordered extent completion.
8753 * This will also unlock the range for incoming
8754 * btrfs_finish_ordered_io().
8756 if (!inode_evicting)
8757 clear_extent_bit(tree, cur, range_end,
8759 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8760 EXTENT_DEFRAG, 1, 0, &cached_state);
8762 spin_lock_irq(&inode->ordered_tree.lock);
8763 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8764 ordered->truncated_len = min(ordered->truncated_len,
8765 cur - ordered->file_offset);
8766 spin_unlock_irq(&inode->ordered_tree.lock);
8768 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8769 cur, range_end + 1 - cur)) {
8770 btrfs_finish_ordered_io(ordered);
8772 * The ordered extent has finished, now we're again
8773 * safe to delete all extent states of the range.
8775 delete_states = true;
8778 * btrfs_finish_ordered_io() will get executed by endio
8779 * of other pages, thus we can't delete extent states
8782 delete_states = false;
8786 btrfs_put_ordered_extent(ordered);
8788 * Qgroup reserved space handler
8789 * Sector(s) here will be either:
8791 * 1) Already written to disk or bio already finished
8792 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8793 * Qgroup will be handled by its qgroup_record then.
8794 * btrfs_qgroup_free_data() call will do nothing here.
8796 * 2) Not written to disk yet
8797 * Then btrfs_qgroup_free_data() call will clear the
8798 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8799 * reserved data space.
8800 * Since the IO will never happen for this page.
8802 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8803 if (!inode_evicting) {
8804 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8805 EXTENT_DELALLOC | EXTENT_UPTODATE |
8806 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8807 delete_states, &cached_state);
8809 cur = range_end + 1;
8812 * We have iterated through all ordered extents of the page, the page
8813 * should not have Ordered (Private2) anymore, or the above iteration
8814 * did something wrong.
8816 ASSERT(!PageOrdered(page));
8817 if (!inode_evicting)
8818 __btrfs_releasepage(page, GFP_NOFS);
8819 ClearPageChecked(page);
8820 clear_page_extent_mapped(page);
8824 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8825 * called from a page fault handler when a page is first dirtied. Hence we must
8826 * be careful to check for EOF conditions here. We set the page up correctly
8827 * for a written page which means we get ENOSPC checking when writing into
8828 * holes and correct delalloc and unwritten extent mapping on filesystems that
8829 * support these features.
8831 * We are not allowed to take the i_mutex here so we have to play games to
8832 * protect against truncate races as the page could now be beyond EOF. Because
8833 * truncate_setsize() writes the inode size before removing pages, once we have
8834 * the page lock we can determine safely if the page is beyond EOF. If it is not
8835 * beyond EOF, then the page is guaranteed safe against truncation until we
8838 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8840 struct page *page = vmf->page;
8841 struct inode *inode = file_inode(vmf->vma->vm_file);
8842 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8843 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8844 struct btrfs_ordered_extent *ordered;
8845 struct extent_state *cached_state = NULL;
8846 struct extent_changeset *data_reserved = NULL;
8847 unsigned long zero_start;
8857 reserved_space = PAGE_SIZE;
8859 sb_start_pagefault(inode->i_sb);
8860 page_start = page_offset(page);
8861 page_end = page_start + PAGE_SIZE - 1;
8865 * Reserving delalloc space after obtaining the page lock can lead to
8866 * deadlock. For example, if a dirty page is locked by this function
8867 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8868 * dirty page write out, then the btrfs_writepage() function could
8869 * end up waiting indefinitely to get a lock on the page currently
8870 * being processed by btrfs_page_mkwrite() function.
8872 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8873 page_start, reserved_space);
8875 ret2 = file_update_time(vmf->vma->vm_file);
8879 ret = vmf_error(ret2);
8885 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8887 down_read(&BTRFS_I(inode)->i_mmap_lock);
8889 size = i_size_read(inode);
8891 if ((page->mapping != inode->i_mapping) ||
8892 (page_start >= size)) {
8893 /* page got truncated out from underneath us */
8896 wait_on_page_writeback(page);
8898 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8899 ret2 = set_page_extent_mapped(page);
8901 ret = vmf_error(ret2);
8902 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8907 * we can't set the delalloc bits if there are pending ordered
8908 * extents. Drop our locks and wait for them to finish
8910 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8913 unlock_extent_cached(io_tree, page_start, page_end,
8916 up_read(&BTRFS_I(inode)->i_mmap_lock);
8917 btrfs_start_ordered_extent(ordered, 1);
8918 btrfs_put_ordered_extent(ordered);
8922 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8923 reserved_space = round_up(size - page_start,
8924 fs_info->sectorsize);
8925 if (reserved_space < PAGE_SIZE) {
8926 end = page_start + reserved_space - 1;
8927 btrfs_delalloc_release_space(BTRFS_I(inode),
8928 data_reserved, page_start,
8929 PAGE_SIZE - reserved_space, true);
8934 * page_mkwrite gets called when the page is firstly dirtied after it's
8935 * faulted in, but write(2) could also dirty a page and set delalloc
8936 * bits, thus in this case for space account reason, we still need to
8937 * clear any delalloc bits within this page range since we have to
8938 * reserve data&meta space before lock_page() (see above comments).
8940 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8941 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8942 EXTENT_DEFRAG, 0, 0, &cached_state);
8944 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8947 unlock_extent_cached(io_tree, page_start, page_end,
8949 ret = VM_FAULT_SIGBUS;
8953 /* page is wholly or partially inside EOF */
8954 if (page_start + PAGE_SIZE > size)
8955 zero_start = offset_in_page(size);
8957 zero_start = PAGE_SIZE;
8959 if (zero_start != PAGE_SIZE) {
8960 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8961 flush_dcache_page(page);
8963 ClearPageChecked(page);
8964 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8965 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8967 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8969 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8970 up_read(&BTRFS_I(inode)->i_mmap_lock);
8972 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8973 sb_end_pagefault(inode->i_sb);
8974 extent_changeset_free(data_reserved);
8975 return VM_FAULT_LOCKED;
8979 up_read(&BTRFS_I(inode)->i_mmap_lock);
8981 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8982 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8983 reserved_space, (ret != 0));
8985 sb_end_pagefault(inode->i_sb);
8986 extent_changeset_free(data_reserved);
8990 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8992 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8993 struct btrfs_root *root = BTRFS_I(inode)->root;
8994 struct btrfs_block_rsv *rsv;
8996 struct btrfs_trans_handle *trans;
8997 u64 mask = fs_info->sectorsize - 1;
8998 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8999 u64 extents_found = 0;
9001 if (!skip_writeback) {
9002 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9009 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9010 * things going on here:
9012 * 1) We need to reserve space to update our inode.
9014 * 2) We need to have something to cache all the space that is going to
9015 * be free'd up by the truncate operation, but also have some slack
9016 * space reserved in case it uses space during the truncate (thank you
9017 * very much snapshotting).
9019 * And we need these to be separate. The fact is we can use a lot of
9020 * space doing the truncate, and we have no earthly idea how much space
9021 * we will use, so we need the truncate reservation to be separate so it
9022 * doesn't end up using space reserved for updating the inode. We also
9023 * need to be able to stop the transaction and start a new one, which
9024 * means we need to be able to update the inode several times, and we
9025 * have no idea of knowing how many times that will be, so we can't just
9026 * reserve 1 item for the entirety of the operation, so that has to be
9027 * done separately as well.
9029 * So that leaves us with
9031 * 1) rsv - for the truncate reservation, which we will steal from the
9032 * transaction reservation.
9033 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9034 * updating the inode.
9036 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9039 rsv->size = min_size;
9043 * 1 for the truncate slack space
9044 * 1 for updating the inode.
9046 trans = btrfs_start_transaction(root, 2);
9047 if (IS_ERR(trans)) {
9048 ret = PTR_ERR(trans);
9052 /* Migrate the slack space for the truncate to our reserve */
9053 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9057 trans->block_rsv = rsv;
9060 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
9062 BTRFS_EXTENT_DATA_KEY,
9064 trans->block_rsv = &fs_info->trans_block_rsv;
9065 if (ret != -ENOSPC && ret != -EAGAIN)
9068 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9072 btrfs_end_transaction(trans);
9073 btrfs_btree_balance_dirty(fs_info);
9075 trans = btrfs_start_transaction(root, 2);
9076 if (IS_ERR(trans)) {
9077 ret = PTR_ERR(trans);
9082 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
9083 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9084 rsv, min_size, false);
9085 BUG_ON(ret); /* shouldn't happen */
9086 trans->block_rsv = rsv;
9090 * We can't call btrfs_truncate_block inside a trans handle as we could
9091 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9092 * we've truncated everything except the last little bit, and can do
9093 * btrfs_truncate_block and then update the disk_i_size.
9095 if (ret == NEED_TRUNCATE_BLOCK) {
9096 btrfs_end_transaction(trans);
9097 btrfs_btree_balance_dirty(fs_info);
9099 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
9102 trans = btrfs_start_transaction(root, 1);
9103 if (IS_ERR(trans)) {
9104 ret = PTR_ERR(trans);
9107 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9113 trans->block_rsv = &fs_info->trans_block_rsv;
9114 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
9118 ret2 = btrfs_end_transaction(trans);
9121 btrfs_btree_balance_dirty(fs_info);
9124 btrfs_free_block_rsv(fs_info, rsv);
9126 * So if we truncate and then write and fsync we normally would just
9127 * write the extents that changed, which is a problem if we need to
9128 * first truncate that entire inode. So set this flag so we write out
9129 * all of the extents in the inode to the sync log so we're completely
9132 * If no extents were dropped or trimmed we don't need to force the next
9133 * fsync to truncate all the inode's items from the log and re-log them
9134 * all. This means the truncate operation did not change the file size,
9135 * or changed it to a smaller size but there was only an implicit hole
9136 * between the old i_size and the new i_size, and there were no prealloc
9137 * extents beyond i_size to drop.
9139 if (extents_found > 0)
9140 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9146 * create a new subvolume directory/inode (helper for the ioctl).
9148 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9149 struct btrfs_root *new_root,
9150 struct btrfs_root *parent_root,
9151 struct user_namespace *mnt_userns)
9153 struct inode *inode;
9158 err = btrfs_get_free_objectid(new_root, &ino);
9162 inode = btrfs_new_inode(trans, new_root, mnt_userns, NULL, "..", 2,
9164 S_IFDIR | (~current_umask() & S_IRWXUGO),
9167 return PTR_ERR(inode);
9168 inode->i_op = &btrfs_dir_inode_operations;
9169 inode->i_fop = &btrfs_dir_file_operations;
9171 set_nlink(inode, 1);
9172 btrfs_i_size_write(BTRFS_I(inode), 0);
9173 unlock_new_inode(inode);
9175 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9177 btrfs_err(new_root->fs_info,
9178 "error inheriting subvolume %llu properties: %d",
9179 new_root->root_key.objectid, err);
9181 err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
9187 struct inode *btrfs_alloc_inode(struct super_block *sb)
9189 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9190 struct btrfs_inode *ei;
9191 struct inode *inode;
9193 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9200 ei->last_sub_trans = 0;
9201 ei->logged_trans = 0;
9202 ei->delalloc_bytes = 0;
9203 ei->new_delalloc_bytes = 0;
9204 ei->defrag_bytes = 0;
9205 ei->disk_i_size = 0;
9209 ei->index_cnt = (u64)-1;
9211 ei->last_unlink_trans = 0;
9212 ei->last_reflink_trans = 0;
9213 ei->last_log_commit = 0;
9215 spin_lock_init(&ei->lock);
9216 ei->outstanding_extents = 0;
9217 if (sb->s_magic != BTRFS_TEST_MAGIC)
9218 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9219 BTRFS_BLOCK_RSV_DELALLOC);
9220 ei->runtime_flags = 0;
9221 ei->prop_compress = BTRFS_COMPRESS_NONE;
9222 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9224 ei->delayed_node = NULL;
9226 ei->i_otime.tv_sec = 0;
9227 ei->i_otime.tv_nsec = 0;
9229 inode = &ei->vfs_inode;
9230 extent_map_tree_init(&ei->extent_tree);
9231 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9232 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9233 IO_TREE_INODE_IO_FAILURE, inode);
9234 extent_io_tree_init(fs_info, &ei->file_extent_tree,
9235 IO_TREE_INODE_FILE_EXTENT, inode);
9236 ei->io_tree.track_uptodate = true;
9237 ei->io_failure_tree.track_uptodate = true;
9238 atomic_set(&ei->sync_writers, 0);
9239 mutex_init(&ei->log_mutex);
9240 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9241 INIT_LIST_HEAD(&ei->delalloc_inodes);
9242 INIT_LIST_HEAD(&ei->delayed_iput);
9243 RB_CLEAR_NODE(&ei->rb_node);
9244 init_rwsem(&ei->i_mmap_lock);
9249 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9250 void btrfs_test_destroy_inode(struct inode *inode)
9252 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9253 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9257 void btrfs_free_inode(struct inode *inode)
9259 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9262 void btrfs_destroy_inode(struct inode *vfs_inode)
9264 struct btrfs_ordered_extent *ordered;
9265 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
9266 struct btrfs_root *root = inode->root;
9268 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
9269 WARN_ON(vfs_inode->i_data.nrpages);
9270 WARN_ON(inode->block_rsv.reserved);
9271 WARN_ON(inode->block_rsv.size);
9272 WARN_ON(inode->outstanding_extents);
9273 WARN_ON(inode->delalloc_bytes);
9274 WARN_ON(inode->new_delalloc_bytes);
9275 WARN_ON(inode->csum_bytes);
9276 WARN_ON(inode->defrag_bytes);
9279 * This can happen where we create an inode, but somebody else also
9280 * created the same inode and we need to destroy the one we already
9287 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9291 btrfs_err(root->fs_info,
9292 "found ordered extent %llu %llu on inode cleanup",
9293 ordered->file_offset, ordered->num_bytes);
9294 btrfs_remove_ordered_extent(inode, ordered);
9295 btrfs_put_ordered_extent(ordered);
9296 btrfs_put_ordered_extent(ordered);
9299 btrfs_qgroup_check_reserved_leak(inode);
9300 inode_tree_del(inode);
9301 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9302 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
9303 btrfs_put_root(inode->root);
9306 int btrfs_drop_inode(struct inode *inode)
9308 struct btrfs_root *root = BTRFS_I(inode)->root;
9313 /* the snap/subvol tree is on deleting */
9314 if (btrfs_root_refs(&root->root_item) == 0)
9317 return generic_drop_inode(inode);
9320 static void init_once(void *foo)
9322 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9324 inode_init_once(&ei->vfs_inode);
9327 void __cold btrfs_destroy_cachep(void)
9330 * Make sure all delayed rcu free inodes are flushed before we
9334 kmem_cache_destroy(btrfs_inode_cachep);
9335 kmem_cache_destroy(btrfs_trans_handle_cachep);
9336 kmem_cache_destroy(btrfs_path_cachep);
9337 kmem_cache_destroy(btrfs_free_space_cachep);
9338 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
9341 int __init btrfs_init_cachep(void)
9343 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9344 sizeof(struct btrfs_inode), 0,
9345 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9347 if (!btrfs_inode_cachep)
9350 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9351 sizeof(struct btrfs_trans_handle), 0,
9352 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9353 if (!btrfs_trans_handle_cachep)
9356 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9357 sizeof(struct btrfs_path), 0,
9358 SLAB_MEM_SPREAD, NULL);
9359 if (!btrfs_path_cachep)
9362 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9363 sizeof(struct btrfs_free_space), 0,
9364 SLAB_MEM_SPREAD, NULL);
9365 if (!btrfs_free_space_cachep)
9368 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9369 PAGE_SIZE, PAGE_SIZE,
9370 SLAB_MEM_SPREAD, NULL);
9371 if (!btrfs_free_space_bitmap_cachep)
9376 btrfs_destroy_cachep();
9380 static int btrfs_getattr(struct user_namespace *mnt_userns,
9381 const struct path *path, struct kstat *stat,
9382 u32 request_mask, unsigned int flags)
9386 struct inode *inode = d_inode(path->dentry);
9387 u32 blocksize = inode->i_sb->s_blocksize;
9388 u32 bi_flags = BTRFS_I(inode)->flags;
9389 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
9391 stat->result_mask |= STATX_BTIME;
9392 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9393 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9394 if (bi_flags & BTRFS_INODE_APPEND)
9395 stat->attributes |= STATX_ATTR_APPEND;
9396 if (bi_flags & BTRFS_INODE_COMPRESS)
9397 stat->attributes |= STATX_ATTR_COMPRESSED;
9398 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9399 stat->attributes |= STATX_ATTR_IMMUTABLE;
9400 if (bi_flags & BTRFS_INODE_NODUMP)
9401 stat->attributes |= STATX_ATTR_NODUMP;
9402 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
9403 stat->attributes |= STATX_ATTR_VERITY;
9405 stat->attributes_mask |= (STATX_ATTR_APPEND |
9406 STATX_ATTR_COMPRESSED |
9407 STATX_ATTR_IMMUTABLE |
9410 generic_fillattr(mnt_userns, inode, stat);
9411 stat->dev = BTRFS_I(inode)->root->anon_dev;
9413 spin_lock(&BTRFS_I(inode)->lock);
9414 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9415 inode_bytes = inode_get_bytes(inode);
9416 spin_unlock(&BTRFS_I(inode)->lock);
9417 stat->blocks = (ALIGN(inode_bytes, blocksize) +
9418 ALIGN(delalloc_bytes, blocksize)) >> 9;
9422 static int btrfs_rename_exchange(struct inode *old_dir,
9423 struct dentry *old_dentry,
9424 struct inode *new_dir,
9425 struct dentry *new_dentry)
9427 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9428 struct btrfs_trans_handle *trans;
9429 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9430 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9431 struct inode *new_inode = new_dentry->d_inode;
9432 struct inode *old_inode = old_dentry->d_inode;
9433 struct timespec64 ctime = current_time(old_inode);
9434 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9435 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9440 bool root_log_pinned = false;
9441 bool dest_log_pinned = false;
9442 bool need_abort = false;
9445 * For non-subvolumes allow exchange only within one subvolume, in the
9446 * same inode namespace. Two subvolumes (represented as directory) can
9447 * be exchanged as they're a logical link and have a fixed inode number.
9450 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9451 new_ino != BTRFS_FIRST_FREE_OBJECTID))
9454 /* close the race window with snapshot create/destroy ioctl */
9455 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9456 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9457 down_read(&fs_info->subvol_sem);
9460 * We want to reserve the absolute worst case amount of items. So if
9461 * both inodes are subvols and we need to unlink them then that would
9462 * require 4 item modifications, but if they are both normal inodes it
9463 * would require 5 item modifications, so we'll assume their normal
9464 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9465 * should cover the worst case number of items we'll modify.
9467 trans = btrfs_start_transaction(root, 12);
9468 if (IS_ERR(trans)) {
9469 ret = PTR_ERR(trans);
9474 ret = btrfs_record_root_in_trans(trans, dest);
9480 * We need to find a free sequence number both in the source and
9481 * in the destination directory for the exchange.
9483 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9486 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9490 BTRFS_I(old_inode)->dir_index = 0ULL;
9491 BTRFS_I(new_inode)->dir_index = 0ULL;
9493 /* Reference for the source. */
9494 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9495 /* force full log commit if subvolume involved. */
9496 btrfs_set_log_full_commit(trans);
9498 ret = btrfs_insert_inode_ref(trans, dest,
9499 new_dentry->d_name.name,
9500 new_dentry->d_name.len,
9502 btrfs_ino(BTRFS_I(new_dir)),
9509 /* And now for the dest. */
9510 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9511 /* force full log commit if subvolume involved. */
9512 btrfs_set_log_full_commit(trans);
9514 ret = btrfs_insert_inode_ref(trans, root,
9515 old_dentry->d_name.name,
9516 old_dentry->d_name.len,
9518 btrfs_ino(BTRFS_I(old_dir)),
9522 btrfs_abort_transaction(trans, ret);
9527 /* Update inode version and ctime/mtime. */
9528 inode_inc_iversion(old_dir);
9529 inode_inc_iversion(new_dir);
9530 inode_inc_iversion(old_inode);
9531 inode_inc_iversion(new_inode);
9532 old_dir->i_ctime = old_dir->i_mtime = ctime;
9533 new_dir->i_ctime = new_dir->i_mtime = ctime;
9534 old_inode->i_ctime = ctime;
9535 new_inode->i_ctime = ctime;
9537 if (old_dentry->d_parent != new_dentry->d_parent) {
9538 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9539 BTRFS_I(old_inode), 1);
9540 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9541 BTRFS_I(new_inode), 1);
9545 * Now pin the logs of the roots. We do it to ensure that no other task
9546 * can sync the logs while we are in progress with the rename, because
9547 * that could result in an inconsistency in case any of the inodes that
9548 * are part of this rename operation were logged before.
9550 * We pin the logs even if at this precise moment none of the inodes was
9551 * logged before. This is because right after we checked for that, some
9552 * other task fsyncing some other inode not involved with this rename
9553 * operation could log that one of our inodes exists.
9555 * We don't need to pin the logs before the above calls to
9556 * btrfs_insert_inode_ref(), since those don't ever need to change a log.
9558 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
9559 btrfs_pin_log_trans(root);
9560 root_log_pinned = true;
9562 if (new_ino != BTRFS_FIRST_FREE_OBJECTID) {
9563 btrfs_pin_log_trans(dest);
9564 dest_log_pinned = true;
9567 /* src is a subvolume */
9568 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9569 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9570 } else { /* src is an inode */
9571 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9572 BTRFS_I(old_dentry->d_inode),
9573 old_dentry->d_name.name,
9574 old_dentry->d_name.len);
9576 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9579 btrfs_abort_transaction(trans, ret);
9583 /* dest is a subvolume */
9584 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9585 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9586 } else { /* dest is an inode */
9587 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9588 BTRFS_I(new_dentry->d_inode),
9589 new_dentry->d_name.name,
9590 new_dentry->d_name.len);
9592 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9595 btrfs_abort_transaction(trans, ret);
9599 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9600 new_dentry->d_name.name,
9601 new_dentry->d_name.len, 0, old_idx);
9603 btrfs_abort_transaction(trans, ret);
9607 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9608 old_dentry->d_name.name,
9609 old_dentry->d_name.len, 0, new_idx);
9611 btrfs_abort_transaction(trans, ret);
9615 if (old_inode->i_nlink == 1)
9616 BTRFS_I(old_inode)->dir_index = old_idx;
9617 if (new_inode->i_nlink == 1)
9618 BTRFS_I(new_inode)->dir_index = new_idx;
9620 if (root_log_pinned) {
9621 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9622 new_dentry->d_parent);
9623 btrfs_end_log_trans(root);
9624 root_log_pinned = false;
9626 if (dest_log_pinned) {
9627 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
9628 old_dentry->d_parent);
9629 btrfs_end_log_trans(dest);
9630 dest_log_pinned = false;
9634 * If we have pinned a log and an error happened, we unpin tasks
9635 * trying to sync the log and force them to fallback to a transaction
9636 * commit if the log currently contains any of the inodes involved in
9637 * this rename operation (to ensure we do not persist a log with an
9638 * inconsistent state for any of these inodes or leading to any
9639 * inconsistencies when replayed). If the transaction was aborted, the
9640 * abortion reason is propagated to userspace when attempting to commit
9641 * the transaction. If the log does not contain any of these inodes, we
9642 * allow the tasks to sync it.
9644 if (ret && (root_log_pinned || dest_log_pinned)) {
9645 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9646 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9647 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9648 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation))
9649 btrfs_set_log_full_commit(trans);
9651 if (root_log_pinned) {
9652 btrfs_end_log_trans(root);
9653 root_log_pinned = false;
9655 if (dest_log_pinned) {
9656 btrfs_end_log_trans(dest);
9657 dest_log_pinned = false;
9660 ret2 = btrfs_end_transaction(trans);
9661 ret = ret ? ret : ret2;
9663 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9664 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9665 up_read(&fs_info->subvol_sem);
9670 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9671 struct btrfs_root *root,
9672 struct user_namespace *mnt_userns,
9674 struct dentry *dentry)
9677 struct inode *inode;
9681 ret = btrfs_get_free_objectid(root, &objectid);
9685 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
9686 dentry->d_name.name,
9688 btrfs_ino(BTRFS_I(dir)),
9690 S_IFCHR | WHITEOUT_MODE,
9693 if (IS_ERR(inode)) {
9694 ret = PTR_ERR(inode);
9698 inode->i_op = &btrfs_special_inode_operations;
9699 init_special_inode(inode, inode->i_mode,
9702 ret = btrfs_init_inode_security(trans, inode, dir,
9707 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9708 BTRFS_I(inode), 0, index);
9712 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9714 unlock_new_inode(inode);
9716 inode_dec_link_count(inode);
9722 static int btrfs_rename(struct user_namespace *mnt_userns,
9723 struct inode *old_dir, struct dentry *old_dentry,
9724 struct inode *new_dir, struct dentry *new_dentry,
9727 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9728 struct btrfs_trans_handle *trans;
9729 unsigned int trans_num_items;
9730 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9731 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9732 struct inode *new_inode = d_inode(new_dentry);
9733 struct inode *old_inode = d_inode(old_dentry);
9737 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9738 bool log_pinned = false;
9740 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9743 /* we only allow rename subvolume link between subvolumes */
9744 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9747 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9748 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9751 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9752 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9756 /* check for collisions, even if the name isn't there */
9757 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9758 new_dentry->d_name.name,
9759 new_dentry->d_name.len);
9762 if (ret == -EEXIST) {
9764 * eexist without a new_inode */
9765 if (WARN_ON(!new_inode)) {
9769 /* maybe -EOVERFLOW */
9776 * we're using rename to replace one file with another. Start IO on it
9777 * now so we don't add too much work to the end of the transaction
9779 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9780 filemap_flush(old_inode->i_mapping);
9782 /* close the racy window with snapshot create/destroy ioctl */
9783 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9784 down_read(&fs_info->subvol_sem);
9786 * We want to reserve the absolute worst case amount of items. So if
9787 * both inodes are subvols and we need to unlink them then that would
9788 * require 4 item modifications, but if they are both normal inodes it
9789 * would require 5 item modifications, so we'll assume they are normal
9790 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9791 * should cover the worst case number of items we'll modify.
9792 * If our rename has the whiteout flag, we need more 5 units for the
9793 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9794 * when selinux is enabled).
9796 trans_num_items = 11;
9797 if (flags & RENAME_WHITEOUT)
9798 trans_num_items += 5;
9799 trans = btrfs_start_transaction(root, trans_num_items);
9800 if (IS_ERR(trans)) {
9801 ret = PTR_ERR(trans);
9806 ret = btrfs_record_root_in_trans(trans, dest);
9811 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9815 BTRFS_I(old_inode)->dir_index = 0ULL;
9816 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9817 /* force full log commit if subvolume involved. */
9818 btrfs_set_log_full_commit(trans);
9820 ret = btrfs_insert_inode_ref(trans, dest,
9821 new_dentry->d_name.name,
9822 new_dentry->d_name.len,
9824 btrfs_ino(BTRFS_I(new_dir)), index);
9829 inode_inc_iversion(old_dir);
9830 inode_inc_iversion(new_dir);
9831 inode_inc_iversion(old_inode);
9832 old_dir->i_ctime = old_dir->i_mtime =
9833 new_dir->i_ctime = new_dir->i_mtime =
9834 old_inode->i_ctime = current_time(old_dir);
9836 if (old_dentry->d_parent != new_dentry->d_parent)
9837 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9838 BTRFS_I(old_inode), 1);
9840 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9841 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9844 * Now pin the log. We do it to ensure that no other task can
9845 * sync the log while we are in progress with the rename, as
9846 * that could result in an inconsistency in case any of the
9847 * inodes that are part of this rename operation were logged
9850 * We pin the log even if at this precise moment none of the
9851 * inodes was logged before. This is because right after we
9852 * checked for that, some other task fsyncing some other inode
9853 * not involved with this rename operation could log that one of
9854 * our inodes exists.
9856 * We don't need to pin the logs before the above call to
9857 * btrfs_insert_inode_ref(), since that does not need to change
9860 btrfs_pin_log_trans(root);
9862 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9863 BTRFS_I(d_inode(old_dentry)),
9864 old_dentry->d_name.name,
9865 old_dentry->d_name.len);
9867 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9870 btrfs_abort_transaction(trans, ret);
9875 inode_inc_iversion(new_inode);
9876 new_inode->i_ctime = current_time(new_inode);
9877 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9878 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9879 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9880 BUG_ON(new_inode->i_nlink == 0);
9882 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9883 BTRFS_I(d_inode(new_dentry)),
9884 new_dentry->d_name.name,
9885 new_dentry->d_name.len);
9887 if (!ret && new_inode->i_nlink == 0)
9888 ret = btrfs_orphan_add(trans,
9889 BTRFS_I(d_inode(new_dentry)));
9891 btrfs_abort_transaction(trans, ret);
9896 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9897 new_dentry->d_name.name,
9898 new_dentry->d_name.len, 0, index);
9900 btrfs_abort_transaction(trans, ret);
9904 if (old_inode->i_nlink == 1)
9905 BTRFS_I(old_inode)->dir_index = index;
9908 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9909 new_dentry->d_parent);
9910 btrfs_end_log_trans(root);
9914 if (flags & RENAME_WHITEOUT) {
9915 ret = btrfs_whiteout_for_rename(trans, root, mnt_userns,
9916 old_dir, old_dentry);
9919 btrfs_abort_transaction(trans, ret);
9925 * If we have pinned the log and an error happened, we unpin tasks
9926 * trying to sync the log and force them to fallback to a transaction
9927 * commit if the log currently contains any of the inodes involved in
9928 * this rename operation (to ensure we do not persist a log with an
9929 * inconsistent state for any of these inodes or leading to any
9930 * inconsistencies when replayed). If the transaction was aborted, the
9931 * abortion reason is propagated to userspace when attempting to commit
9932 * the transaction. If the log does not contain any of these inodes, we
9933 * allow the tasks to sync it.
9935 if (ret && log_pinned) {
9936 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9937 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9938 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9940 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9941 btrfs_set_log_full_commit(trans);
9943 btrfs_end_log_trans(root);
9946 ret2 = btrfs_end_transaction(trans);
9947 ret = ret ? ret : ret2;
9949 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9950 up_read(&fs_info->subvol_sem);
9955 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9956 struct dentry *old_dentry, struct inode *new_dir,
9957 struct dentry *new_dentry, unsigned int flags)
9959 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9962 if (flags & RENAME_EXCHANGE)
9963 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9966 return btrfs_rename(mnt_userns, old_dir, old_dentry, new_dir,
9970 struct btrfs_delalloc_work {
9971 struct inode *inode;
9972 struct completion completion;
9973 struct list_head list;
9974 struct btrfs_work work;
9977 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9979 struct btrfs_delalloc_work *delalloc_work;
9980 struct inode *inode;
9982 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9984 inode = delalloc_work->inode;
9985 filemap_flush(inode->i_mapping);
9986 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9987 &BTRFS_I(inode)->runtime_flags))
9988 filemap_flush(inode->i_mapping);
9991 complete(&delalloc_work->completion);
9994 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9996 struct btrfs_delalloc_work *work;
9998 work = kmalloc(sizeof(*work), GFP_NOFS);
10002 init_completion(&work->completion);
10003 INIT_LIST_HEAD(&work->list);
10004 work->inode = inode;
10005 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
10011 * some fairly slow code that needs optimization. This walks the list
10012 * of all the inodes with pending delalloc and forces them to disk.
10014 static int start_delalloc_inodes(struct btrfs_root *root,
10015 struct writeback_control *wbc, bool snapshot,
10016 bool in_reclaim_context)
10018 struct btrfs_inode *binode;
10019 struct inode *inode;
10020 struct btrfs_delalloc_work *work, *next;
10021 struct list_head works;
10022 struct list_head splice;
10024 bool full_flush = wbc->nr_to_write == LONG_MAX;
10026 INIT_LIST_HEAD(&works);
10027 INIT_LIST_HEAD(&splice);
10029 mutex_lock(&root->delalloc_mutex);
10030 spin_lock(&root->delalloc_lock);
10031 list_splice_init(&root->delalloc_inodes, &splice);
10032 while (!list_empty(&splice)) {
10033 binode = list_entry(splice.next, struct btrfs_inode,
10036 list_move_tail(&binode->delalloc_inodes,
10037 &root->delalloc_inodes);
10039 if (in_reclaim_context &&
10040 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
10043 inode = igrab(&binode->vfs_inode);
10045 cond_resched_lock(&root->delalloc_lock);
10048 spin_unlock(&root->delalloc_lock);
10051 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10052 &binode->runtime_flags);
10054 work = btrfs_alloc_delalloc_work(inode);
10060 list_add_tail(&work->list, &works);
10061 btrfs_queue_work(root->fs_info->flush_workers,
10064 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
10065 btrfs_add_delayed_iput(inode);
10066 if (ret || wbc->nr_to_write <= 0)
10070 spin_lock(&root->delalloc_lock);
10072 spin_unlock(&root->delalloc_lock);
10075 list_for_each_entry_safe(work, next, &works, list) {
10076 list_del_init(&work->list);
10077 wait_for_completion(&work->completion);
10081 if (!list_empty(&splice)) {
10082 spin_lock(&root->delalloc_lock);
10083 list_splice_tail(&splice, &root->delalloc_inodes);
10084 spin_unlock(&root->delalloc_lock);
10086 mutex_unlock(&root->delalloc_mutex);
10090 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
10092 struct writeback_control wbc = {
10093 .nr_to_write = LONG_MAX,
10094 .sync_mode = WB_SYNC_NONE,
10096 .range_end = LLONG_MAX,
10098 struct btrfs_fs_info *fs_info = root->fs_info;
10100 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10103 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
10106 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
10107 bool in_reclaim_context)
10109 struct writeback_control wbc = {
10111 .sync_mode = WB_SYNC_NONE,
10113 .range_end = LLONG_MAX,
10115 struct btrfs_root *root;
10116 struct list_head splice;
10119 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10122 INIT_LIST_HEAD(&splice);
10124 mutex_lock(&fs_info->delalloc_root_mutex);
10125 spin_lock(&fs_info->delalloc_root_lock);
10126 list_splice_init(&fs_info->delalloc_roots, &splice);
10127 while (!list_empty(&splice)) {
10129 * Reset nr_to_write here so we know that we're doing a full
10132 if (nr == LONG_MAX)
10133 wbc.nr_to_write = LONG_MAX;
10135 root = list_first_entry(&splice, struct btrfs_root,
10137 root = btrfs_grab_root(root);
10139 list_move_tail(&root->delalloc_root,
10140 &fs_info->delalloc_roots);
10141 spin_unlock(&fs_info->delalloc_root_lock);
10143 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
10144 btrfs_put_root(root);
10145 if (ret < 0 || wbc.nr_to_write <= 0)
10147 spin_lock(&fs_info->delalloc_root_lock);
10149 spin_unlock(&fs_info->delalloc_root_lock);
10153 if (!list_empty(&splice)) {
10154 spin_lock(&fs_info->delalloc_root_lock);
10155 list_splice_tail(&splice, &fs_info->delalloc_roots);
10156 spin_unlock(&fs_info->delalloc_root_lock);
10158 mutex_unlock(&fs_info->delalloc_root_mutex);
10162 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
10163 struct dentry *dentry, const char *symname)
10165 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10166 struct btrfs_trans_handle *trans;
10167 struct btrfs_root *root = BTRFS_I(dir)->root;
10168 struct btrfs_path *path;
10169 struct btrfs_key key;
10170 struct inode *inode = NULL;
10177 struct btrfs_file_extent_item *ei;
10178 struct extent_buffer *leaf;
10180 name_len = strlen(symname);
10181 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10182 return -ENAMETOOLONG;
10185 * 2 items for inode item and ref
10186 * 2 items for dir items
10187 * 1 item for updating parent inode item
10188 * 1 item for the inline extent item
10189 * 1 item for xattr if selinux is on
10191 trans = btrfs_start_transaction(root, 7);
10193 return PTR_ERR(trans);
10195 err = btrfs_get_free_objectid(root, &objectid);
10199 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
10200 dentry->d_name.name, dentry->d_name.len,
10201 btrfs_ino(BTRFS_I(dir)), objectid,
10202 S_IFLNK | S_IRWXUGO, &index);
10203 if (IS_ERR(inode)) {
10204 err = PTR_ERR(inode);
10210 * If the active LSM wants to access the inode during
10211 * d_instantiate it needs these. Smack checks to see
10212 * if the filesystem supports xattrs by looking at the
10215 inode->i_fop = &btrfs_file_operations;
10216 inode->i_op = &btrfs_file_inode_operations;
10217 inode->i_mapping->a_ops = &btrfs_aops;
10219 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10223 path = btrfs_alloc_path();
10228 key.objectid = btrfs_ino(BTRFS_I(inode));
10230 key.type = BTRFS_EXTENT_DATA_KEY;
10231 datasize = btrfs_file_extent_calc_inline_size(name_len);
10232 err = btrfs_insert_empty_item(trans, root, path, &key,
10235 btrfs_free_path(path);
10238 leaf = path->nodes[0];
10239 ei = btrfs_item_ptr(leaf, path->slots[0],
10240 struct btrfs_file_extent_item);
10241 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10242 btrfs_set_file_extent_type(leaf, ei,
10243 BTRFS_FILE_EXTENT_INLINE);
10244 btrfs_set_file_extent_encryption(leaf, ei, 0);
10245 btrfs_set_file_extent_compression(leaf, ei, 0);
10246 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10247 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10249 ptr = btrfs_file_extent_inline_start(ei);
10250 write_extent_buffer(leaf, symname, ptr, name_len);
10251 btrfs_mark_buffer_dirty(leaf);
10252 btrfs_free_path(path);
10254 inode->i_op = &btrfs_symlink_inode_operations;
10255 inode_nohighmem(inode);
10256 inode_set_bytes(inode, name_len);
10257 btrfs_i_size_write(BTRFS_I(inode), name_len);
10258 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
10260 * Last step, add directory indexes for our symlink inode. This is the
10261 * last step to avoid extra cleanup of these indexes if an error happens
10265 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10266 BTRFS_I(inode), 0, index);
10270 d_instantiate_new(dentry, inode);
10273 btrfs_end_transaction(trans);
10274 if (err && inode) {
10275 inode_dec_link_count(inode);
10276 discard_new_inode(inode);
10278 btrfs_btree_balance_dirty(fs_info);
10282 static struct btrfs_trans_handle *insert_prealloc_file_extent(
10283 struct btrfs_trans_handle *trans_in,
10284 struct btrfs_inode *inode,
10285 struct btrfs_key *ins,
10288 struct btrfs_file_extent_item stack_fi;
10289 struct btrfs_replace_extent_info extent_info;
10290 struct btrfs_trans_handle *trans = trans_in;
10291 struct btrfs_path *path;
10292 u64 start = ins->objectid;
10293 u64 len = ins->offset;
10294 int qgroup_released;
10297 memset(&stack_fi, 0, sizeof(stack_fi));
10299 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
10300 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
10301 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
10302 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
10303 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
10304 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
10305 /* Encryption and other encoding is reserved and all 0 */
10307 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
10308 if (qgroup_released < 0)
10309 return ERR_PTR(qgroup_released);
10312 ret = insert_reserved_file_extent(trans, inode,
10313 file_offset, &stack_fi,
10314 true, qgroup_released);
10320 extent_info.disk_offset = start;
10321 extent_info.disk_len = len;
10322 extent_info.data_offset = 0;
10323 extent_info.data_len = len;
10324 extent_info.file_offset = file_offset;
10325 extent_info.extent_buf = (char *)&stack_fi;
10326 extent_info.is_new_extent = true;
10327 extent_info.qgroup_reserved = qgroup_released;
10328 extent_info.insertions = 0;
10330 path = btrfs_alloc_path();
10336 ret = btrfs_replace_file_extents(inode, path, file_offset,
10337 file_offset + len - 1, &extent_info,
10339 btrfs_free_path(path);
10346 * We have released qgroup data range at the beginning of the function,
10347 * and normally qgroup_released bytes will be freed when committing
10349 * But if we error out early, we have to free what we have released
10350 * or we leak qgroup data reservation.
10352 btrfs_qgroup_free_refroot(inode->root->fs_info,
10353 inode->root->root_key.objectid, qgroup_released,
10354 BTRFS_QGROUP_RSV_DATA);
10355 return ERR_PTR(ret);
10358 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10359 u64 start, u64 num_bytes, u64 min_size,
10360 loff_t actual_len, u64 *alloc_hint,
10361 struct btrfs_trans_handle *trans)
10363 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10364 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10365 struct extent_map *em;
10366 struct btrfs_root *root = BTRFS_I(inode)->root;
10367 struct btrfs_key ins;
10368 u64 cur_offset = start;
10369 u64 clear_offset = start;
10372 u64 last_alloc = (u64)-1;
10374 bool own_trans = true;
10375 u64 end = start + num_bytes - 1;
10379 while (num_bytes > 0) {
10380 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10381 cur_bytes = max(cur_bytes, min_size);
10383 * If we are severely fragmented we could end up with really
10384 * small allocations, so if the allocator is returning small
10385 * chunks lets make its job easier by only searching for those
10388 cur_bytes = min(cur_bytes, last_alloc);
10389 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10390 min_size, 0, *alloc_hint, &ins, 1, 0);
10395 * We've reserved this space, and thus converted it from
10396 * ->bytes_may_use to ->bytes_reserved. Any error that happens
10397 * from here on out we will only need to clear our reservation
10398 * for the remaining unreserved area, so advance our
10399 * clear_offset by our extent size.
10401 clear_offset += ins.offset;
10403 last_alloc = ins.offset;
10404 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
10407 * Now that we inserted the prealloc extent we can finally
10408 * decrement the number of reservations in the block group.
10409 * If we did it before, we could race with relocation and have
10410 * relocation miss the reserved extent, making it fail later.
10412 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10413 if (IS_ERR(trans)) {
10414 ret = PTR_ERR(trans);
10415 btrfs_free_reserved_extent(fs_info, ins.objectid,
10420 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10421 cur_offset + ins.offset -1, 0);
10423 em = alloc_extent_map();
10425 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10426 &BTRFS_I(inode)->runtime_flags);
10430 em->start = cur_offset;
10431 em->orig_start = cur_offset;
10432 em->len = ins.offset;
10433 em->block_start = ins.objectid;
10434 em->block_len = ins.offset;
10435 em->orig_block_len = ins.offset;
10436 em->ram_bytes = ins.offset;
10437 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10438 em->generation = trans->transid;
10441 write_lock(&em_tree->lock);
10442 ret = add_extent_mapping(em_tree, em, 1);
10443 write_unlock(&em_tree->lock);
10444 if (ret != -EEXIST)
10446 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10447 cur_offset + ins.offset - 1,
10450 free_extent_map(em);
10452 num_bytes -= ins.offset;
10453 cur_offset += ins.offset;
10454 *alloc_hint = ins.objectid + ins.offset;
10456 inode_inc_iversion(inode);
10457 inode->i_ctime = current_time(inode);
10458 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10459 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10460 (actual_len > inode->i_size) &&
10461 (cur_offset > inode->i_size)) {
10462 if (cur_offset > actual_len)
10463 i_size = actual_len;
10465 i_size = cur_offset;
10466 i_size_write(inode, i_size);
10467 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10470 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10473 btrfs_abort_transaction(trans, ret);
10475 btrfs_end_transaction(trans);
10480 btrfs_end_transaction(trans);
10484 if (clear_offset < end)
10485 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10486 end - clear_offset + 1);
10490 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10491 u64 start, u64 num_bytes, u64 min_size,
10492 loff_t actual_len, u64 *alloc_hint)
10494 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10495 min_size, actual_len, alloc_hint,
10499 int btrfs_prealloc_file_range_trans(struct inode *inode,
10500 struct btrfs_trans_handle *trans, int mode,
10501 u64 start, u64 num_bytes, u64 min_size,
10502 loff_t actual_len, u64 *alloc_hint)
10504 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10505 min_size, actual_len, alloc_hint, trans);
10508 static int btrfs_set_page_dirty(struct page *page)
10510 return __set_page_dirty_nobuffers(page);
10513 static int btrfs_permission(struct user_namespace *mnt_userns,
10514 struct inode *inode, int mask)
10516 struct btrfs_root *root = BTRFS_I(inode)->root;
10517 umode_t mode = inode->i_mode;
10519 if (mask & MAY_WRITE &&
10520 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10521 if (btrfs_root_readonly(root))
10523 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10526 return generic_permission(mnt_userns, inode, mask);
10529 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10530 struct dentry *dentry, umode_t mode)
10532 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10533 struct btrfs_trans_handle *trans;
10534 struct btrfs_root *root = BTRFS_I(dir)->root;
10535 struct inode *inode = NULL;
10541 * 5 units required for adding orphan entry
10543 trans = btrfs_start_transaction(root, 5);
10545 return PTR_ERR(trans);
10547 ret = btrfs_get_free_objectid(root, &objectid);
10551 inode = btrfs_new_inode(trans, root, mnt_userns, dir, NULL, 0,
10552 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10553 if (IS_ERR(inode)) {
10554 ret = PTR_ERR(inode);
10559 inode->i_fop = &btrfs_file_operations;
10560 inode->i_op = &btrfs_file_inode_operations;
10562 inode->i_mapping->a_ops = &btrfs_aops;
10564 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10568 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10571 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10576 * We set number of links to 0 in btrfs_new_inode(), and here we set
10577 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10580 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10582 set_nlink(inode, 1);
10583 d_tmpfile(dentry, inode);
10584 unlock_new_inode(inode);
10585 mark_inode_dirty(inode);
10587 btrfs_end_transaction(trans);
10589 discard_new_inode(inode);
10590 btrfs_btree_balance_dirty(fs_info);
10594 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
10596 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10597 unsigned long index = start >> PAGE_SHIFT;
10598 unsigned long end_index = end >> PAGE_SHIFT;
10602 ASSERT(end + 1 - start <= U32_MAX);
10603 len = end + 1 - start;
10604 while (index <= end_index) {
10605 page = find_get_page(inode->vfs_inode.i_mapping, index);
10606 ASSERT(page); /* Pages should be in the extent_io_tree */
10608 btrfs_page_set_writeback(fs_info, page, start, len);
10616 * Add an entry indicating a block group or device which is pinned by a
10617 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10618 * negative errno on failure.
10620 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10621 bool is_block_group)
10623 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10624 struct btrfs_swapfile_pin *sp, *entry;
10625 struct rb_node **p;
10626 struct rb_node *parent = NULL;
10628 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10633 sp->is_block_group = is_block_group;
10634 sp->bg_extent_count = 1;
10636 spin_lock(&fs_info->swapfile_pins_lock);
10637 p = &fs_info->swapfile_pins.rb_node;
10640 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10641 if (sp->ptr < entry->ptr ||
10642 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10643 p = &(*p)->rb_left;
10644 } else if (sp->ptr > entry->ptr ||
10645 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10646 p = &(*p)->rb_right;
10648 if (is_block_group)
10649 entry->bg_extent_count++;
10650 spin_unlock(&fs_info->swapfile_pins_lock);
10655 rb_link_node(&sp->node, parent, p);
10656 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10657 spin_unlock(&fs_info->swapfile_pins_lock);
10661 /* Free all of the entries pinned by this swapfile. */
10662 static void btrfs_free_swapfile_pins(struct inode *inode)
10664 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10665 struct btrfs_swapfile_pin *sp;
10666 struct rb_node *node, *next;
10668 spin_lock(&fs_info->swapfile_pins_lock);
10669 node = rb_first(&fs_info->swapfile_pins);
10671 next = rb_next(node);
10672 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10673 if (sp->inode == inode) {
10674 rb_erase(&sp->node, &fs_info->swapfile_pins);
10675 if (sp->is_block_group) {
10676 btrfs_dec_block_group_swap_extents(sp->ptr,
10677 sp->bg_extent_count);
10678 btrfs_put_block_group(sp->ptr);
10684 spin_unlock(&fs_info->swapfile_pins_lock);
10687 struct btrfs_swap_info {
10693 unsigned long nr_pages;
10697 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10698 struct btrfs_swap_info *bsi)
10700 unsigned long nr_pages;
10701 unsigned long max_pages;
10702 u64 first_ppage, first_ppage_reported, next_ppage;
10706 * Our swapfile may have had its size extended after the swap header was
10707 * written. In that case activating the swapfile should not go beyond
10708 * the max size set in the swap header.
10710 if (bsi->nr_pages >= sis->max)
10713 max_pages = sis->max - bsi->nr_pages;
10714 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10715 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10716 PAGE_SIZE) >> PAGE_SHIFT;
10718 if (first_ppage >= next_ppage)
10720 nr_pages = next_ppage - first_ppage;
10721 nr_pages = min(nr_pages, max_pages);
10723 first_ppage_reported = first_ppage;
10724 if (bsi->start == 0)
10725 first_ppage_reported++;
10726 if (bsi->lowest_ppage > first_ppage_reported)
10727 bsi->lowest_ppage = first_ppage_reported;
10728 if (bsi->highest_ppage < (next_ppage - 1))
10729 bsi->highest_ppage = next_ppage - 1;
10731 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10734 bsi->nr_extents += ret;
10735 bsi->nr_pages += nr_pages;
10739 static void btrfs_swap_deactivate(struct file *file)
10741 struct inode *inode = file_inode(file);
10743 btrfs_free_swapfile_pins(inode);
10744 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10747 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10750 struct inode *inode = file_inode(file);
10751 struct btrfs_root *root = BTRFS_I(inode)->root;
10752 struct btrfs_fs_info *fs_info = root->fs_info;
10753 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10754 struct extent_state *cached_state = NULL;
10755 struct extent_map *em = NULL;
10756 struct btrfs_device *device = NULL;
10757 struct btrfs_swap_info bsi = {
10758 .lowest_ppage = (sector_t)-1ULL,
10765 * If the swap file was just created, make sure delalloc is done. If the
10766 * file changes again after this, the user is doing something stupid and
10767 * we don't really care.
10769 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10774 * The inode is locked, so these flags won't change after we check them.
10776 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10777 btrfs_warn(fs_info, "swapfile must not be compressed");
10780 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10781 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10784 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10785 btrfs_warn(fs_info, "swapfile must not be checksummed");
10790 * Balance or device remove/replace/resize can move stuff around from
10791 * under us. The exclop protection makes sure they aren't running/won't
10792 * run concurrently while we are mapping the swap extents, and
10793 * fs_info->swapfile_pins prevents them from running while the swap
10794 * file is active and moving the extents. Note that this also prevents
10795 * a concurrent device add which isn't actually necessary, but it's not
10796 * really worth the trouble to allow it.
10798 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10799 btrfs_warn(fs_info,
10800 "cannot activate swapfile while exclusive operation is running");
10805 * Prevent snapshot creation while we are activating the swap file.
10806 * We do not want to race with snapshot creation. If snapshot creation
10807 * already started before we bumped nr_swapfiles from 0 to 1 and
10808 * completes before the first write into the swap file after it is
10809 * activated, than that write would fallback to COW.
10811 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10812 btrfs_exclop_finish(fs_info);
10813 btrfs_warn(fs_info,
10814 "cannot activate swapfile because snapshot creation is in progress");
10818 * Snapshots can create extents which require COW even if NODATACOW is
10819 * set. We use this counter to prevent snapshots. We must increment it
10820 * before walking the extents because we don't want a concurrent
10821 * snapshot to run after we've already checked the extents.
10823 * It is possible that subvolume is marked for deletion but still not
10824 * removed yet. To prevent this race, we check the root status before
10825 * activating the swapfile.
10827 spin_lock(&root->root_item_lock);
10828 if (btrfs_root_dead(root)) {
10829 spin_unlock(&root->root_item_lock);
10831 btrfs_exclop_finish(fs_info);
10832 btrfs_warn(fs_info,
10833 "cannot activate swapfile because subvolume %llu is being deleted",
10834 root->root_key.objectid);
10837 atomic_inc(&root->nr_swapfiles);
10838 spin_unlock(&root->root_item_lock);
10840 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10842 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10844 while (start < isize) {
10845 u64 logical_block_start, physical_block_start;
10846 struct btrfs_block_group *bg;
10847 u64 len = isize - start;
10849 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10855 if (em->block_start == EXTENT_MAP_HOLE) {
10856 btrfs_warn(fs_info, "swapfile must not have holes");
10860 if (em->block_start == EXTENT_MAP_INLINE) {
10862 * It's unlikely we'll ever actually find ourselves
10863 * here, as a file small enough to fit inline won't be
10864 * big enough to store more than the swap header, but in
10865 * case something changes in the future, let's catch it
10866 * here rather than later.
10868 btrfs_warn(fs_info, "swapfile must not be inline");
10872 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10873 btrfs_warn(fs_info, "swapfile must not be compressed");
10878 logical_block_start = em->block_start + (start - em->start);
10879 len = min(len, em->len - (start - em->start));
10880 free_extent_map(em);
10883 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10889 btrfs_warn(fs_info,
10890 "swapfile must not be copy-on-write");
10895 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10901 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10902 btrfs_warn(fs_info,
10903 "swapfile must have single data profile");
10908 if (device == NULL) {
10909 device = em->map_lookup->stripes[0].dev;
10910 ret = btrfs_add_swapfile_pin(inode, device, false);
10915 } else if (device != em->map_lookup->stripes[0].dev) {
10916 btrfs_warn(fs_info, "swapfile must be on one device");
10921 physical_block_start = (em->map_lookup->stripes[0].physical +
10922 (logical_block_start - em->start));
10923 len = min(len, em->len - (logical_block_start - em->start));
10924 free_extent_map(em);
10927 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10929 btrfs_warn(fs_info,
10930 "could not find block group containing swapfile");
10935 if (!btrfs_inc_block_group_swap_extents(bg)) {
10936 btrfs_warn(fs_info,
10937 "block group for swapfile at %llu is read-only%s",
10939 atomic_read(&fs_info->scrubs_running) ?
10940 " (scrub running)" : "");
10941 btrfs_put_block_group(bg);
10946 ret = btrfs_add_swapfile_pin(inode, bg, true);
10948 btrfs_put_block_group(bg);
10955 if (bsi.block_len &&
10956 bsi.block_start + bsi.block_len == physical_block_start) {
10957 bsi.block_len += len;
10959 if (bsi.block_len) {
10960 ret = btrfs_add_swap_extent(sis, &bsi);
10965 bsi.block_start = physical_block_start;
10966 bsi.block_len = len;
10973 ret = btrfs_add_swap_extent(sis, &bsi);
10976 if (!IS_ERR_OR_NULL(em))
10977 free_extent_map(em);
10979 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10982 btrfs_swap_deactivate(file);
10984 btrfs_drew_write_unlock(&root->snapshot_lock);
10986 btrfs_exclop_finish(fs_info);
10992 sis->bdev = device->bdev;
10993 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10994 sis->max = bsi.nr_pages;
10995 sis->pages = bsi.nr_pages - 1;
10996 sis->highest_bit = bsi.nr_pages - 1;
10997 return bsi.nr_extents;
11000 static void btrfs_swap_deactivate(struct file *file)
11004 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11007 return -EOPNOTSUPP;
11012 * Update the number of bytes used in the VFS' inode. When we replace extents in
11013 * a range (clone, dedupe, fallocate's zero range), we must update the number of
11014 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
11015 * always get a correct value.
11017 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
11018 const u64 add_bytes,
11019 const u64 del_bytes)
11021 if (add_bytes == del_bytes)
11024 spin_lock(&inode->lock);
11026 inode_sub_bytes(&inode->vfs_inode, del_bytes);
11028 inode_add_bytes(&inode->vfs_inode, add_bytes);
11029 spin_unlock(&inode->lock);
11032 static const struct inode_operations btrfs_dir_inode_operations = {
11033 .getattr = btrfs_getattr,
11034 .lookup = btrfs_lookup,
11035 .create = btrfs_create,
11036 .unlink = btrfs_unlink,
11037 .link = btrfs_link,
11038 .mkdir = btrfs_mkdir,
11039 .rmdir = btrfs_rmdir,
11040 .rename = btrfs_rename2,
11041 .symlink = btrfs_symlink,
11042 .setattr = btrfs_setattr,
11043 .mknod = btrfs_mknod,
11044 .listxattr = btrfs_listxattr,
11045 .permission = btrfs_permission,
11046 .get_acl = btrfs_get_acl,
11047 .set_acl = btrfs_set_acl,
11048 .update_time = btrfs_update_time,
11049 .tmpfile = btrfs_tmpfile,
11050 .fileattr_get = btrfs_fileattr_get,
11051 .fileattr_set = btrfs_fileattr_set,
11054 static const struct file_operations btrfs_dir_file_operations = {
11055 .llseek = generic_file_llseek,
11056 .read = generic_read_dir,
11057 .iterate_shared = btrfs_real_readdir,
11058 .open = btrfs_opendir,
11059 .unlocked_ioctl = btrfs_ioctl,
11060 #ifdef CONFIG_COMPAT
11061 .compat_ioctl = btrfs_compat_ioctl,
11063 .release = btrfs_release_file,
11064 .fsync = btrfs_sync_file,
11068 * btrfs doesn't support the bmap operation because swapfiles
11069 * use bmap to make a mapping of extents in the file. They assume
11070 * these extents won't change over the life of the file and they
11071 * use the bmap result to do IO directly to the drive.
11073 * the btrfs bmap call would return logical addresses that aren't
11074 * suitable for IO and they also will change frequently as COW
11075 * operations happen. So, swapfile + btrfs == corruption.
11077 * For now we're avoiding this by dropping bmap.
11079 static const struct address_space_operations btrfs_aops = {
11080 .readpage = btrfs_readpage,
11081 .writepage = btrfs_writepage,
11082 .writepages = btrfs_writepages,
11083 .readahead = btrfs_readahead,
11084 .direct_IO = noop_direct_IO,
11085 .invalidatepage = btrfs_invalidatepage,
11086 .releasepage = btrfs_releasepage,
11087 #ifdef CONFIG_MIGRATION
11088 .migratepage = btrfs_migratepage,
11090 .set_page_dirty = btrfs_set_page_dirty,
11091 .error_remove_page = generic_error_remove_page,
11092 .swap_activate = btrfs_swap_activate,
11093 .swap_deactivate = btrfs_swap_deactivate,
11096 static const struct inode_operations btrfs_file_inode_operations = {
11097 .getattr = btrfs_getattr,
11098 .setattr = btrfs_setattr,
11099 .listxattr = btrfs_listxattr,
11100 .permission = btrfs_permission,
11101 .fiemap = btrfs_fiemap,
11102 .get_acl = btrfs_get_acl,
11103 .set_acl = btrfs_set_acl,
11104 .update_time = btrfs_update_time,
11105 .fileattr_get = btrfs_fileattr_get,
11106 .fileattr_set = btrfs_fileattr_set,
11108 static const struct inode_operations btrfs_special_inode_operations = {
11109 .getattr = btrfs_getattr,
11110 .setattr = btrfs_setattr,
11111 .permission = btrfs_permission,
11112 .listxattr = btrfs_listxattr,
11113 .get_acl = btrfs_get_acl,
11114 .set_acl = btrfs_set_acl,
11115 .update_time = btrfs_update_time,
11117 static const struct inode_operations btrfs_symlink_inode_operations = {
11118 .get_link = page_get_link,
11119 .getattr = btrfs_getattr,
11120 .setattr = btrfs_setattr,
11121 .permission = btrfs_permission,
11122 .listxattr = btrfs_listxattr,
11123 .update_time = btrfs_update_time,
11126 const struct dentry_operations btrfs_dentry_operations = {
11127 .d_delete = btrfs_dentry_delete,