1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <crypto/hash.h>
7 #include <linux/kernel.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/migrate.h>
32 #include <linux/sched/mm.h>
33 #include <linux/iomap.h>
34 #include <asm/unaligned.h>
38 #include "transaction.h"
39 #include "btrfs_inode.h"
40 #include "print-tree.h"
41 #include "ordered-data.h"
45 #include "compression.h"
47 #include "free-space-cache.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
52 #include "space-info.h"
56 struct btrfs_iget_args {
58 struct btrfs_root *root;
61 struct btrfs_dio_data {
65 struct extent_changeset *data_reserved;
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_special_inode_operations;
71 static const struct inode_operations btrfs_file_inode_operations;
72 static const struct address_space_operations btrfs_aops;
73 static const struct file_operations btrfs_dir_file_operations;
75 static struct kmem_cache *btrfs_inode_cachep;
76 struct kmem_cache *btrfs_trans_handle_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
79 struct kmem_cache *btrfs_free_space_bitmap_cachep;
81 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
82 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
83 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
84 static noinline int cow_file_range(struct btrfs_inode *inode,
85 struct page *locked_page,
86 u64 start, u64 end, int *page_started,
87 unsigned long *nr_written, int unlock);
88 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
89 u64 len, u64 orig_start, u64 block_start,
90 u64 block_len, u64 orig_block_len,
91 u64 ram_bytes, int compress_type,
94 static void __endio_write_update_ordered(struct btrfs_inode *inode,
95 const u64 offset, const u64 bytes,
99 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
101 * ilock_flags can have the following bit set:
103 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
104 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
106 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
108 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
110 if (ilock_flags & BTRFS_ILOCK_SHARED) {
111 if (ilock_flags & BTRFS_ILOCK_TRY) {
112 if (!inode_trylock_shared(inode))
117 inode_lock_shared(inode);
119 if (ilock_flags & BTRFS_ILOCK_TRY) {
120 if (!inode_trylock(inode))
127 if (ilock_flags & BTRFS_ILOCK_MMAP)
128 down_write(&BTRFS_I(inode)->i_mmap_lock);
133 * btrfs_inode_unlock - unock inode i_rwsem
135 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
136 * to decide whether the lock acquired is shared or exclusive.
138 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
140 if (ilock_flags & BTRFS_ILOCK_MMAP)
141 up_write(&BTRFS_I(inode)->i_mmap_lock);
142 if (ilock_flags & BTRFS_ILOCK_SHARED)
143 inode_unlock_shared(inode);
149 * Cleanup all submitted ordered extents in specified range to handle errors
150 * from the btrfs_run_delalloc_range() callback.
152 * NOTE: caller must ensure that when an error happens, it can not call
153 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
154 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
155 * to be released, which we want to happen only when finishing the ordered
156 * extent (btrfs_finish_ordered_io()).
158 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
159 struct page *locked_page,
160 u64 offset, u64 bytes)
162 unsigned long index = offset >> PAGE_SHIFT;
163 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
164 u64 page_start = page_offset(locked_page);
165 u64 page_end = page_start + PAGE_SIZE - 1;
169 while (index <= end_index) {
171 * For locked page, we will call end_extent_writepage() on it
172 * in run_delalloc_range() for the error handling. That
173 * end_extent_writepage() function will call
174 * btrfs_mark_ordered_io_finished() to clear page Ordered and
175 * run the ordered extent accounting.
177 * Here we can't just clear the Ordered bit, or
178 * btrfs_mark_ordered_io_finished() would skip the accounting
179 * for the page range, and the ordered extent will never finish.
181 if (index == (page_offset(locked_page) >> PAGE_SHIFT)) {
185 page = find_get_page(inode->vfs_inode.i_mapping, index);
191 * Here we just clear all Ordered bits for every page in the
192 * range, then __endio_write_update_ordered() will handle
193 * the ordered extent accounting for the range.
195 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
200 /* The locked page covers the full range, nothing needs to be done */
201 if (bytes + offset <= page_offset(locked_page) + PAGE_SIZE)
204 * In case this page belongs to the delalloc range being instantiated
205 * then skip it, since the first page of a range is going to be
206 * properly cleaned up by the caller of run_delalloc_range
208 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
209 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
210 offset = page_offset(locked_page) + PAGE_SIZE;
213 return __endio_write_update_ordered(inode, offset, bytes, false);
216 static int btrfs_dirty_inode(struct inode *inode);
218 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
219 struct inode *inode, struct inode *dir,
220 const struct qstr *qstr)
224 err = btrfs_init_acl(trans, inode, dir);
226 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
231 * this does all the hard work for inserting an inline extent into
232 * the btree. The caller should have done a btrfs_drop_extents so that
233 * no overlapping inline items exist in the btree
235 static int insert_inline_extent(struct btrfs_trans_handle *trans,
236 struct btrfs_path *path, bool extent_inserted,
237 struct btrfs_root *root, struct inode *inode,
238 u64 start, size_t size, size_t compressed_size,
240 struct page **compressed_pages)
242 struct extent_buffer *leaf;
243 struct page *page = NULL;
246 struct btrfs_file_extent_item *ei;
248 size_t cur_size = size;
249 unsigned long offset;
251 ASSERT((compressed_size > 0 && compressed_pages) ||
252 (compressed_size == 0 && !compressed_pages));
254 if (compressed_size && compressed_pages)
255 cur_size = compressed_size;
257 if (!extent_inserted) {
258 struct btrfs_key key;
261 key.objectid = btrfs_ino(BTRFS_I(inode));
263 key.type = BTRFS_EXTENT_DATA_KEY;
265 datasize = btrfs_file_extent_calc_inline_size(cur_size);
266 ret = btrfs_insert_empty_item(trans, root, path, &key,
271 leaf = path->nodes[0];
272 ei = btrfs_item_ptr(leaf, path->slots[0],
273 struct btrfs_file_extent_item);
274 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
275 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
276 btrfs_set_file_extent_encryption(leaf, ei, 0);
277 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
278 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
279 ptr = btrfs_file_extent_inline_start(ei);
281 if (compress_type != BTRFS_COMPRESS_NONE) {
284 while (compressed_size > 0) {
285 cpage = compressed_pages[i];
286 cur_size = min_t(unsigned long, compressed_size,
289 kaddr = page_address(cpage);
290 write_extent_buffer(leaf, kaddr, ptr, cur_size);
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 (nr_pages > 1 && 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 static noinline int cow_file_range(struct btrfs_inode *inode,
1058 struct page *locked_page,
1059 u64 start, u64 end, int *page_started,
1060 unsigned long *nr_written, int unlock)
1062 struct btrfs_root *root = inode->root;
1063 struct btrfs_fs_info *fs_info = root->fs_info;
1066 unsigned long ram_size;
1067 u64 cur_alloc_size = 0;
1069 u64 blocksize = fs_info->sectorsize;
1070 struct btrfs_key ins;
1071 struct extent_map *em;
1072 unsigned clear_bits;
1073 unsigned long page_ops;
1074 bool extent_reserved = false;
1077 if (btrfs_is_free_space_inode(inode)) {
1083 num_bytes = ALIGN(end - start + 1, blocksize);
1084 num_bytes = max(blocksize, num_bytes);
1085 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1087 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1090 * Due to the page size limit, for subpage we can only trigger the
1091 * writeback for the dirty sectors of page, that means data writeback
1092 * is doing more writeback than what we want.
1094 * This is especially unexpected for some call sites like fallocate,
1095 * where we only increase i_size after everything is done.
1096 * This means we can trigger inline extent even if we didn't want to.
1097 * So here we skip inline extent creation completely.
1099 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
1100 /* lets try to make an inline extent */
1101 ret = cow_file_range_inline(inode, start, end, 0,
1102 BTRFS_COMPRESS_NONE, NULL);
1105 * We use DO_ACCOUNTING here because we need the
1106 * delalloc_release_metadata to be run _after_ we drop
1107 * our outstanding extent for clearing delalloc for this
1110 extent_clear_unlock_delalloc(inode, start, end,
1112 EXTENT_LOCKED | EXTENT_DELALLOC |
1113 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1114 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1115 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1116 *nr_written = *nr_written +
1117 (end - start + PAGE_SIZE) / PAGE_SIZE;
1120 * locked_page is locked by the caller of
1121 * writepage_delalloc(), not locked by
1122 * __process_pages_contig().
1124 * We can't let __process_pages_contig() to unlock it,
1125 * as it doesn't have any subpage::writers recorded.
1127 * Here we manually unlock the page, since the caller
1128 * can't use page_started to determine if it's an
1129 * inline extent or a compressed extent.
1131 unlock_page(locked_page);
1133 } else if (ret < 0) {
1138 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1139 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1142 * Relocation relies on the relocated extents to have exactly the same
1143 * size as the original extents. Normally writeback for relocation data
1144 * extents follows a NOCOW path because relocation preallocates the
1145 * extents. However, due to an operation such as scrub turning a block
1146 * group to RO mode, it may fallback to COW mode, so we must make sure
1147 * an extent allocated during COW has exactly the requested size and can
1148 * not be split into smaller extents, otherwise relocation breaks and
1149 * fails during the stage where it updates the bytenr of file extent
1152 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1153 min_alloc_size = num_bytes;
1155 min_alloc_size = fs_info->sectorsize;
1157 while (num_bytes > 0) {
1158 cur_alloc_size = num_bytes;
1159 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1160 min_alloc_size, 0, alloc_hint,
1164 cur_alloc_size = ins.offset;
1165 extent_reserved = true;
1167 ram_size = ins.offset;
1168 em = create_io_em(inode, start, ins.offset, /* len */
1169 start, /* orig_start */
1170 ins.objectid, /* block_start */
1171 ins.offset, /* block_len */
1172 ins.offset, /* orig_block_len */
1173 ram_size, /* ram_bytes */
1174 BTRFS_COMPRESS_NONE, /* compress_type */
1175 BTRFS_ORDERED_REGULAR /* type */);
1180 free_extent_map(em);
1182 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1183 ram_size, cur_alloc_size,
1184 BTRFS_ORDERED_REGULAR);
1186 goto out_drop_extent_cache;
1188 if (root->root_key.objectid ==
1189 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1190 ret = btrfs_reloc_clone_csums(inode, start,
1193 * Only drop cache here, and process as normal.
1195 * We must not allow extent_clear_unlock_delalloc()
1196 * at out_unlock label to free meta of this ordered
1197 * extent, as its meta should be freed by
1198 * btrfs_finish_ordered_io().
1200 * So we must continue until @start is increased to
1201 * skip current ordered extent.
1204 btrfs_drop_extent_cache(inode, start,
1205 start + ram_size - 1, 0);
1208 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1211 * We're not doing compressed IO, don't unlock the first page
1212 * (which the caller expects to stay locked), don't clear any
1213 * dirty bits and don't set any writeback bits
1215 * Do set the Ordered (Private2) bit so we know this page was
1216 * properly setup for writepage.
1218 page_ops = unlock ? PAGE_UNLOCK : 0;
1219 page_ops |= PAGE_SET_ORDERED;
1221 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1223 EXTENT_LOCKED | EXTENT_DELALLOC,
1225 if (num_bytes < cur_alloc_size)
1228 num_bytes -= cur_alloc_size;
1229 alloc_hint = ins.objectid + ins.offset;
1230 start += cur_alloc_size;
1231 extent_reserved = false;
1234 * btrfs_reloc_clone_csums() error, since start is increased
1235 * extent_clear_unlock_delalloc() at out_unlock label won't
1236 * free metadata of current ordered extent, we're OK to exit.
1244 out_drop_extent_cache:
1245 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1247 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1248 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1250 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1251 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1252 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1254 * If we reserved an extent for our delalloc range (or a subrange) and
1255 * failed to create the respective ordered extent, then it means that
1256 * when we reserved the extent we decremented the extent's size from
1257 * the data space_info's bytes_may_use counter and incremented the
1258 * space_info's bytes_reserved counter by the same amount. We must make
1259 * sure extent_clear_unlock_delalloc() does not try to decrement again
1260 * the data space_info's bytes_may_use counter, therefore we do not pass
1261 * it the flag EXTENT_CLEAR_DATA_RESV.
1263 if (extent_reserved) {
1264 extent_clear_unlock_delalloc(inode, start,
1265 start + cur_alloc_size - 1,
1269 start += cur_alloc_size;
1273 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1274 clear_bits | EXTENT_CLEAR_DATA_RESV,
1280 * work queue call back to started compression on a file and pages
1282 static noinline void async_cow_start(struct btrfs_work *work)
1284 struct async_chunk *async_chunk;
1285 int compressed_extents;
1287 async_chunk = container_of(work, struct async_chunk, work);
1289 compressed_extents = compress_file_range(async_chunk);
1290 if (compressed_extents == 0) {
1291 btrfs_add_delayed_iput(async_chunk->inode);
1292 async_chunk->inode = NULL;
1297 * work queue call back to submit previously compressed pages
1299 static noinline void async_cow_submit(struct btrfs_work *work)
1301 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1303 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1304 unsigned long nr_pages;
1306 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1310 * ->inode could be NULL if async_chunk_start has failed to compress,
1311 * in which case we don't have anything to submit, yet we need to
1312 * always adjust ->async_delalloc_pages as its paired with the init
1313 * happening in cow_file_range_async
1315 if (async_chunk->inode)
1316 submit_compressed_extents(async_chunk);
1318 /* atomic_sub_return implies a barrier */
1319 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1321 cond_wake_up_nomb(&fs_info->async_submit_wait);
1324 static noinline void async_cow_free(struct btrfs_work *work)
1326 struct async_chunk *async_chunk;
1328 async_chunk = container_of(work, struct async_chunk, work);
1329 if (async_chunk->inode)
1330 btrfs_add_delayed_iput(async_chunk->inode);
1331 if (async_chunk->blkcg_css)
1332 css_put(async_chunk->blkcg_css);
1334 * Since the pointer to 'pending' is at the beginning of the array of
1335 * async_chunk's, freeing it ensures the whole array has been freed.
1337 if (atomic_dec_and_test(async_chunk->pending))
1338 kvfree(async_chunk->pending);
1341 static int cow_file_range_async(struct btrfs_inode *inode,
1342 struct writeback_control *wbc,
1343 struct page *locked_page,
1344 u64 start, u64 end, int *page_started,
1345 unsigned long *nr_written)
1347 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1348 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1349 struct async_cow *ctx;
1350 struct async_chunk *async_chunk;
1351 unsigned long nr_pages;
1353 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1355 bool should_compress;
1357 const unsigned int write_flags = wbc_to_write_flags(wbc);
1359 unlock_extent(&inode->io_tree, start, end);
1361 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1362 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1364 should_compress = false;
1366 should_compress = true;
1369 nofs_flag = memalloc_nofs_save();
1370 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1371 memalloc_nofs_restore(nofs_flag);
1374 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1375 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1376 EXTENT_DO_ACCOUNTING;
1377 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1378 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1380 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1381 clear_bits, page_ops);
1385 async_chunk = ctx->chunks;
1386 atomic_set(&ctx->num_chunks, num_chunks);
1388 for (i = 0; i < num_chunks; i++) {
1389 if (should_compress)
1390 cur_end = min(end, start + SZ_512K - 1);
1395 * igrab is called higher up in the call chain, take only the
1396 * lightweight reference for the callback lifetime
1398 ihold(&inode->vfs_inode);
1399 async_chunk[i].pending = &ctx->num_chunks;
1400 async_chunk[i].inode = &inode->vfs_inode;
1401 async_chunk[i].start = start;
1402 async_chunk[i].end = cur_end;
1403 async_chunk[i].write_flags = write_flags;
1404 INIT_LIST_HEAD(&async_chunk[i].extents);
1407 * The locked_page comes all the way from writepage and its
1408 * the original page we were actually given. As we spread
1409 * this large delalloc region across multiple async_chunk
1410 * structs, only the first struct needs a pointer to locked_page
1412 * This way we don't need racey decisions about who is supposed
1417 * Depending on the compressibility, the pages might or
1418 * might not go through async. We want all of them to
1419 * be accounted against wbc once. Let's do it here
1420 * before the paths diverge. wbc accounting is used
1421 * only for foreign writeback detection and doesn't
1422 * need full accuracy. Just account the whole thing
1423 * against the first page.
1425 wbc_account_cgroup_owner(wbc, locked_page,
1427 async_chunk[i].locked_page = locked_page;
1430 async_chunk[i].locked_page = NULL;
1433 if (blkcg_css != blkcg_root_css) {
1435 async_chunk[i].blkcg_css = blkcg_css;
1437 async_chunk[i].blkcg_css = NULL;
1440 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1441 async_cow_submit, async_cow_free);
1443 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1444 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1446 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1448 *nr_written += nr_pages;
1449 start = cur_end + 1;
1455 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1456 struct page *locked_page, u64 start,
1457 u64 end, int *page_started,
1458 unsigned long *nr_written)
1462 ret = cow_file_range(inode, locked_page, start, end, page_started,
1470 __set_page_dirty_nobuffers(locked_page);
1471 account_page_redirty(locked_page);
1472 extent_write_locked_range(&inode->vfs_inode, start, end, WB_SYNC_ALL);
1478 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1479 u64 bytenr, u64 num_bytes)
1482 struct btrfs_ordered_sum *sums;
1485 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1486 bytenr + num_bytes - 1, &list, 0);
1487 if (ret == 0 && list_empty(&list))
1490 while (!list_empty(&list)) {
1491 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1492 list_del(&sums->list);
1500 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1501 const u64 start, const u64 end,
1502 int *page_started, unsigned long *nr_written)
1504 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1505 const bool is_reloc_ino = (inode->root->root_key.objectid ==
1506 BTRFS_DATA_RELOC_TREE_OBJECTID);
1507 const u64 range_bytes = end + 1 - start;
1508 struct extent_io_tree *io_tree = &inode->io_tree;
1509 u64 range_start = start;
1513 * If EXTENT_NORESERVE is set it means that when the buffered write was
1514 * made we had not enough available data space and therefore we did not
1515 * reserve data space for it, since we though we could do NOCOW for the
1516 * respective file range (either there is prealloc extent or the inode
1517 * has the NOCOW bit set).
1519 * However when we need to fallback to COW mode (because for example the
1520 * block group for the corresponding extent was turned to RO mode by a
1521 * scrub or relocation) we need to do the following:
1523 * 1) We increment the bytes_may_use counter of the data space info.
1524 * If COW succeeds, it allocates a new data extent and after doing
1525 * that it decrements the space info's bytes_may_use counter and
1526 * increments its bytes_reserved counter by the same amount (we do
1527 * this at btrfs_add_reserved_bytes()). So we need to increment the
1528 * bytes_may_use counter to compensate (when space is reserved at
1529 * buffered write time, the bytes_may_use counter is incremented);
1531 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1532 * that if the COW path fails for any reason, it decrements (through
1533 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1534 * data space info, which we incremented in the step above.
1536 * If we need to fallback to cow and the inode corresponds to a free
1537 * space cache inode or an inode of the data relocation tree, we must
1538 * also increment bytes_may_use of the data space_info for the same
1539 * reason. Space caches and relocated data extents always get a prealloc
1540 * extent for them, however scrub or balance may have set the block
1541 * group that contains that extent to RO mode and therefore force COW
1542 * when starting writeback.
1544 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1545 EXTENT_NORESERVE, 0);
1546 if (count > 0 || is_space_ino || is_reloc_ino) {
1548 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1549 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1551 if (is_space_ino || is_reloc_ino)
1552 bytes = range_bytes;
1554 spin_lock(&sinfo->lock);
1555 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1556 spin_unlock(&sinfo->lock);
1559 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1563 return cow_file_range(inode, locked_page, start, end, page_started,
1568 * when nowcow writeback call back. This checks for snapshots or COW copies
1569 * of the extents that exist in the file, and COWs the file as required.
1571 * If no cow copies or snapshots exist, we write directly to the existing
1574 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1575 struct page *locked_page,
1576 const u64 start, const u64 end,
1578 unsigned long *nr_written)
1580 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1581 struct btrfs_root *root = inode->root;
1582 struct btrfs_path *path;
1583 u64 cow_start = (u64)-1;
1584 u64 cur_offset = start;
1586 bool check_prev = true;
1587 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1588 u64 ino = btrfs_ino(inode);
1590 u64 disk_bytenr = 0;
1591 const bool force = inode->flags & BTRFS_INODE_NODATACOW;
1593 path = btrfs_alloc_path();
1595 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1596 EXTENT_LOCKED | EXTENT_DELALLOC |
1597 EXTENT_DO_ACCOUNTING |
1598 EXTENT_DEFRAG, PAGE_UNLOCK |
1599 PAGE_START_WRITEBACK |
1600 PAGE_END_WRITEBACK);
1605 struct btrfs_key found_key;
1606 struct btrfs_file_extent_item *fi;
1607 struct extent_buffer *leaf;
1617 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1623 * If there is no extent for our range when doing the initial
1624 * search, then go back to the previous slot as it will be the
1625 * one containing the search offset
1627 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1628 leaf = path->nodes[0];
1629 btrfs_item_key_to_cpu(leaf, &found_key,
1630 path->slots[0] - 1);
1631 if (found_key.objectid == ino &&
1632 found_key.type == BTRFS_EXTENT_DATA_KEY)
1637 /* Go to next leaf if we have exhausted the current one */
1638 leaf = path->nodes[0];
1639 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1640 ret = btrfs_next_leaf(root, path);
1642 if (cow_start != (u64)-1)
1643 cur_offset = cow_start;
1648 leaf = path->nodes[0];
1651 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1653 /* Didn't find anything for our INO */
1654 if (found_key.objectid > ino)
1657 * Keep searching until we find an EXTENT_ITEM or there are no
1658 * more extents for this inode
1660 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1661 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1666 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1667 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1668 found_key.offset > end)
1672 * If the found extent starts after requested offset, then
1673 * adjust extent_end to be right before this extent begins
1675 if (found_key.offset > cur_offset) {
1676 extent_end = found_key.offset;
1682 * Found extent which begins before our range and potentially
1685 fi = btrfs_item_ptr(leaf, path->slots[0],
1686 struct btrfs_file_extent_item);
1687 extent_type = btrfs_file_extent_type(leaf, fi);
1689 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1690 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1691 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1692 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1693 extent_offset = btrfs_file_extent_offset(leaf, fi);
1694 extent_end = found_key.offset +
1695 btrfs_file_extent_num_bytes(leaf, fi);
1697 btrfs_file_extent_disk_num_bytes(leaf, fi);
1699 * If the extent we got ends before our current offset,
1700 * skip to the next extent.
1702 if (extent_end <= cur_offset) {
1707 if (disk_bytenr == 0)
1709 /* Skip compressed/encrypted/encoded extents */
1710 if (btrfs_file_extent_compression(leaf, fi) ||
1711 btrfs_file_extent_encryption(leaf, fi) ||
1712 btrfs_file_extent_other_encoding(leaf, fi))
1715 * If extent is created before the last volume's snapshot
1716 * this implies the extent is shared, hence we can't do
1717 * nocow. This is the same check as in
1718 * btrfs_cross_ref_exist but without calling
1719 * btrfs_search_slot.
1721 if (!freespace_inode &&
1722 btrfs_file_extent_generation(leaf, fi) <=
1723 btrfs_root_last_snapshot(&root->root_item))
1725 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1729 * The following checks can be expensive, as they need to
1730 * take other locks and do btree or rbtree searches, so
1731 * release the path to avoid blocking other tasks for too
1734 btrfs_release_path(path);
1736 ret = btrfs_cross_ref_exist(root, ino,
1738 extent_offset, disk_bytenr, false);
1741 * ret could be -EIO if the above fails to read
1745 if (cow_start != (u64)-1)
1746 cur_offset = cow_start;
1750 WARN_ON_ONCE(freespace_inode);
1753 disk_bytenr += extent_offset;
1754 disk_bytenr += cur_offset - found_key.offset;
1755 num_bytes = min(end + 1, extent_end) - cur_offset;
1757 * If there are pending snapshots for this root, we
1758 * fall into common COW way
1760 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1763 * force cow if csum exists in the range.
1764 * this ensure that csum for a given extent are
1765 * either valid or do not exist.
1767 ret = csum_exist_in_range(fs_info, disk_bytenr,
1771 * ret could be -EIO if the above fails to read
1775 if (cow_start != (u64)-1)
1776 cur_offset = cow_start;
1779 WARN_ON_ONCE(freespace_inode);
1782 /* If the extent's block group is RO, we must COW */
1783 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1786 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1787 extent_end = found_key.offset + ram_bytes;
1788 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1789 /* Skip extents outside of our requested range */
1790 if (extent_end <= start) {
1795 /* If this triggers then we have a memory corruption */
1800 * If nocow is false then record the beginning of the range
1801 * that needs to be COWed
1804 if (cow_start == (u64)-1)
1805 cow_start = cur_offset;
1806 cur_offset = extent_end;
1807 if (cur_offset > end)
1809 if (!path->nodes[0])
1816 * COW range from cow_start to found_key.offset - 1. As the key
1817 * will contain the beginning of the first extent that can be
1818 * NOCOW, following one which needs to be COW'ed
1820 if (cow_start != (u64)-1) {
1821 ret = fallback_to_cow(inode, locked_page,
1822 cow_start, found_key.offset - 1,
1823 page_started, nr_written);
1826 cow_start = (u64)-1;
1829 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1830 u64 orig_start = found_key.offset - extent_offset;
1831 struct extent_map *em;
1833 em = create_io_em(inode, cur_offset, num_bytes,
1835 disk_bytenr, /* block_start */
1836 num_bytes, /* block_len */
1837 disk_num_bytes, /* orig_block_len */
1838 ram_bytes, BTRFS_COMPRESS_NONE,
1839 BTRFS_ORDERED_PREALLOC);
1844 free_extent_map(em);
1845 ret = btrfs_add_ordered_extent(inode, cur_offset,
1846 disk_bytenr, num_bytes,
1848 BTRFS_ORDERED_PREALLOC);
1850 btrfs_drop_extent_cache(inode, cur_offset,
1851 cur_offset + num_bytes - 1,
1856 ret = btrfs_add_ordered_extent(inode, cur_offset,
1857 disk_bytenr, num_bytes,
1859 BTRFS_ORDERED_NOCOW);
1865 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1868 if (root->root_key.objectid ==
1869 BTRFS_DATA_RELOC_TREE_OBJECTID)
1871 * Error handled later, as we must prevent
1872 * extent_clear_unlock_delalloc() in error handler
1873 * from freeing metadata of created ordered extent.
1875 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1878 extent_clear_unlock_delalloc(inode, cur_offset,
1879 cur_offset + num_bytes - 1,
1880 locked_page, EXTENT_LOCKED |
1882 EXTENT_CLEAR_DATA_RESV,
1883 PAGE_UNLOCK | PAGE_SET_ORDERED);
1885 cur_offset = extent_end;
1888 * btrfs_reloc_clone_csums() error, now we're OK to call error
1889 * handler, as metadata for created ordered extent will only
1890 * be freed by btrfs_finish_ordered_io().
1894 if (cur_offset > end)
1897 btrfs_release_path(path);
1899 if (cur_offset <= end && cow_start == (u64)-1)
1900 cow_start = cur_offset;
1902 if (cow_start != (u64)-1) {
1904 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1905 page_started, nr_written);
1912 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1914 if (ret && cur_offset < end)
1915 extent_clear_unlock_delalloc(inode, cur_offset, end,
1916 locked_page, EXTENT_LOCKED |
1917 EXTENT_DELALLOC | EXTENT_DEFRAG |
1918 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1919 PAGE_START_WRITEBACK |
1920 PAGE_END_WRITEBACK);
1921 btrfs_free_path(path);
1925 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
1927 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
1928 if (inode->defrag_bytes &&
1929 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
1938 * Function to process delayed allocation (create CoW) for ranges which are
1939 * being touched for the first time.
1941 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1942 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1943 struct writeback_control *wbc)
1946 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
1948 if (should_nocow(inode, start, end)) {
1950 ret = run_delalloc_nocow(inode, locked_page, start, end,
1951 page_started, nr_written);
1952 } else if (!inode_can_compress(inode) ||
1953 !inode_need_compress(inode, start, end)) {
1955 ret = run_delalloc_zoned(inode, locked_page, start, end,
1956 page_started, nr_written);
1958 ret = cow_file_range(inode, locked_page, start, end,
1959 page_started, nr_written, 1);
1961 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1962 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1963 page_started, nr_written);
1966 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1971 void btrfs_split_delalloc_extent(struct inode *inode,
1972 struct extent_state *orig, u64 split)
1976 /* not delalloc, ignore it */
1977 if (!(orig->state & EXTENT_DELALLOC))
1980 size = orig->end - orig->start + 1;
1981 if (size > BTRFS_MAX_EXTENT_SIZE) {
1986 * See the explanation in btrfs_merge_delalloc_extent, the same
1987 * applies here, just in reverse.
1989 new_size = orig->end - split + 1;
1990 num_extents = count_max_extents(new_size);
1991 new_size = split - orig->start;
1992 num_extents += count_max_extents(new_size);
1993 if (count_max_extents(size) >= num_extents)
1997 spin_lock(&BTRFS_I(inode)->lock);
1998 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1999 spin_unlock(&BTRFS_I(inode)->lock);
2003 * Handle merged delayed allocation extents so we can keep track of new extents
2004 * that are just merged onto old extents, such as when we are doing sequential
2005 * writes, so we can properly account for the metadata space we'll need.
2007 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
2008 struct extent_state *other)
2010 u64 new_size, old_size;
2013 /* not delalloc, ignore it */
2014 if (!(other->state & EXTENT_DELALLOC))
2017 if (new->start > other->start)
2018 new_size = new->end - other->start + 1;
2020 new_size = other->end - new->start + 1;
2022 /* we're not bigger than the max, unreserve the space and go */
2023 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
2024 spin_lock(&BTRFS_I(inode)->lock);
2025 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2026 spin_unlock(&BTRFS_I(inode)->lock);
2031 * We have to add up either side to figure out how many extents were
2032 * accounted for before we merged into one big extent. If the number of
2033 * extents we accounted for is <= the amount we need for the new range
2034 * then we can return, otherwise drop. Think of it like this
2038 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2039 * need 2 outstanding extents, on one side we have 1 and the other side
2040 * we have 1 so they are == and we can return. But in this case
2042 * [MAX_SIZE+4k][MAX_SIZE+4k]
2044 * Each range on their own accounts for 2 extents, but merged together
2045 * they are only 3 extents worth of accounting, so we need to drop in
2048 old_size = other->end - other->start + 1;
2049 num_extents = count_max_extents(old_size);
2050 old_size = new->end - new->start + 1;
2051 num_extents += count_max_extents(old_size);
2052 if (count_max_extents(new_size) >= num_extents)
2055 spin_lock(&BTRFS_I(inode)->lock);
2056 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2057 spin_unlock(&BTRFS_I(inode)->lock);
2060 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2061 struct inode *inode)
2063 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2065 spin_lock(&root->delalloc_lock);
2066 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2067 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2068 &root->delalloc_inodes);
2069 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2070 &BTRFS_I(inode)->runtime_flags);
2071 root->nr_delalloc_inodes++;
2072 if (root->nr_delalloc_inodes == 1) {
2073 spin_lock(&fs_info->delalloc_root_lock);
2074 BUG_ON(!list_empty(&root->delalloc_root));
2075 list_add_tail(&root->delalloc_root,
2076 &fs_info->delalloc_roots);
2077 spin_unlock(&fs_info->delalloc_root_lock);
2080 spin_unlock(&root->delalloc_lock);
2084 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2085 struct btrfs_inode *inode)
2087 struct btrfs_fs_info *fs_info = root->fs_info;
2089 if (!list_empty(&inode->delalloc_inodes)) {
2090 list_del_init(&inode->delalloc_inodes);
2091 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2092 &inode->runtime_flags);
2093 root->nr_delalloc_inodes--;
2094 if (!root->nr_delalloc_inodes) {
2095 ASSERT(list_empty(&root->delalloc_inodes));
2096 spin_lock(&fs_info->delalloc_root_lock);
2097 BUG_ON(list_empty(&root->delalloc_root));
2098 list_del_init(&root->delalloc_root);
2099 spin_unlock(&fs_info->delalloc_root_lock);
2104 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2105 struct btrfs_inode *inode)
2107 spin_lock(&root->delalloc_lock);
2108 __btrfs_del_delalloc_inode(root, inode);
2109 spin_unlock(&root->delalloc_lock);
2113 * Properly track delayed allocation bytes in the inode and to maintain the
2114 * list of inodes that have pending delalloc work to be done.
2116 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2119 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2121 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2124 * set_bit and clear bit hooks normally require _irqsave/restore
2125 * but in this case, we are only testing for the DELALLOC
2126 * bit, which is only set or cleared with irqs on
2128 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2129 struct btrfs_root *root = BTRFS_I(inode)->root;
2130 u64 len = state->end + 1 - state->start;
2131 u32 num_extents = count_max_extents(len);
2132 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2134 spin_lock(&BTRFS_I(inode)->lock);
2135 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2136 spin_unlock(&BTRFS_I(inode)->lock);
2138 /* For sanity tests */
2139 if (btrfs_is_testing(fs_info))
2142 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2143 fs_info->delalloc_batch);
2144 spin_lock(&BTRFS_I(inode)->lock);
2145 BTRFS_I(inode)->delalloc_bytes += len;
2146 if (*bits & EXTENT_DEFRAG)
2147 BTRFS_I(inode)->defrag_bytes += len;
2148 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2149 &BTRFS_I(inode)->runtime_flags))
2150 btrfs_add_delalloc_inodes(root, inode);
2151 spin_unlock(&BTRFS_I(inode)->lock);
2154 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2155 (*bits & EXTENT_DELALLOC_NEW)) {
2156 spin_lock(&BTRFS_I(inode)->lock);
2157 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2159 spin_unlock(&BTRFS_I(inode)->lock);
2164 * Once a range is no longer delalloc this function ensures that proper
2165 * accounting happens.
2167 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2168 struct extent_state *state, unsigned *bits)
2170 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2171 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2172 u64 len = state->end + 1 - state->start;
2173 u32 num_extents = count_max_extents(len);
2175 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2176 spin_lock(&inode->lock);
2177 inode->defrag_bytes -= len;
2178 spin_unlock(&inode->lock);
2182 * set_bit and clear bit hooks normally require _irqsave/restore
2183 * but in this case, we are only testing for the DELALLOC
2184 * bit, which is only set or cleared with irqs on
2186 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2187 struct btrfs_root *root = inode->root;
2188 bool do_list = !btrfs_is_free_space_inode(inode);
2190 spin_lock(&inode->lock);
2191 btrfs_mod_outstanding_extents(inode, -num_extents);
2192 spin_unlock(&inode->lock);
2195 * We don't reserve metadata space for space cache inodes so we
2196 * don't need to call delalloc_release_metadata if there is an
2199 if (*bits & EXTENT_CLEAR_META_RESV &&
2200 root != fs_info->tree_root)
2201 btrfs_delalloc_release_metadata(inode, len, false);
2203 /* For sanity tests. */
2204 if (btrfs_is_testing(fs_info))
2207 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2208 do_list && !(state->state & EXTENT_NORESERVE) &&
2209 (*bits & EXTENT_CLEAR_DATA_RESV))
2210 btrfs_free_reserved_data_space_noquota(fs_info, len);
2212 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2213 fs_info->delalloc_batch);
2214 spin_lock(&inode->lock);
2215 inode->delalloc_bytes -= len;
2216 if (do_list && inode->delalloc_bytes == 0 &&
2217 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2218 &inode->runtime_flags))
2219 btrfs_del_delalloc_inode(root, inode);
2220 spin_unlock(&inode->lock);
2223 if ((state->state & EXTENT_DELALLOC_NEW) &&
2224 (*bits & EXTENT_DELALLOC_NEW)) {
2225 spin_lock(&inode->lock);
2226 ASSERT(inode->new_delalloc_bytes >= len);
2227 inode->new_delalloc_bytes -= len;
2228 if (*bits & EXTENT_ADD_INODE_BYTES)
2229 inode_add_bytes(&inode->vfs_inode, len);
2230 spin_unlock(&inode->lock);
2235 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2236 * in a chunk's stripe. This function ensures that bios do not span a
2239 * @page - The page we are about to add to the bio
2240 * @size - size we want to add to the bio
2241 * @bio - bio we want to ensure is smaller than a stripe
2242 * @bio_flags - flags of the bio
2244 * return 1 if page cannot be added to the bio
2245 * return 0 if page can be added to the bio
2246 * return error otherwise
2248 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2249 unsigned long bio_flags)
2251 struct inode *inode = page->mapping->host;
2252 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2253 u64 logical = bio->bi_iter.bi_sector << 9;
2254 u32 bio_len = bio->bi_iter.bi_size;
2255 struct extent_map *em;
2257 struct btrfs_io_geometry geom;
2259 if (bio_flags & EXTENT_BIO_COMPRESSED)
2262 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
2265 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), logical, &geom);
2269 if (geom.len < bio_len + size)
2272 free_extent_map(em);
2277 * in order to insert checksums into the metadata in large chunks,
2278 * we wait until bio submission time. All the pages in the bio are
2279 * checksummed and sums are attached onto the ordered extent record.
2281 * At IO completion time the cums attached on the ordered extent record
2282 * are inserted into the btree
2284 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2285 u64 dio_file_offset)
2287 return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2291 * Split an extent_map at [start, start + len]
2293 * This function is intended to be used only for extract_ordered_extent().
2295 static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2298 struct extent_map_tree *em_tree = &inode->extent_tree;
2299 struct extent_map *em;
2300 struct extent_map *split_pre = NULL;
2301 struct extent_map *split_mid = NULL;
2302 struct extent_map *split_post = NULL;
2305 unsigned long flags;
2308 if (pre == 0 && post == 0)
2311 split_pre = alloc_extent_map();
2313 split_mid = alloc_extent_map();
2315 split_post = alloc_extent_map();
2316 if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2321 ASSERT(pre + post < len);
2323 lock_extent(&inode->io_tree, start, start + len - 1);
2324 write_lock(&em_tree->lock);
2325 em = lookup_extent_mapping(em_tree, start, len);
2331 ASSERT(em->len == len);
2332 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2333 ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2336 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2337 clear_bit(EXTENT_FLAG_LOGGING, &flags);
2338 modified = !list_empty(&em->list);
2340 /* First, replace the em with a new extent_map starting from * em->start */
2341 split_pre->start = em->start;
2342 split_pre->len = (pre ? pre : em->len - post);
2343 split_pre->orig_start = split_pre->start;
2344 split_pre->block_start = em->block_start;
2345 split_pre->block_len = split_pre->len;
2346 split_pre->orig_block_len = split_pre->block_len;
2347 split_pre->ram_bytes = split_pre->len;
2348 split_pre->flags = flags;
2349 split_pre->compress_type = em->compress_type;
2350 split_pre->generation = em->generation;
2352 replace_extent_mapping(em_tree, em, split_pre, modified);
2355 * Now we only have an extent_map at:
2356 * [em->start, em->start + pre] if pre != 0
2357 * [em->start, em->start + em->len - post] if pre == 0
2361 /* Insert the middle extent_map */
2362 split_mid->start = em->start + pre;
2363 split_mid->len = em->len - pre - post;
2364 split_mid->orig_start = split_mid->start;
2365 split_mid->block_start = em->block_start + pre;
2366 split_mid->block_len = split_mid->len;
2367 split_mid->orig_block_len = split_mid->block_len;
2368 split_mid->ram_bytes = split_mid->len;
2369 split_mid->flags = flags;
2370 split_mid->compress_type = em->compress_type;
2371 split_mid->generation = em->generation;
2372 add_extent_mapping(em_tree, split_mid, modified);
2376 split_post->start = em->start + em->len - post;
2377 split_post->len = post;
2378 split_post->orig_start = split_post->start;
2379 split_post->block_start = em->block_start + em->len - post;
2380 split_post->block_len = split_post->len;
2381 split_post->orig_block_len = split_post->block_len;
2382 split_post->ram_bytes = split_post->len;
2383 split_post->flags = flags;
2384 split_post->compress_type = em->compress_type;
2385 split_post->generation = em->generation;
2386 add_extent_mapping(em_tree, split_post, modified);
2390 free_extent_map(em);
2391 /* Once for the tree */
2392 free_extent_map(em);
2395 write_unlock(&em_tree->lock);
2396 unlock_extent(&inode->io_tree, start, start + len - 1);
2398 free_extent_map(split_pre);
2399 free_extent_map(split_mid);
2400 free_extent_map(split_post);
2405 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2406 struct bio *bio, loff_t file_offset)
2408 struct btrfs_ordered_extent *ordered;
2409 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2411 u64 len = bio->bi_iter.bi_size;
2412 u64 end = start + len;
2417 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2418 if (WARN_ON_ONCE(!ordered))
2419 return BLK_STS_IOERR;
2421 /* No need to split */
2422 if (ordered->disk_num_bytes == len)
2425 /* We cannot split once end_bio'd ordered extent */
2426 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2431 /* We cannot split a compressed ordered extent */
2432 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2437 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2438 /* bio must be in one ordered extent */
2439 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2444 /* Checksum list should be empty */
2445 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2450 file_len = ordered->num_bytes;
2451 pre = start - ordered->disk_bytenr;
2452 post = ordered_end - end;
2454 ret = btrfs_split_ordered_extent(ordered, pre, post);
2457 ret = split_zoned_em(inode, file_offset, file_len, pre, post);
2460 btrfs_put_ordered_extent(ordered);
2462 return errno_to_blk_status(ret);
2466 * extent_io.c submission hook. This does the right thing for csum calculation
2467 * on write, or reading the csums from the tree before a read.
2469 * Rules about async/sync submit,
2470 * a) read: sync submit
2472 * b) write without checksum: sync submit
2474 * c) write with checksum:
2475 * c-1) if bio is issued by fsync: sync submit
2476 * (sync_writers != 0)
2478 * c-2) if root is reloc root: sync submit
2479 * (only in case of buffered IO)
2481 * c-3) otherwise: async submit
2483 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2484 int mirror_num, unsigned long bio_flags)
2487 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2488 struct btrfs_root *root = BTRFS_I(inode)->root;
2489 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2490 blk_status_t ret = 0;
2492 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2494 skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2495 !fs_info->csum_root;
2497 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2498 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2500 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2501 struct page *page = bio_first_bvec_all(bio)->bv_page;
2502 loff_t file_offset = page_offset(page);
2504 ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2509 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2510 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2514 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2515 ret = btrfs_submit_compressed_read(inode, bio,
2521 * Lookup bio sums does extra checks around whether we
2522 * need to csum or not, which is why we ignore skip_sum
2525 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2530 } else if (async && !skip_sum) {
2531 /* csum items have already been cloned */
2532 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2534 /* we're doing a write, do the async checksumming */
2535 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2536 0, btrfs_submit_bio_start);
2538 } else if (!skip_sum) {
2539 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2545 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2549 bio->bi_status = ret;
2556 * given a list of ordered sums record them in the inode. This happens
2557 * at IO completion time based on sums calculated at bio submission time.
2559 static int add_pending_csums(struct btrfs_trans_handle *trans,
2560 struct list_head *list)
2562 struct btrfs_ordered_sum *sum;
2565 list_for_each_entry(sum, list, list) {
2566 trans->adding_csums = true;
2567 ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2568 trans->adding_csums = false;
2575 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2578 struct extent_state **cached_state)
2580 u64 search_start = start;
2581 const u64 end = start + len - 1;
2583 while (search_start < end) {
2584 const u64 search_len = end - search_start + 1;
2585 struct extent_map *em;
2589 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2593 if (em->block_start != EXTENT_MAP_HOLE)
2597 if (em->start < search_start)
2598 em_len -= search_start - em->start;
2599 if (em_len > search_len)
2600 em_len = search_len;
2602 ret = set_extent_bit(&inode->io_tree, search_start,
2603 search_start + em_len - 1,
2604 EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2607 search_start = extent_map_end(em);
2608 free_extent_map(em);
2615 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2616 unsigned int extra_bits,
2617 struct extent_state **cached_state)
2619 WARN_ON(PAGE_ALIGNED(end));
2621 if (start >= i_size_read(&inode->vfs_inode) &&
2622 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2624 * There can't be any extents following eof in this case so just
2625 * set the delalloc new bit for the range directly.
2627 extra_bits |= EXTENT_DELALLOC_NEW;
2631 ret = btrfs_find_new_delalloc_bytes(inode, start,
2638 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2642 /* see btrfs_writepage_start_hook for details on why this is required */
2643 struct btrfs_writepage_fixup {
2645 struct inode *inode;
2646 struct btrfs_work work;
2649 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2651 struct btrfs_writepage_fixup *fixup;
2652 struct btrfs_ordered_extent *ordered;
2653 struct extent_state *cached_state = NULL;
2654 struct extent_changeset *data_reserved = NULL;
2656 struct btrfs_inode *inode;
2660 bool free_delalloc_space = true;
2662 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2664 inode = BTRFS_I(fixup->inode);
2665 page_start = page_offset(page);
2666 page_end = page_offset(page) + PAGE_SIZE - 1;
2669 * This is similar to page_mkwrite, we need to reserve the space before
2670 * we take the page lock.
2672 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2678 * Before we queued this fixup, we took a reference on the page.
2679 * page->mapping may go NULL, but it shouldn't be moved to a different
2682 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2684 * Unfortunately this is a little tricky, either
2686 * 1) We got here and our page had already been dealt with and
2687 * we reserved our space, thus ret == 0, so we need to just
2688 * drop our space reservation and bail. This can happen the
2689 * first time we come into the fixup worker, or could happen
2690 * while waiting for the ordered extent.
2691 * 2) Our page was already dealt with, but we happened to get an
2692 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2693 * this case we obviously don't have anything to release, but
2694 * because the page was already dealt with we don't want to
2695 * mark the page with an error, so make sure we're resetting
2696 * ret to 0. This is why we have this check _before_ the ret
2697 * check, because we do not want to have a surprise ENOSPC
2698 * when the page was already properly dealt with.
2701 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2702 btrfs_delalloc_release_space(inode, data_reserved,
2703 page_start, PAGE_SIZE,
2711 * We can't mess with the page state unless it is locked, so now that
2712 * it is locked bail if we failed to make our space reservation.
2717 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2719 /* already ordered? We're done */
2720 if (PageOrdered(page))
2723 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2725 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2728 btrfs_start_ordered_extent(ordered, 1);
2729 btrfs_put_ordered_extent(ordered);
2733 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2739 * Everything went as planned, we're now the owner of a dirty page with
2740 * delayed allocation bits set and space reserved for our COW
2743 * The page was dirty when we started, nothing should have cleaned it.
2745 BUG_ON(!PageDirty(page));
2746 free_delalloc_space = false;
2748 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2749 if (free_delalloc_space)
2750 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2752 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2757 * We hit ENOSPC or other errors. Update the mapping and page
2758 * to reflect the errors and clean the page.
2760 mapping_set_error(page->mapping, ret);
2761 end_extent_writepage(page, ret, page_start, page_end);
2762 clear_page_dirty_for_io(page);
2765 ClearPageChecked(page);
2769 extent_changeset_free(data_reserved);
2771 * As a precaution, do a delayed iput in case it would be the last iput
2772 * that could need flushing space. Recursing back to fixup worker would
2775 btrfs_add_delayed_iput(&inode->vfs_inode);
2779 * There are a few paths in the higher layers of the kernel that directly
2780 * set the page dirty bit without asking the filesystem if it is a
2781 * good idea. This causes problems because we want to make sure COW
2782 * properly happens and the data=ordered rules are followed.
2784 * In our case any range that doesn't have the ORDERED bit set
2785 * hasn't been properly setup for IO. We kick off an async process
2786 * to fix it up. The async helper will wait for ordered extents, set
2787 * the delalloc bit and make it safe to write the page.
2789 int btrfs_writepage_cow_fixup(struct page *page)
2791 struct inode *inode = page->mapping->host;
2792 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2793 struct btrfs_writepage_fixup *fixup;
2795 /* This page has ordered extent covering it already */
2796 if (PageOrdered(page))
2800 * PageChecked is set below when we create a fixup worker for this page,
2801 * don't try to create another one if we're already PageChecked()
2803 * The extent_io writepage code will redirty the page if we send back
2806 if (PageChecked(page))
2809 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2814 * We are already holding a reference to this inode from
2815 * write_cache_pages. We need to hold it because the space reservation
2816 * takes place outside of the page lock, and we can't trust
2817 * page->mapping outside of the page lock.
2820 SetPageChecked(page);
2822 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2824 fixup->inode = inode;
2825 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2830 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2831 struct btrfs_inode *inode, u64 file_pos,
2832 struct btrfs_file_extent_item *stack_fi,
2833 const bool update_inode_bytes,
2834 u64 qgroup_reserved)
2836 struct btrfs_root *root = inode->root;
2837 const u64 sectorsize = root->fs_info->sectorsize;
2838 struct btrfs_path *path;
2839 struct extent_buffer *leaf;
2840 struct btrfs_key ins;
2841 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2842 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2843 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2844 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2845 struct btrfs_drop_extents_args drop_args = { 0 };
2848 path = btrfs_alloc_path();
2853 * we may be replacing one extent in the tree with another.
2854 * The new extent is pinned in the extent map, and we don't want
2855 * to drop it from the cache until it is completely in the btree.
2857 * So, tell btrfs_drop_extents to leave this extent in the cache.
2858 * the caller is expected to unpin it and allow it to be merged
2861 drop_args.path = path;
2862 drop_args.start = file_pos;
2863 drop_args.end = file_pos + num_bytes;
2864 drop_args.replace_extent = true;
2865 drop_args.extent_item_size = sizeof(*stack_fi);
2866 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2870 if (!drop_args.extent_inserted) {
2871 ins.objectid = btrfs_ino(inode);
2872 ins.offset = file_pos;
2873 ins.type = BTRFS_EXTENT_DATA_KEY;
2875 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2880 leaf = path->nodes[0];
2881 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2882 write_extent_buffer(leaf, stack_fi,
2883 btrfs_item_ptr_offset(leaf, path->slots[0]),
2884 sizeof(struct btrfs_file_extent_item));
2886 btrfs_mark_buffer_dirty(leaf);
2887 btrfs_release_path(path);
2890 * If we dropped an inline extent here, we know the range where it is
2891 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2892 * number of bytes only for that range containing the inline extent.
2893 * The remaining of the range will be processed when clearning the
2894 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2896 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2897 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2899 inline_size = drop_args.bytes_found - inline_size;
2900 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2901 drop_args.bytes_found -= inline_size;
2902 num_bytes -= sectorsize;
2905 if (update_inode_bytes)
2906 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2908 ins.objectid = disk_bytenr;
2909 ins.offset = disk_num_bytes;
2910 ins.type = BTRFS_EXTENT_ITEM_KEY;
2912 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2916 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2917 file_pos, qgroup_reserved, &ins);
2919 btrfs_free_path(path);
2924 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2927 struct btrfs_block_group *cache;
2929 cache = btrfs_lookup_block_group(fs_info, start);
2932 spin_lock(&cache->lock);
2933 cache->delalloc_bytes -= len;
2934 spin_unlock(&cache->lock);
2936 btrfs_put_block_group(cache);
2939 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2940 struct btrfs_ordered_extent *oe)
2942 struct btrfs_file_extent_item stack_fi;
2944 bool update_inode_bytes;
2946 memset(&stack_fi, 0, sizeof(stack_fi));
2947 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2948 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2949 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2950 oe->disk_num_bytes);
2951 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2952 logical_len = oe->truncated_len;
2954 logical_len = oe->num_bytes;
2955 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2956 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2957 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2958 /* Encryption and other encoding is reserved and all 0 */
2961 * For delalloc, when completing an ordered extent we update the inode's
2962 * bytes when clearing the range in the inode's io tree, so pass false
2963 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
2964 * except if the ordered extent was truncated.
2966 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
2967 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
2969 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
2970 oe->file_offset, &stack_fi,
2971 update_inode_bytes, oe->qgroup_rsv);
2975 * As ordered data IO finishes, this gets called so we can finish
2976 * an ordered extent if the range of bytes in the file it covers are
2979 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2981 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
2982 struct btrfs_root *root = inode->root;
2983 struct btrfs_fs_info *fs_info = root->fs_info;
2984 struct btrfs_trans_handle *trans = NULL;
2985 struct extent_io_tree *io_tree = &inode->io_tree;
2986 struct extent_state *cached_state = NULL;
2988 int compress_type = 0;
2990 u64 logical_len = ordered_extent->num_bytes;
2991 bool freespace_inode;
2992 bool truncated = false;
2993 bool clear_reserved_extent = true;
2994 unsigned int clear_bits = EXTENT_DEFRAG;
2996 start = ordered_extent->file_offset;
2997 end = start + ordered_extent->num_bytes - 1;
2999 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3000 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3001 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
3002 clear_bits |= EXTENT_DELALLOC_NEW;
3004 freespace_inode = btrfs_is_free_space_inode(inode);
3006 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3011 if (ordered_extent->bdev)
3012 btrfs_rewrite_logical_zoned(ordered_extent);
3014 btrfs_free_io_failure_record(inode, start, end);
3016 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3018 logical_len = ordered_extent->truncated_len;
3019 /* Truncated the entire extent, don't bother adding */
3024 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3025 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3027 btrfs_inode_safe_disk_i_size_write(inode, 0);
3028 if (freespace_inode)
3029 trans = btrfs_join_transaction_spacecache(root);
3031 trans = btrfs_join_transaction(root);
3032 if (IS_ERR(trans)) {
3033 ret = PTR_ERR(trans);
3037 trans->block_rsv = &inode->block_rsv;
3038 ret = btrfs_update_inode_fallback(trans, root, inode);
3039 if (ret) /* -ENOMEM or corruption */
3040 btrfs_abort_transaction(trans, ret);
3044 clear_bits |= EXTENT_LOCKED;
3045 lock_extent_bits(io_tree, start, end, &cached_state);
3047 if (freespace_inode)
3048 trans = btrfs_join_transaction_spacecache(root);
3050 trans = btrfs_join_transaction(root);
3051 if (IS_ERR(trans)) {
3052 ret = PTR_ERR(trans);
3057 trans->block_rsv = &inode->block_rsv;
3059 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3060 compress_type = ordered_extent->compress_type;
3061 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3062 BUG_ON(compress_type);
3063 ret = btrfs_mark_extent_written(trans, inode,
3064 ordered_extent->file_offset,
3065 ordered_extent->file_offset +
3068 BUG_ON(root == fs_info->tree_root);
3069 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3071 clear_reserved_extent = false;
3072 btrfs_release_delalloc_bytes(fs_info,
3073 ordered_extent->disk_bytenr,
3074 ordered_extent->disk_num_bytes);
3077 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3078 ordered_extent->num_bytes, trans->transid);
3080 btrfs_abort_transaction(trans, ret);
3084 ret = add_pending_csums(trans, &ordered_extent->list);
3086 btrfs_abort_transaction(trans, ret);
3091 * If this is a new delalloc range, clear its new delalloc flag to
3092 * update the inode's number of bytes. This needs to be done first
3093 * before updating the inode item.
3095 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3096 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3097 clear_extent_bit(&inode->io_tree, start, end,
3098 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3099 0, 0, &cached_state);
3101 btrfs_inode_safe_disk_i_size_write(inode, 0);
3102 ret = btrfs_update_inode_fallback(trans, root, inode);
3103 if (ret) { /* -ENOMEM or corruption */
3104 btrfs_abort_transaction(trans, ret);
3109 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3110 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
3114 btrfs_end_transaction(trans);
3116 if (ret || truncated) {
3117 u64 unwritten_start = start;
3120 * If we failed to finish this ordered extent for any reason we
3121 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3122 * extent, and mark the inode with the error if it wasn't
3123 * already set. Any error during writeback would have already
3124 * set the mapping error, so we need to set it if we're the ones
3125 * marking this ordered extent as failed.
3127 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3128 &ordered_extent->flags))
3129 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3132 unwritten_start += logical_len;
3133 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3135 /* Drop the cache for the part of the extent we didn't write. */
3136 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3139 * If the ordered extent had an IOERR or something else went
3140 * wrong we need to return the space for this ordered extent
3141 * back to the allocator. We only free the extent in the
3142 * truncated case if we didn't write out the extent at all.
3144 * If we made it past insert_reserved_file_extent before we
3145 * errored out then we don't need to do this as the accounting
3146 * has already been done.
3148 if ((ret || !logical_len) &&
3149 clear_reserved_extent &&
3150 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3151 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3153 * Discard the range before returning it back to the
3156 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3157 btrfs_discard_extent(fs_info,
3158 ordered_extent->disk_bytenr,
3159 ordered_extent->disk_num_bytes,
3161 btrfs_free_reserved_extent(fs_info,
3162 ordered_extent->disk_bytenr,
3163 ordered_extent->disk_num_bytes, 1);
3168 * This needs to be done to make sure anybody waiting knows we are done
3169 * updating everything for this ordered extent.
3171 btrfs_remove_ordered_extent(inode, ordered_extent);
3174 btrfs_put_ordered_extent(ordered_extent);
3175 /* once for the tree */
3176 btrfs_put_ordered_extent(ordered_extent);
3181 static void finish_ordered_fn(struct btrfs_work *work)
3183 struct btrfs_ordered_extent *ordered_extent;
3184 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3185 btrfs_finish_ordered_io(ordered_extent);
3188 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3189 struct page *page, u64 start,
3190 u64 end, bool uptodate)
3192 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3194 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start,
3195 finish_ordered_fn, uptodate);
3199 * check_data_csum - verify checksum of one sector of uncompressed data
3201 * @io_bio: btrfs_io_bio which contains the csum
3202 * @bio_offset: offset to the beginning of the bio (in bytes)
3203 * @page: page where is the data to be verified
3204 * @pgoff: offset inside the page
3205 * @start: logical offset in the file
3207 * The length of such check is always one sector size.
3209 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
3210 u32 bio_offset, struct page *page, u32 pgoff,
3213 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3214 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3216 u32 len = fs_info->sectorsize;
3217 const u32 csum_size = fs_info->csum_size;
3218 unsigned int offset_sectors;
3220 u8 csum[BTRFS_CSUM_SIZE];
3222 ASSERT(pgoff + len <= PAGE_SIZE);
3224 offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3225 csum_expected = ((u8 *)io_bio->csum) + offset_sectors * csum_size;
3227 kaddr = kmap_atomic(page);
3228 shash->tfm = fs_info->csum_shash;
3230 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3232 if (memcmp(csum, csum_expected, csum_size))
3235 kunmap_atomic(kaddr);
3238 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3239 io_bio->mirror_num);
3241 btrfs_dev_stat_inc_and_print(io_bio->device,
3242 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3243 memset(kaddr + pgoff, 1, len);
3244 flush_dcache_page(page);
3245 kunmap_atomic(kaddr);
3250 * When reads are done, we need to check csums to verify the data is correct.
3251 * if there's a match, we allow the bio to finish. If not, the code in
3252 * extent_io.c will try to find good copies for us.
3254 * @bio_offset: offset to the beginning of the bio (in bytes)
3255 * @start: file offset of the range start
3256 * @end: file offset of the range end (inclusive)
3258 * Return a bitmap where bit set means a csum mismatch, and bit not set means
3261 unsigned int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u32 bio_offset,
3262 struct page *page, u64 start, u64 end)
3264 struct inode *inode = page->mapping->host;
3265 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3266 struct btrfs_root *root = BTRFS_I(inode)->root;
3267 const u32 sectorsize = root->fs_info->sectorsize;
3269 unsigned int result = 0;
3271 if (PageChecked(page)) {
3272 ClearPageChecked(page);
3277 * For subpage case, above PageChecked is not safe as it's not subpage
3279 * But for now only cow fixup and compressed read utilize PageChecked
3280 * flag, while in this context we can easily use io_bio->csum to
3281 * determine if we really need to do csum verification.
3283 * So for now, just exit if io_bio->csum is NULL, as it means it's
3284 * compressed read, and its compressed data csum has already been
3287 if (io_bio->csum == NULL)
3290 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3293 if (!root->fs_info->csum_root)
3296 ASSERT(page_offset(page) <= start &&
3297 end <= page_offset(page) + PAGE_SIZE - 1);
3298 for (pg_off = offset_in_page(start);
3299 pg_off < offset_in_page(end);
3300 pg_off += sectorsize, bio_offset += sectorsize) {
3301 u64 file_offset = pg_off + page_offset(page);
3304 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3305 test_range_bit(io_tree, file_offset,
3306 file_offset + sectorsize - 1,
3307 EXTENT_NODATASUM, 1, NULL)) {
3308 /* Skip the range without csum for data reloc inode */
3309 clear_extent_bits(io_tree, file_offset,
3310 file_offset + sectorsize - 1,
3314 ret = check_data_csum(inode, io_bio, bio_offset, page, pg_off,
3315 page_offset(page) + pg_off);
3317 const int nr_bit = (pg_off - offset_in_page(start)) >>
3318 root->fs_info->sectorsize_bits;
3320 result |= (1U << nr_bit);
3327 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3329 * @inode: The inode we want to perform iput on
3331 * This function uses the generic vfs_inode::i_count to track whether we should
3332 * just decrement it (in case it's > 1) or if this is the last iput then link
3333 * the inode to the delayed iput machinery. Delayed iputs are processed at
3334 * transaction commit time/superblock commit/cleaner kthread.
3336 void btrfs_add_delayed_iput(struct inode *inode)
3338 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3339 struct btrfs_inode *binode = BTRFS_I(inode);
3341 if (atomic_add_unless(&inode->i_count, -1, 1))
3344 atomic_inc(&fs_info->nr_delayed_iputs);
3345 spin_lock(&fs_info->delayed_iput_lock);
3346 ASSERT(list_empty(&binode->delayed_iput));
3347 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3348 spin_unlock(&fs_info->delayed_iput_lock);
3349 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3350 wake_up_process(fs_info->cleaner_kthread);
3353 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3354 struct btrfs_inode *inode)
3356 list_del_init(&inode->delayed_iput);
3357 spin_unlock(&fs_info->delayed_iput_lock);
3358 iput(&inode->vfs_inode);
3359 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3360 wake_up(&fs_info->delayed_iputs_wait);
3361 spin_lock(&fs_info->delayed_iput_lock);
3364 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3365 struct btrfs_inode *inode)
3367 if (!list_empty(&inode->delayed_iput)) {
3368 spin_lock(&fs_info->delayed_iput_lock);
3369 if (!list_empty(&inode->delayed_iput))
3370 run_delayed_iput_locked(fs_info, inode);
3371 spin_unlock(&fs_info->delayed_iput_lock);
3375 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3378 spin_lock(&fs_info->delayed_iput_lock);
3379 while (!list_empty(&fs_info->delayed_iputs)) {
3380 struct btrfs_inode *inode;
3382 inode = list_first_entry(&fs_info->delayed_iputs,
3383 struct btrfs_inode, delayed_iput);
3384 run_delayed_iput_locked(fs_info, inode);
3385 cond_resched_lock(&fs_info->delayed_iput_lock);
3387 spin_unlock(&fs_info->delayed_iput_lock);
3391 * Wait for flushing all delayed iputs
3393 * @fs_info: the filesystem
3395 * This will wait on any delayed iputs that are currently running with KILLABLE
3396 * set. Once they are all done running we will return, unless we are killed in
3397 * which case we return EINTR. This helps in user operations like fallocate etc
3398 * that might get blocked on the iputs.
3400 * Return EINTR if we were killed, 0 if nothing's pending
3402 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3404 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3405 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3412 * This creates an orphan entry for the given inode in case something goes wrong
3413 * in the middle of an unlink.
3415 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3416 struct btrfs_inode *inode)
3420 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3421 if (ret && ret != -EEXIST) {
3422 btrfs_abort_transaction(trans, ret);
3430 * We have done the delete so we can go ahead and remove the orphan item for
3431 * this particular inode.
3433 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3434 struct btrfs_inode *inode)
3436 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3440 * this cleans up any orphans that may be left on the list from the last use
3443 int btrfs_orphan_cleanup(struct btrfs_root *root)
3445 struct btrfs_fs_info *fs_info = root->fs_info;
3446 struct btrfs_path *path;
3447 struct extent_buffer *leaf;
3448 struct btrfs_key key, found_key;
3449 struct btrfs_trans_handle *trans;
3450 struct inode *inode;
3451 u64 last_objectid = 0;
3452 int ret = 0, nr_unlink = 0;
3454 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3457 path = btrfs_alloc_path();
3462 path->reada = READA_BACK;
3464 key.objectid = BTRFS_ORPHAN_OBJECTID;
3465 key.type = BTRFS_ORPHAN_ITEM_KEY;
3466 key.offset = (u64)-1;
3469 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3474 * if ret == 0 means we found what we were searching for, which
3475 * is weird, but possible, so only screw with path if we didn't
3476 * find the key and see if we have stuff that matches
3480 if (path->slots[0] == 0)
3485 /* pull out the item */
3486 leaf = path->nodes[0];
3487 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3489 /* make sure the item matches what we want */
3490 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3492 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3495 /* release the path since we're done with it */
3496 btrfs_release_path(path);
3499 * this is where we are basically btrfs_lookup, without the
3500 * crossing root thing. we store the inode number in the
3501 * offset of the orphan item.
3504 if (found_key.offset == last_objectid) {
3506 "Error removing orphan entry, stopping orphan cleanup");
3511 last_objectid = found_key.offset;
3513 found_key.objectid = found_key.offset;
3514 found_key.type = BTRFS_INODE_ITEM_KEY;
3515 found_key.offset = 0;
3516 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3517 ret = PTR_ERR_OR_ZERO(inode);
3518 if (ret && ret != -ENOENT)
3521 if (ret == -ENOENT && root == fs_info->tree_root) {
3522 struct btrfs_root *dead_root;
3523 int is_dead_root = 0;
3526 * This is an orphan in the tree root. Currently these
3527 * could come from 2 sources:
3528 * a) a root (snapshot/subvolume) deletion in progress
3529 * b) a free space cache inode
3530 * We need to distinguish those two, as the orphan item
3531 * for a root must not get deleted before the deletion
3532 * of the snapshot/subvolume's tree completes.
3534 * btrfs_find_orphan_roots() ran before us, which has
3535 * found all deleted roots and loaded them into
3536 * fs_info->fs_roots_radix. So here we can find if an
3537 * orphan item corresponds to a deleted root by looking
3538 * up the root from that radix tree.
3541 spin_lock(&fs_info->fs_roots_radix_lock);
3542 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3543 (unsigned long)found_key.objectid);
3544 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3546 spin_unlock(&fs_info->fs_roots_radix_lock);
3549 /* prevent this orphan from being found again */
3550 key.offset = found_key.objectid - 1;
3557 * If we have an inode with links, there are a couple of
3558 * possibilities. Old kernels (before v3.12) used to create an
3559 * orphan item for truncate indicating that there were possibly
3560 * extent items past i_size that needed to be deleted. In v3.12,
3561 * truncate was changed to update i_size in sync with the extent
3562 * items, but the (useless) orphan item was still created. Since
3563 * v4.18, we don't create the orphan item for truncate at all.
3565 * So, this item could mean that we need to do a truncate, but
3566 * only if this filesystem was last used on a pre-v3.12 kernel
3567 * and was not cleanly unmounted. The odds of that are quite
3568 * slim, and it's a pain to do the truncate now, so just delete
3571 * It's also possible that this orphan item was supposed to be
3572 * deleted but wasn't. The inode number may have been reused,
3573 * but either way, we can delete the orphan item.
3575 if (ret == -ENOENT || inode->i_nlink) {
3578 trans = btrfs_start_transaction(root, 1);
3579 if (IS_ERR(trans)) {
3580 ret = PTR_ERR(trans);
3583 btrfs_debug(fs_info, "auto deleting %Lu",
3584 found_key.objectid);
3585 ret = btrfs_del_orphan_item(trans, root,
3586 found_key.objectid);
3587 btrfs_end_transaction(trans);
3595 /* this will do delete_inode and everything for us */
3598 /* release the path since we're done with it */
3599 btrfs_release_path(path);
3601 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3603 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3604 trans = btrfs_join_transaction(root);
3606 btrfs_end_transaction(trans);
3610 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3614 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3615 btrfs_free_path(path);
3620 * very simple check to peek ahead in the leaf looking for xattrs. If we
3621 * don't find any xattrs, we know there can't be any acls.
3623 * slot is the slot the inode is in, objectid is the objectid of the inode
3625 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3626 int slot, u64 objectid,
3627 int *first_xattr_slot)
3629 u32 nritems = btrfs_header_nritems(leaf);
3630 struct btrfs_key found_key;
3631 static u64 xattr_access = 0;
3632 static u64 xattr_default = 0;
3635 if (!xattr_access) {
3636 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3637 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3638 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3639 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3643 *first_xattr_slot = -1;
3644 while (slot < nritems) {
3645 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3647 /* we found a different objectid, there must not be acls */
3648 if (found_key.objectid != objectid)
3651 /* we found an xattr, assume we've got an acl */
3652 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3653 if (*first_xattr_slot == -1)
3654 *first_xattr_slot = slot;
3655 if (found_key.offset == xattr_access ||
3656 found_key.offset == xattr_default)
3661 * we found a key greater than an xattr key, there can't
3662 * be any acls later on
3664 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3671 * it goes inode, inode backrefs, xattrs, extents,
3672 * so if there are a ton of hard links to an inode there can
3673 * be a lot of backrefs. Don't waste time searching too hard,
3674 * this is just an optimization
3679 /* we hit the end of the leaf before we found an xattr or
3680 * something larger than an xattr. We have to assume the inode
3683 if (*first_xattr_slot == -1)
3684 *first_xattr_slot = slot;
3689 * read an inode from the btree into the in-memory inode
3691 static int btrfs_read_locked_inode(struct inode *inode,
3692 struct btrfs_path *in_path)
3694 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3695 struct btrfs_path *path = in_path;
3696 struct extent_buffer *leaf;
3697 struct btrfs_inode_item *inode_item;
3698 struct btrfs_root *root = BTRFS_I(inode)->root;
3699 struct btrfs_key location;
3704 bool filled = false;
3705 int first_xattr_slot;
3707 ret = btrfs_fill_inode(inode, &rdev);
3712 path = btrfs_alloc_path();
3717 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3719 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3721 if (path != in_path)
3722 btrfs_free_path(path);
3726 leaf = path->nodes[0];
3731 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3732 struct btrfs_inode_item);
3733 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3734 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3735 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3736 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3737 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3738 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3739 round_up(i_size_read(inode), fs_info->sectorsize));
3741 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3742 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3744 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3745 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3747 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3748 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3750 BTRFS_I(inode)->i_otime.tv_sec =
3751 btrfs_timespec_sec(leaf, &inode_item->otime);
3752 BTRFS_I(inode)->i_otime.tv_nsec =
3753 btrfs_timespec_nsec(leaf, &inode_item->otime);
3755 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3756 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3757 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3759 inode_set_iversion_queried(inode,
3760 btrfs_inode_sequence(leaf, inode_item));
3761 inode->i_generation = BTRFS_I(inode)->generation;
3763 rdev = btrfs_inode_rdev(leaf, inode_item);
3765 BTRFS_I(inode)->index_cnt = (u64)-1;
3766 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3770 * If we were modified in the current generation and evicted from memory
3771 * and then re-read we need to do a full sync since we don't have any
3772 * idea about which extents were modified before we were evicted from
3775 * This is required for both inode re-read from disk and delayed inode
3776 * in delayed_nodes_tree.
3778 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3779 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3780 &BTRFS_I(inode)->runtime_flags);
3783 * We don't persist the id of the transaction where an unlink operation
3784 * against the inode was last made. So here we assume the inode might
3785 * have been evicted, and therefore the exact value of last_unlink_trans
3786 * lost, and set it to last_trans to avoid metadata inconsistencies
3787 * between the inode and its parent if the inode is fsync'ed and the log
3788 * replayed. For example, in the scenario:
3791 * ln mydir/foo mydir/bar
3794 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3795 * xfs_io -c fsync mydir/foo
3797 * mount fs, triggers fsync log replay
3799 * We must make sure that when we fsync our inode foo we also log its
3800 * parent inode, otherwise after log replay the parent still has the
3801 * dentry with the "bar" name but our inode foo has a link count of 1
3802 * and doesn't have an inode ref with the name "bar" anymore.
3804 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3805 * but it guarantees correctness at the expense of occasional full
3806 * transaction commits on fsync if our inode is a directory, or if our
3807 * inode is not a directory, logging its parent unnecessarily.
3809 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3812 * Same logic as for last_unlink_trans. We don't persist the generation
3813 * of the last transaction where this inode was used for a reflink
3814 * operation, so after eviction and reloading the inode we must be
3815 * pessimistic and assume the last transaction that modified the inode.
3817 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3820 if (inode->i_nlink != 1 ||
3821 path->slots[0] >= btrfs_header_nritems(leaf))
3824 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3825 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3828 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3829 if (location.type == BTRFS_INODE_REF_KEY) {
3830 struct btrfs_inode_ref *ref;
3832 ref = (struct btrfs_inode_ref *)ptr;
3833 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3834 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3835 struct btrfs_inode_extref *extref;
3837 extref = (struct btrfs_inode_extref *)ptr;
3838 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3843 * try to precache a NULL acl entry for files that don't have
3844 * any xattrs or acls
3846 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3847 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3848 if (first_xattr_slot != -1) {
3849 path->slots[0] = first_xattr_slot;
3850 ret = btrfs_load_inode_props(inode, path);
3853 "error loading props for ino %llu (root %llu): %d",
3854 btrfs_ino(BTRFS_I(inode)),
3855 root->root_key.objectid, ret);
3857 if (path != in_path)
3858 btrfs_free_path(path);
3861 cache_no_acl(inode);
3863 switch (inode->i_mode & S_IFMT) {
3865 inode->i_mapping->a_ops = &btrfs_aops;
3866 inode->i_fop = &btrfs_file_operations;
3867 inode->i_op = &btrfs_file_inode_operations;
3870 inode->i_fop = &btrfs_dir_file_operations;
3871 inode->i_op = &btrfs_dir_inode_operations;
3874 inode->i_op = &btrfs_symlink_inode_operations;
3875 inode_nohighmem(inode);
3876 inode->i_mapping->a_ops = &btrfs_aops;
3879 inode->i_op = &btrfs_special_inode_operations;
3880 init_special_inode(inode, inode->i_mode, rdev);
3884 btrfs_sync_inode_flags_to_i_flags(inode);
3889 * given a leaf and an inode, copy the inode fields into the leaf
3891 static void fill_inode_item(struct btrfs_trans_handle *trans,
3892 struct extent_buffer *leaf,
3893 struct btrfs_inode_item *item,
3894 struct inode *inode)
3896 struct btrfs_map_token token;
3898 btrfs_init_map_token(&token, leaf);
3900 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3901 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3902 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3903 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3904 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3906 btrfs_set_token_timespec_sec(&token, &item->atime,
3907 inode->i_atime.tv_sec);
3908 btrfs_set_token_timespec_nsec(&token, &item->atime,
3909 inode->i_atime.tv_nsec);
3911 btrfs_set_token_timespec_sec(&token, &item->mtime,
3912 inode->i_mtime.tv_sec);
3913 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3914 inode->i_mtime.tv_nsec);
3916 btrfs_set_token_timespec_sec(&token, &item->ctime,
3917 inode->i_ctime.tv_sec);
3918 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3919 inode->i_ctime.tv_nsec);
3921 btrfs_set_token_timespec_sec(&token, &item->otime,
3922 BTRFS_I(inode)->i_otime.tv_sec);
3923 btrfs_set_token_timespec_nsec(&token, &item->otime,
3924 BTRFS_I(inode)->i_otime.tv_nsec);
3926 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3927 btrfs_set_token_inode_generation(&token, item,
3928 BTRFS_I(inode)->generation);
3929 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3930 btrfs_set_token_inode_transid(&token, item, trans->transid);
3931 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3932 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3933 btrfs_set_token_inode_block_group(&token, item, 0);
3937 * copy everything in the in-memory inode into the btree.
3939 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3940 struct btrfs_root *root,
3941 struct btrfs_inode *inode)
3943 struct btrfs_inode_item *inode_item;
3944 struct btrfs_path *path;
3945 struct extent_buffer *leaf;
3948 path = btrfs_alloc_path();
3952 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
3959 leaf = path->nodes[0];
3960 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3961 struct btrfs_inode_item);
3963 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
3964 btrfs_mark_buffer_dirty(leaf);
3965 btrfs_set_inode_last_trans(trans, inode);
3968 btrfs_free_path(path);
3973 * copy everything in the in-memory inode into the btree.
3975 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3976 struct btrfs_root *root,
3977 struct btrfs_inode *inode)
3979 struct btrfs_fs_info *fs_info = root->fs_info;
3983 * If the inode is a free space inode, we can deadlock during commit
3984 * if we put it into the delayed code.
3986 * The data relocation inode should also be directly updated
3989 if (!btrfs_is_free_space_inode(inode)
3990 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3991 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3992 btrfs_update_root_times(trans, root);
3994 ret = btrfs_delayed_update_inode(trans, root, inode);
3996 btrfs_set_inode_last_trans(trans, inode);
4000 return btrfs_update_inode_item(trans, root, inode);
4003 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4004 struct btrfs_root *root, struct btrfs_inode *inode)
4008 ret = btrfs_update_inode(trans, root, inode);
4010 return btrfs_update_inode_item(trans, root, inode);
4015 * unlink helper that gets used here in inode.c and in the tree logging
4016 * recovery code. It remove a link in a directory with a given name, and
4017 * also drops the back refs in the inode to the directory
4019 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4020 struct btrfs_root *root,
4021 struct btrfs_inode *dir,
4022 struct btrfs_inode *inode,
4023 const char *name, int name_len)
4025 struct btrfs_fs_info *fs_info = root->fs_info;
4026 struct btrfs_path *path;
4028 struct btrfs_dir_item *di;
4030 u64 ino = btrfs_ino(inode);
4031 u64 dir_ino = btrfs_ino(dir);
4033 path = btrfs_alloc_path();
4039 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4040 name, name_len, -1);
4041 if (IS_ERR_OR_NULL(di)) {
4042 ret = di ? PTR_ERR(di) : -ENOENT;
4045 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4048 btrfs_release_path(path);
4051 * If we don't have dir index, we have to get it by looking up
4052 * the inode ref, since we get the inode ref, remove it directly,
4053 * it is unnecessary to do delayed deletion.
4055 * But if we have dir index, needn't search inode ref to get it.
4056 * Since the inode ref is close to the inode item, it is better
4057 * that we delay to delete it, and just do this deletion when
4058 * we update the inode item.
4060 if (inode->dir_index) {
4061 ret = btrfs_delayed_delete_inode_ref(inode);
4063 index = inode->dir_index;
4068 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4072 "failed to delete reference to %.*s, inode %llu parent %llu",
4073 name_len, name, ino, dir_ino);
4074 btrfs_abort_transaction(trans, ret);
4078 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4080 btrfs_abort_transaction(trans, ret);
4084 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4086 if (ret != 0 && ret != -ENOENT) {
4087 btrfs_abort_transaction(trans, ret);
4091 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4096 btrfs_abort_transaction(trans, ret);
4099 * If we have a pending delayed iput we could end up with the final iput
4100 * being run in btrfs-cleaner context. If we have enough of these built
4101 * up we can end up burning a lot of time in btrfs-cleaner without any
4102 * way to throttle the unlinks. Since we're currently holding a ref on
4103 * the inode we can run the delayed iput here without any issues as the
4104 * final iput won't be done until after we drop the ref we're currently
4107 btrfs_run_delayed_iput(fs_info, inode);
4109 btrfs_free_path(path);
4113 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4114 inode_inc_iversion(&inode->vfs_inode);
4115 inode_inc_iversion(&dir->vfs_inode);
4116 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4117 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4118 ret = btrfs_update_inode(trans, root, dir);
4123 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4124 struct btrfs_root *root,
4125 struct btrfs_inode *dir, struct btrfs_inode *inode,
4126 const char *name, int name_len)
4129 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4131 drop_nlink(&inode->vfs_inode);
4132 ret = btrfs_update_inode(trans, root, inode);
4138 * helper to start transaction for unlink and rmdir.
4140 * unlink and rmdir are special in btrfs, they do not always free space, so
4141 * if we cannot make our reservations the normal way try and see if there is
4142 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4143 * allow the unlink to occur.
4145 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4147 struct btrfs_root *root = BTRFS_I(dir)->root;
4150 * 1 for the possible orphan item
4151 * 1 for the dir item
4152 * 1 for the dir index
4153 * 1 for the inode ref
4156 return btrfs_start_transaction_fallback_global_rsv(root, 5);
4159 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4161 struct btrfs_root *root = BTRFS_I(dir)->root;
4162 struct btrfs_trans_handle *trans;
4163 struct inode *inode = d_inode(dentry);
4166 trans = __unlink_start_trans(dir);
4168 return PTR_ERR(trans);
4170 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4173 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4174 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4175 dentry->d_name.len);
4179 if (inode->i_nlink == 0) {
4180 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4186 btrfs_end_transaction(trans);
4187 btrfs_btree_balance_dirty(root->fs_info);
4191 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4192 struct inode *dir, struct dentry *dentry)
4194 struct btrfs_root *root = BTRFS_I(dir)->root;
4195 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4196 struct btrfs_path *path;
4197 struct extent_buffer *leaf;
4198 struct btrfs_dir_item *di;
4199 struct btrfs_key key;
4200 const char *name = dentry->d_name.name;
4201 int name_len = dentry->d_name.len;
4205 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4207 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4208 objectid = inode->root->root_key.objectid;
4209 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4210 objectid = inode->location.objectid;
4216 path = btrfs_alloc_path();
4220 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4221 name, name_len, -1);
4222 if (IS_ERR_OR_NULL(di)) {
4223 ret = di ? PTR_ERR(di) : -ENOENT;
4227 leaf = path->nodes[0];
4228 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4229 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4230 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4232 btrfs_abort_transaction(trans, ret);
4235 btrfs_release_path(path);
4238 * This is a placeholder inode for a subvolume we didn't have a
4239 * reference to at the time of the snapshot creation. In the meantime
4240 * we could have renamed the real subvol link into our snapshot, so
4241 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4242 * Instead simply lookup the dir_index_item for this entry so we can
4243 * remove it. Otherwise we know we have a ref to the root and we can
4244 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4246 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4247 di = btrfs_search_dir_index_item(root, path, dir_ino,
4249 if (IS_ERR_OR_NULL(di)) {
4254 btrfs_abort_transaction(trans, ret);
4258 leaf = path->nodes[0];
4259 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4261 btrfs_release_path(path);
4263 ret = btrfs_del_root_ref(trans, objectid,
4264 root->root_key.objectid, dir_ino,
4265 &index, name, name_len);
4267 btrfs_abort_transaction(trans, ret);
4272 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4274 btrfs_abort_transaction(trans, ret);
4278 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4279 inode_inc_iversion(dir);
4280 dir->i_mtime = dir->i_ctime = current_time(dir);
4281 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4283 btrfs_abort_transaction(trans, ret);
4285 btrfs_free_path(path);
4290 * Helper to check if the subvolume references other subvolumes or if it's
4293 static noinline int may_destroy_subvol(struct btrfs_root *root)
4295 struct btrfs_fs_info *fs_info = root->fs_info;
4296 struct btrfs_path *path;
4297 struct btrfs_dir_item *di;
4298 struct btrfs_key key;
4302 path = btrfs_alloc_path();
4306 /* Make sure this root isn't set as the default subvol */
4307 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4308 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4309 dir_id, "default", 7, 0);
4310 if (di && !IS_ERR(di)) {
4311 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4312 if (key.objectid == root->root_key.objectid) {
4315 "deleting default subvolume %llu is not allowed",
4319 btrfs_release_path(path);
4322 key.objectid = root->root_key.objectid;
4323 key.type = BTRFS_ROOT_REF_KEY;
4324 key.offset = (u64)-1;
4326 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4332 if (path->slots[0] > 0) {
4334 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4335 if (key.objectid == root->root_key.objectid &&
4336 key.type == BTRFS_ROOT_REF_KEY)
4340 btrfs_free_path(path);
4344 /* Delete all dentries for inodes belonging to the root */
4345 static void btrfs_prune_dentries(struct btrfs_root *root)
4347 struct btrfs_fs_info *fs_info = root->fs_info;
4348 struct rb_node *node;
4349 struct rb_node *prev;
4350 struct btrfs_inode *entry;
4351 struct inode *inode;
4354 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4355 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4357 spin_lock(&root->inode_lock);
4359 node = root->inode_tree.rb_node;
4363 entry = rb_entry(node, struct btrfs_inode, rb_node);
4365 if (objectid < btrfs_ino(entry))
4366 node = node->rb_left;
4367 else if (objectid > btrfs_ino(entry))
4368 node = node->rb_right;
4374 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4375 if (objectid <= btrfs_ino(entry)) {
4379 prev = rb_next(prev);
4383 entry = rb_entry(node, struct btrfs_inode, rb_node);
4384 objectid = btrfs_ino(entry) + 1;
4385 inode = igrab(&entry->vfs_inode);
4387 spin_unlock(&root->inode_lock);
4388 if (atomic_read(&inode->i_count) > 1)
4389 d_prune_aliases(inode);
4391 * btrfs_drop_inode will have it removed from the inode
4392 * cache when its usage count hits zero.
4396 spin_lock(&root->inode_lock);
4400 if (cond_resched_lock(&root->inode_lock))
4403 node = rb_next(node);
4405 spin_unlock(&root->inode_lock);
4408 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4410 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4411 struct btrfs_root *root = BTRFS_I(dir)->root;
4412 struct inode *inode = d_inode(dentry);
4413 struct btrfs_root *dest = BTRFS_I(inode)->root;
4414 struct btrfs_trans_handle *trans;
4415 struct btrfs_block_rsv block_rsv;
4420 * Don't allow to delete a subvolume with send in progress. This is
4421 * inside the inode lock so the error handling that has to drop the bit
4422 * again is not run concurrently.
4424 spin_lock(&dest->root_item_lock);
4425 if (dest->send_in_progress) {
4426 spin_unlock(&dest->root_item_lock);
4428 "attempt to delete subvolume %llu during send",
4429 dest->root_key.objectid);
4432 root_flags = btrfs_root_flags(&dest->root_item);
4433 btrfs_set_root_flags(&dest->root_item,
4434 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4435 spin_unlock(&dest->root_item_lock);
4437 down_write(&fs_info->subvol_sem);
4439 ret = may_destroy_subvol(dest);
4443 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4445 * One for dir inode,
4446 * two for dir entries,
4447 * two for root ref/backref.
4449 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4453 trans = btrfs_start_transaction(root, 0);
4454 if (IS_ERR(trans)) {
4455 ret = PTR_ERR(trans);
4458 trans->block_rsv = &block_rsv;
4459 trans->bytes_reserved = block_rsv.size;
4461 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4463 ret = btrfs_unlink_subvol(trans, dir, dentry);
4465 btrfs_abort_transaction(trans, ret);
4469 ret = btrfs_record_root_in_trans(trans, dest);
4471 btrfs_abort_transaction(trans, ret);
4475 memset(&dest->root_item.drop_progress, 0,
4476 sizeof(dest->root_item.drop_progress));
4477 btrfs_set_root_drop_level(&dest->root_item, 0);
4478 btrfs_set_root_refs(&dest->root_item, 0);
4480 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4481 ret = btrfs_insert_orphan_item(trans,
4483 dest->root_key.objectid);
4485 btrfs_abort_transaction(trans, ret);
4490 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4491 BTRFS_UUID_KEY_SUBVOL,
4492 dest->root_key.objectid);
4493 if (ret && ret != -ENOENT) {
4494 btrfs_abort_transaction(trans, ret);
4497 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4498 ret = btrfs_uuid_tree_remove(trans,
4499 dest->root_item.received_uuid,
4500 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4501 dest->root_key.objectid);
4502 if (ret && ret != -ENOENT) {
4503 btrfs_abort_transaction(trans, ret);
4508 free_anon_bdev(dest->anon_dev);
4511 trans->block_rsv = NULL;
4512 trans->bytes_reserved = 0;
4513 ret = btrfs_end_transaction(trans);
4514 inode->i_flags |= S_DEAD;
4516 btrfs_subvolume_release_metadata(root, &block_rsv);
4518 up_write(&fs_info->subvol_sem);
4520 spin_lock(&dest->root_item_lock);
4521 root_flags = btrfs_root_flags(&dest->root_item);
4522 btrfs_set_root_flags(&dest->root_item,
4523 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4524 spin_unlock(&dest->root_item_lock);
4526 d_invalidate(dentry);
4527 btrfs_prune_dentries(dest);
4528 ASSERT(dest->send_in_progress == 0);
4534 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4536 struct inode *inode = d_inode(dentry);
4538 struct btrfs_root *root = BTRFS_I(dir)->root;
4539 struct btrfs_trans_handle *trans;
4540 u64 last_unlink_trans;
4542 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4544 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4545 return btrfs_delete_subvolume(dir, dentry);
4547 trans = __unlink_start_trans(dir);
4549 return PTR_ERR(trans);
4551 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4552 err = btrfs_unlink_subvol(trans, dir, dentry);
4556 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4560 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4562 /* now the directory is empty */
4563 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4564 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4565 dentry->d_name.len);
4567 btrfs_i_size_write(BTRFS_I(inode), 0);
4569 * Propagate the last_unlink_trans value of the deleted dir to
4570 * its parent directory. This is to prevent an unrecoverable
4571 * log tree in the case we do something like this:
4573 * 2) create snapshot under dir foo
4574 * 3) delete the snapshot
4577 * 6) fsync foo or some file inside foo
4579 if (last_unlink_trans >= trans->transid)
4580 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4583 btrfs_end_transaction(trans);
4584 btrfs_btree_balance_dirty(root->fs_info);
4590 * Return this if we need to call truncate_block for the last bit of the
4593 #define NEED_TRUNCATE_BLOCK 1
4596 * Remove inode items from a given root.
4598 * @trans: A transaction handle.
4599 * @root: The root from which to remove items.
4600 * @inode: The inode whose items we want to remove.
4601 * @new_size: The new i_size for the inode. This is only applicable when
4602 * @min_type is BTRFS_EXTENT_DATA_KEY, must be 0 otherwise.
4603 * @min_type: The minimum key type to remove. All keys with a type
4604 * greater than this value are removed and all keys with
4605 * this type are removed only if their offset is >= @new_size.
4606 * @extents_found: Output parameter that will contain the number of file
4607 * extent items that were removed or adjusted to the new
4608 * inode i_size. The caller is responsible for initializing
4609 * the counter. Also, it can be NULL if the caller does not
4610 * need this counter.
4612 * Remove all keys associated with the inode from the given root that have a key
4613 * with a type greater than or equals to @min_type. When @min_type has a value of
4614 * BTRFS_EXTENT_DATA_KEY, only remove file extent items that have an offset value
4615 * greater than or equals to @new_size. If a file extent item that starts before
4616 * @new_size and ends after it is found, its length is adjusted.
4618 * Returns: 0 on success, < 0 on error and NEED_TRUNCATE_BLOCK when @min_type is
4619 * BTRFS_EXTENT_DATA_KEY and the caller must truncate the last block.
4621 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4622 struct btrfs_root *root,
4623 struct btrfs_inode *inode,
4624 u64 new_size, u32 min_type,
4627 struct btrfs_fs_info *fs_info = root->fs_info;
4628 struct btrfs_path *path;
4629 struct extent_buffer *leaf;
4630 struct btrfs_file_extent_item *fi;
4631 struct btrfs_key key;
4632 struct btrfs_key found_key;
4633 u64 extent_start = 0;
4634 u64 extent_num_bytes = 0;
4635 u64 extent_offset = 0;
4637 u64 last_size = new_size;
4638 u32 found_type = (u8)-1;
4641 int pending_del_nr = 0;
4642 int pending_del_slot = 0;
4643 int extent_type = -1;
4645 u64 ino = btrfs_ino(inode);
4646 u64 bytes_deleted = 0;
4647 bool be_nice = false;
4648 bool should_throttle = false;
4649 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4650 struct extent_state *cached_state = NULL;
4652 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4655 * For non-free space inodes and non-shareable roots, we want to back
4656 * off from time to time. This means all inodes in subvolume roots,
4657 * reloc roots, and data reloc roots.
4659 if (!btrfs_is_free_space_inode(inode) &&
4660 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4663 path = btrfs_alloc_path();
4666 path->reada = READA_BACK;
4668 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4669 lock_extent_bits(&inode->io_tree, lock_start, (u64)-1,
4673 * We want to drop from the next block forward in case this
4674 * new size is not block aligned since we will be keeping the
4675 * last block of the extent just the way it is.
4677 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4678 fs_info->sectorsize),
4683 * This function is also used to drop the items in the log tree before
4684 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4685 * it is used to drop the logged items. So we shouldn't kill the delayed
4688 if (min_type == 0 && root == inode->root)
4689 btrfs_kill_delayed_inode_items(inode);
4692 key.offset = (u64)-1;
4697 * with a 16K leaf size and 128MB extents, you can actually queue
4698 * up a huge file in a single leaf. Most of the time that
4699 * bytes_deleted is > 0, it will be huge by the time we get here
4701 if (be_nice && bytes_deleted > SZ_32M &&
4702 btrfs_should_end_transaction(trans)) {
4707 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4713 /* there are no items in the tree for us to truncate, we're
4716 if (path->slots[0] == 0)
4722 u64 clear_start = 0, clear_len = 0;
4725 leaf = path->nodes[0];
4726 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4727 found_type = found_key.type;
4729 if (found_key.objectid != ino)
4732 if (found_type < min_type)
4735 item_end = found_key.offset;
4736 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4737 fi = btrfs_item_ptr(leaf, path->slots[0],
4738 struct btrfs_file_extent_item);
4739 extent_type = btrfs_file_extent_type(leaf, fi);
4740 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4742 btrfs_file_extent_num_bytes(leaf, fi);
4744 trace_btrfs_truncate_show_fi_regular(
4745 inode, leaf, fi, found_key.offset);
4746 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4747 item_end += btrfs_file_extent_ram_bytes(leaf,
4750 trace_btrfs_truncate_show_fi_inline(
4751 inode, leaf, fi, path->slots[0],
4756 if (found_type > min_type) {
4759 if (item_end < new_size)
4761 if (found_key.offset >= new_size)
4767 /* FIXME, shrink the extent if the ref count is only 1 */
4768 if (found_type != BTRFS_EXTENT_DATA_KEY)
4771 if (extents_found != NULL)
4774 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4777 clear_start = found_key.offset;
4778 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4780 u64 orig_num_bytes =
4781 btrfs_file_extent_num_bytes(leaf, fi);
4782 extent_num_bytes = ALIGN(new_size -
4784 fs_info->sectorsize);
4785 clear_start = ALIGN(new_size, fs_info->sectorsize);
4786 btrfs_set_file_extent_num_bytes(leaf, fi,
4788 num_dec = (orig_num_bytes -
4790 if (test_bit(BTRFS_ROOT_SHAREABLE,
4793 inode_sub_bytes(&inode->vfs_inode,
4795 btrfs_mark_buffer_dirty(leaf);
4798 btrfs_file_extent_disk_num_bytes(leaf,
4800 extent_offset = found_key.offset -
4801 btrfs_file_extent_offset(leaf, fi);
4803 /* FIXME blocksize != 4096 */
4804 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4805 if (extent_start != 0) {
4807 if (test_bit(BTRFS_ROOT_SHAREABLE,
4809 inode_sub_bytes(&inode->vfs_inode,
4813 clear_len = num_dec;
4814 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4816 * we can't truncate inline items that have had
4820 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4821 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4822 btrfs_file_extent_compression(leaf, fi) == 0) {
4823 u32 size = (u32)(new_size - found_key.offset);
4825 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4826 size = btrfs_file_extent_calc_inline_size(size);
4827 btrfs_truncate_item(path, size, 1);
4828 } else if (!del_item) {
4830 * We have to bail so the last_size is set to
4831 * just before this extent.
4833 ret = NEED_TRUNCATE_BLOCK;
4837 * Inline extents are special, we just treat
4838 * them as a full sector worth in the file
4839 * extent tree just for simplicity sake.
4841 clear_len = fs_info->sectorsize;
4844 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4845 inode_sub_bytes(&inode->vfs_inode,
4846 item_end + 1 - new_size);
4850 * We use btrfs_truncate_inode_items() to clean up log trees for
4851 * multiple fsyncs, and in this case we don't want to clear the
4852 * file extent range because it's just the log.
4854 if (root == inode->root) {
4855 ret = btrfs_inode_clear_file_extent_range(inode,
4856 clear_start, clear_len);
4858 btrfs_abort_transaction(trans, ret);
4864 last_size = found_key.offset;
4866 last_size = new_size;
4868 if (!pending_del_nr) {
4869 /* no pending yet, add ourselves */
4870 pending_del_slot = path->slots[0];
4872 } else if (pending_del_nr &&
4873 path->slots[0] + 1 == pending_del_slot) {
4874 /* hop on the pending chunk */
4876 pending_del_slot = path->slots[0];
4883 should_throttle = false;
4886 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4887 struct btrfs_ref ref = { 0 };
4889 bytes_deleted += extent_num_bytes;
4891 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4892 extent_start, extent_num_bytes, 0);
4893 ref.real_root = root->root_key.objectid;
4894 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4895 ino, extent_offset);
4896 ret = btrfs_free_extent(trans, &ref);
4898 btrfs_abort_transaction(trans, ret);
4902 if (btrfs_should_throttle_delayed_refs(trans))
4903 should_throttle = true;
4907 if (found_type == BTRFS_INODE_ITEM_KEY)
4910 if (path->slots[0] == 0 ||
4911 path->slots[0] != pending_del_slot ||
4913 if (pending_del_nr) {
4914 ret = btrfs_del_items(trans, root, path,
4918 btrfs_abort_transaction(trans, ret);
4923 btrfs_release_path(path);
4926 * We can generate a lot of delayed refs, so we need to
4927 * throttle every once and a while and make sure we're
4928 * adding enough space to keep up with the work we are
4929 * generating. Since we hold a transaction here we
4930 * can't flush, and we don't want to FLUSH_LIMIT because
4931 * we could have generated too many delayed refs to
4932 * actually allocate, so just bail if we're short and
4933 * let the normal reservation dance happen higher up.
4935 if (should_throttle) {
4936 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4937 BTRFS_RESERVE_NO_FLUSH);
4949 if (ret >= 0 && pending_del_nr) {
4952 err = btrfs_del_items(trans, root, path, pending_del_slot,
4955 btrfs_abort_transaction(trans, err);
4959 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4960 ASSERT(last_size >= new_size);
4961 if (!ret && last_size > new_size)
4962 last_size = new_size;
4963 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4964 unlock_extent_cached(&inode->io_tree, lock_start, (u64)-1,
4968 btrfs_free_path(path);
4973 * btrfs_truncate_block - read, zero a chunk and write a block
4974 * @inode - inode that we're zeroing
4975 * @from - the offset to start zeroing
4976 * @len - the length to zero, 0 to zero the entire range respective to the
4978 * @front - zero up to the offset instead of from the offset on
4980 * This will find the block for the "from" offset and cow the block and zero the
4981 * part we want to zero. This is used with truncate and hole punching.
4983 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4986 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4987 struct address_space *mapping = inode->vfs_inode.i_mapping;
4988 struct extent_io_tree *io_tree = &inode->io_tree;
4989 struct btrfs_ordered_extent *ordered;
4990 struct extent_state *cached_state = NULL;
4991 struct extent_changeset *data_reserved = NULL;
4992 bool only_release_metadata = false;
4993 u32 blocksize = fs_info->sectorsize;
4994 pgoff_t index = from >> PAGE_SHIFT;
4995 unsigned offset = from & (blocksize - 1);
4997 gfp_t mask = btrfs_alloc_write_mask(mapping);
4998 size_t write_bytes = blocksize;
5003 if (IS_ALIGNED(offset, blocksize) &&
5004 (!len || IS_ALIGNED(len, blocksize)))
5007 block_start = round_down(from, blocksize);
5008 block_end = block_start + blocksize - 1;
5010 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
5013 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
5014 /* For nocow case, no need to reserve data space */
5015 only_release_metadata = true;
5020 ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
5022 if (!only_release_metadata)
5023 btrfs_free_reserved_data_space(inode, data_reserved,
5024 block_start, blocksize);
5028 page = find_or_create_page(mapping, index, mask);
5030 btrfs_delalloc_release_space(inode, data_reserved, block_start,
5032 btrfs_delalloc_release_extents(inode, blocksize);
5036 ret = set_page_extent_mapped(page);
5040 if (!PageUptodate(page)) {
5041 ret = btrfs_readpage(NULL, page);
5043 if (page->mapping != mapping) {
5048 if (!PageUptodate(page)) {
5053 wait_on_page_writeback(page);
5055 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
5057 ordered = btrfs_lookup_ordered_extent(inode, block_start);
5059 unlock_extent_cached(io_tree, block_start, block_end,
5063 btrfs_start_ordered_extent(ordered, 1);
5064 btrfs_put_ordered_extent(ordered);
5068 clear_extent_bit(&inode->io_tree, block_start, block_end,
5069 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5070 0, 0, &cached_state);
5072 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5075 unlock_extent_cached(io_tree, block_start, block_end,
5080 if (offset != blocksize) {
5082 len = blocksize - offset;
5084 memzero_page(page, (block_start - page_offset(page)),
5087 memzero_page(page, (block_start - page_offset(page)) + offset,
5089 flush_dcache_page(page);
5091 ClearPageChecked(page);
5092 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
5093 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
5095 if (only_release_metadata)
5096 set_extent_bit(&inode->io_tree, block_start, block_end,
5097 EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
5101 if (only_release_metadata)
5102 btrfs_delalloc_release_metadata(inode, blocksize, true);
5104 btrfs_delalloc_release_space(inode, data_reserved,
5105 block_start, blocksize, true);
5107 btrfs_delalloc_release_extents(inode, blocksize);
5111 if (only_release_metadata)
5112 btrfs_check_nocow_unlock(inode);
5113 extent_changeset_free(data_reserved);
5117 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
5118 u64 offset, u64 len)
5120 struct btrfs_fs_info *fs_info = root->fs_info;
5121 struct btrfs_trans_handle *trans;
5122 struct btrfs_drop_extents_args drop_args = { 0 };
5126 * If NO_HOLES is enabled, we don't need to do anything.
5127 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5128 * or btrfs_update_inode() will be called, which guarantee that the next
5129 * fsync will know this inode was changed and needs to be logged.
5131 if (btrfs_fs_incompat(fs_info, NO_HOLES))
5135 * 1 - for the one we're dropping
5136 * 1 - for the one we're adding
5137 * 1 - for updating the inode.
5139 trans = btrfs_start_transaction(root, 3);
5141 return PTR_ERR(trans);
5143 drop_args.start = offset;
5144 drop_args.end = offset + len;
5145 drop_args.drop_cache = true;
5147 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5149 btrfs_abort_transaction(trans, ret);
5150 btrfs_end_transaction(trans);
5154 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
5155 offset, 0, 0, len, 0, len, 0, 0, 0);
5157 btrfs_abort_transaction(trans, ret);
5159 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5160 btrfs_update_inode(trans, root, inode);
5162 btrfs_end_transaction(trans);
5167 * This function puts in dummy file extents for the area we're creating a hole
5168 * for. So if we are truncating this file to a larger size we need to insert
5169 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5170 * the range between oldsize and size
5172 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5174 struct btrfs_root *root = inode->root;
5175 struct btrfs_fs_info *fs_info = root->fs_info;
5176 struct extent_io_tree *io_tree = &inode->io_tree;
5177 struct extent_map *em = NULL;
5178 struct extent_state *cached_state = NULL;
5179 struct extent_map_tree *em_tree = &inode->extent_tree;
5180 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5181 u64 block_end = ALIGN(size, fs_info->sectorsize);
5188 * If our size started in the middle of a block we need to zero out the
5189 * rest of the block before we expand the i_size, otherwise we could
5190 * expose stale data.
5192 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5196 if (size <= hole_start)
5199 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5201 cur_offset = hole_start;
5203 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5204 block_end - cur_offset);
5210 last_byte = min(extent_map_end(em), block_end);
5211 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5212 hole_size = last_byte - cur_offset;
5214 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5215 struct extent_map *hole_em;
5217 err = maybe_insert_hole(root, inode, cur_offset,
5222 err = btrfs_inode_set_file_extent_range(inode,
5223 cur_offset, hole_size);
5227 btrfs_drop_extent_cache(inode, cur_offset,
5228 cur_offset + hole_size - 1, 0);
5229 hole_em = alloc_extent_map();
5231 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5232 &inode->runtime_flags);
5235 hole_em->start = cur_offset;
5236 hole_em->len = hole_size;
5237 hole_em->orig_start = cur_offset;
5239 hole_em->block_start = EXTENT_MAP_HOLE;
5240 hole_em->block_len = 0;
5241 hole_em->orig_block_len = 0;
5242 hole_em->ram_bytes = hole_size;
5243 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5244 hole_em->generation = fs_info->generation;
5247 write_lock(&em_tree->lock);
5248 err = add_extent_mapping(em_tree, hole_em, 1);
5249 write_unlock(&em_tree->lock);
5252 btrfs_drop_extent_cache(inode, cur_offset,
5256 free_extent_map(hole_em);
5258 err = btrfs_inode_set_file_extent_range(inode,
5259 cur_offset, hole_size);
5264 free_extent_map(em);
5266 cur_offset = last_byte;
5267 if (cur_offset >= block_end)
5270 free_extent_map(em);
5271 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5275 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5277 struct btrfs_root *root = BTRFS_I(inode)->root;
5278 struct btrfs_trans_handle *trans;
5279 loff_t oldsize = i_size_read(inode);
5280 loff_t newsize = attr->ia_size;
5281 int mask = attr->ia_valid;
5285 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5286 * special case where we need to update the times despite not having
5287 * these flags set. For all other operations the VFS set these flags
5288 * explicitly if it wants a timestamp update.
5290 if (newsize != oldsize) {
5291 inode_inc_iversion(inode);
5292 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5293 inode->i_ctime = inode->i_mtime =
5294 current_time(inode);
5297 if (newsize > oldsize) {
5299 * Don't do an expanding truncate while snapshotting is ongoing.
5300 * This is to ensure the snapshot captures a fully consistent
5301 * state of this file - if the snapshot captures this expanding
5302 * truncation, it must capture all writes that happened before
5305 btrfs_drew_write_lock(&root->snapshot_lock);
5306 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5308 btrfs_drew_write_unlock(&root->snapshot_lock);
5312 trans = btrfs_start_transaction(root, 1);
5313 if (IS_ERR(trans)) {
5314 btrfs_drew_write_unlock(&root->snapshot_lock);
5315 return PTR_ERR(trans);
5318 i_size_write(inode, newsize);
5319 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5320 pagecache_isize_extended(inode, oldsize, newsize);
5321 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5322 btrfs_drew_write_unlock(&root->snapshot_lock);
5323 btrfs_end_transaction(trans);
5325 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5327 if (btrfs_is_zoned(fs_info)) {
5328 ret = btrfs_wait_ordered_range(inode,
5329 ALIGN(newsize, fs_info->sectorsize),
5336 * We're truncating a file that used to have good data down to
5337 * zero. Make sure any new writes to the file get on disk
5341 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5342 &BTRFS_I(inode)->runtime_flags);
5344 truncate_setsize(inode, newsize);
5346 inode_dio_wait(inode);
5348 ret = btrfs_truncate(inode, newsize == oldsize);
5349 if (ret && inode->i_nlink) {
5353 * Truncate failed, so fix up the in-memory size. We
5354 * adjusted disk_i_size down as we removed extents, so
5355 * wait for disk_i_size to be stable and then update the
5356 * in-memory size to match.
5358 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5361 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5368 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5371 struct inode *inode = d_inode(dentry);
5372 struct btrfs_root *root = BTRFS_I(inode)->root;
5375 if (btrfs_root_readonly(root))
5378 err = setattr_prepare(&init_user_ns, dentry, attr);
5382 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5383 err = btrfs_setsize(inode, attr);
5388 if (attr->ia_valid) {
5389 setattr_copy(&init_user_ns, inode, attr);
5390 inode_inc_iversion(inode);
5391 err = btrfs_dirty_inode(inode);
5393 if (!err && attr->ia_valid & ATTR_MODE)
5394 err = posix_acl_chmod(&init_user_ns, inode,
5402 * While truncating the inode pages during eviction, we get the VFS calling
5403 * btrfs_invalidatepage() against each page of the inode. This is slow because
5404 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5405 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5406 * extent_state structures over and over, wasting lots of time.
5408 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5409 * those expensive operations on a per page basis and do only the ordered io
5410 * finishing, while we release here the extent_map and extent_state structures,
5411 * without the excessive merging and splitting.
5413 static void evict_inode_truncate_pages(struct inode *inode)
5415 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5416 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5417 struct rb_node *node;
5419 ASSERT(inode->i_state & I_FREEING);
5420 truncate_inode_pages_final(&inode->i_data);
5422 write_lock(&map_tree->lock);
5423 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5424 struct extent_map *em;
5426 node = rb_first_cached(&map_tree->map);
5427 em = rb_entry(node, struct extent_map, rb_node);
5428 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5429 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5430 remove_extent_mapping(map_tree, em);
5431 free_extent_map(em);
5432 if (need_resched()) {
5433 write_unlock(&map_tree->lock);
5435 write_lock(&map_tree->lock);
5438 write_unlock(&map_tree->lock);
5441 * Keep looping until we have no more ranges in the io tree.
5442 * We can have ongoing bios started by readahead that have
5443 * their endio callback (extent_io.c:end_bio_extent_readpage)
5444 * still in progress (unlocked the pages in the bio but did not yet
5445 * unlocked the ranges in the io tree). Therefore this means some
5446 * ranges can still be locked and eviction started because before
5447 * submitting those bios, which are executed by a separate task (work
5448 * queue kthread), inode references (inode->i_count) were not taken
5449 * (which would be dropped in the end io callback of each bio).
5450 * Therefore here we effectively end up waiting for those bios and
5451 * anyone else holding locked ranges without having bumped the inode's
5452 * reference count - if we don't do it, when they access the inode's
5453 * io_tree to unlock a range it may be too late, leading to an
5454 * use-after-free issue.
5456 spin_lock(&io_tree->lock);
5457 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5458 struct extent_state *state;
5459 struct extent_state *cached_state = NULL;
5462 unsigned state_flags;
5464 node = rb_first(&io_tree->state);
5465 state = rb_entry(node, struct extent_state, rb_node);
5466 start = state->start;
5468 state_flags = state->state;
5469 spin_unlock(&io_tree->lock);
5471 lock_extent_bits(io_tree, start, end, &cached_state);
5474 * If still has DELALLOC flag, the extent didn't reach disk,
5475 * and its reserved space won't be freed by delayed_ref.
5476 * So we need to free its reserved space here.
5477 * (Refer to comment in btrfs_invalidatepage, case 2)
5479 * Note, end is the bytenr of last byte, so we need + 1 here.
5481 if (state_flags & EXTENT_DELALLOC)
5482 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5485 clear_extent_bit(io_tree, start, end,
5486 EXTENT_LOCKED | EXTENT_DELALLOC |
5487 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5491 spin_lock(&io_tree->lock);
5493 spin_unlock(&io_tree->lock);
5496 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5497 struct btrfs_block_rsv *rsv)
5499 struct btrfs_fs_info *fs_info = root->fs_info;
5500 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5501 struct btrfs_trans_handle *trans;
5502 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5506 * Eviction should be taking place at some place safe because of our
5507 * delayed iputs. However the normal flushing code will run delayed
5508 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5510 * We reserve the delayed_refs_extra here again because we can't use
5511 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5512 * above. We reserve our extra bit here because we generate a ton of
5513 * delayed refs activity by truncating.
5515 * If we cannot make our reservation we'll attempt to steal from the
5516 * global reserve, because we really want to be able to free up space.
5518 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5519 BTRFS_RESERVE_FLUSH_EVICT);
5522 * Try to steal from the global reserve if there is space for
5525 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5526 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5528 "could not allocate space for delete; will truncate on mount");
5529 return ERR_PTR(-ENOSPC);
5531 delayed_refs_extra = 0;
5534 trans = btrfs_join_transaction(root);
5538 if (delayed_refs_extra) {
5539 trans->block_rsv = &fs_info->trans_block_rsv;
5540 trans->bytes_reserved = delayed_refs_extra;
5541 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5542 delayed_refs_extra, 1);
5547 void btrfs_evict_inode(struct inode *inode)
5549 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5550 struct btrfs_trans_handle *trans;
5551 struct btrfs_root *root = BTRFS_I(inode)->root;
5552 struct btrfs_block_rsv *rsv;
5555 trace_btrfs_inode_evict(inode);
5562 evict_inode_truncate_pages(inode);
5564 if (inode->i_nlink &&
5565 ((btrfs_root_refs(&root->root_item) != 0 &&
5566 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5567 btrfs_is_free_space_inode(BTRFS_I(inode))))
5570 if (is_bad_inode(inode))
5573 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5575 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5578 if (inode->i_nlink > 0) {
5579 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5580 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5584 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5588 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5591 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5594 btrfs_i_size_write(BTRFS_I(inode), 0);
5597 trans = evict_refill_and_join(root, rsv);
5601 trans->block_rsv = rsv;
5603 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
5605 trans->block_rsv = &fs_info->trans_block_rsv;
5606 btrfs_end_transaction(trans);
5607 btrfs_btree_balance_dirty(fs_info);
5608 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5615 * Errors here aren't a big deal, it just means we leave orphan items in
5616 * the tree. They will be cleaned up on the next mount. If the inode
5617 * number gets reused, cleanup deletes the orphan item without doing
5618 * anything, and unlink reuses the existing orphan item.
5620 * If it turns out that we are dropping too many of these, we might want
5621 * to add a mechanism for retrying these after a commit.
5623 trans = evict_refill_and_join(root, rsv);
5624 if (!IS_ERR(trans)) {
5625 trans->block_rsv = rsv;
5626 btrfs_orphan_del(trans, BTRFS_I(inode));
5627 trans->block_rsv = &fs_info->trans_block_rsv;
5628 btrfs_end_transaction(trans);
5632 btrfs_free_block_rsv(fs_info, rsv);
5635 * If we didn't successfully delete, the orphan item will still be in
5636 * the tree and we'll retry on the next mount. Again, we might also want
5637 * to retry these periodically in the future.
5639 btrfs_remove_delayed_node(BTRFS_I(inode));
5644 * Return the key found in the dir entry in the location pointer, fill @type
5645 * with BTRFS_FT_*, and return 0.
5647 * If no dir entries were found, returns -ENOENT.
5648 * If found a corrupted location in dir entry, returns -EUCLEAN.
5650 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5651 struct btrfs_key *location, u8 *type)
5653 const char *name = dentry->d_name.name;
5654 int namelen = dentry->d_name.len;
5655 struct btrfs_dir_item *di;
5656 struct btrfs_path *path;
5657 struct btrfs_root *root = BTRFS_I(dir)->root;
5660 path = btrfs_alloc_path();
5664 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5666 if (IS_ERR_OR_NULL(di)) {
5667 ret = di ? PTR_ERR(di) : -ENOENT;
5671 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5672 if (location->type != BTRFS_INODE_ITEM_KEY &&
5673 location->type != BTRFS_ROOT_ITEM_KEY) {
5675 btrfs_warn(root->fs_info,
5676 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5677 __func__, name, btrfs_ino(BTRFS_I(dir)),
5678 location->objectid, location->type, location->offset);
5681 *type = btrfs_dir_type(path->nodes[0], di);
5683 btrfs_free_path(path);
5688 * when we hit a tree root in a directory, the btrfs part of the inode
5689 * needs to be changed to reflect the root directory of the tree root. This
5690 * is kind of like crossing a mount point.
5692 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5694 struct dentry *dentry,
5695 struct btrfs_key *location,
5696 struct btrfs_root **sub_root)
5698 struct btrfs_path *path;
5699 struct btrfs_root *new_root;
5700 struct btrfs_root_ref *ref;
5701 struct extent_buffer *leaf;
5702 struct btrfs_key key;
5706 path = btrfs_alloc_path();
5713 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5714 key.type = BTRFS_ROOT_REF_KEY;
5715 key.offset = location->objectid;
5717 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5724 leaf = path->nodes[0];
5725 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5726 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5727 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5730 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5731 (unsigned long)(ref + 1),
5732 dentry->d_name.len);
5736 btrfs_release_path(path);
5738 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5739 if (IS_ERR(new_root)) {
5740 err = PTR_ERR(new_root);
5744 *sub_root = new_root;
5745 location->objectid = btrfs_root_dirid(&new_root->root_item);
5746 location->type = BTRFS_INODE_ITEM_KEY;
5747 location->offset = 0;
5750 btrfs_free_path(path);
5754 static void inode_tree_add(struct inode *inode)
5756 struct btrfs_root *root = BTRFS_I(inode)->root;
5757 struct btrfs_inode *entry;
5759 struct rb_node *parent;
5760 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5761 u64 ino = btrfs_ino(BTRFS_I(inode));
5763 if (inode_unhashed(inode))
5766 spin_lock(&root->inode_lock);
5767 p = &root->inode_tree.rb_node;
5770 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5772 if (ino < btrfs_ino(entry))
5773 p = &parent->rb_left;
5774 else if (ino > btrfs_ino(entry))
5775 p = &parent->rb_right;
5777 WARN_ON(!(entry->vfs_inode.i_state &
5778 (I_WILL_FREE | I_FREEING)));
5779 rb_replace_node(parent, new, &root->inode_tree);
5780 RB_CLEAR_NODE(parent);
5781 spin_unlock(&root->inode_lock);
5785 rb_link_node(new, parent, p);
5786 rb_insert_color(new, &root->inode_tree);
5787 spin_unlock(&root->inode_lock);
5790 static void inode_tree_del(struct btrfs_inode *inode)
5792 struct btrfs_root *root = inode->root;
5795 spin_lock(&root->inode_lock);
5796 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5797 rb_erase(&inode->rb_node, &root->inode_tree);
5798 RB_CLEAR_NODE(&inode->rb_node);
5799 empty = RB_EMPTY_ROOT(&root->inode_tree);
5801 spin_unlock(&root->inode_lock);
5803 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5804 spin_lock(&root->inode_lock);
5805 empty = RB_EMPTY_ROOT(&root->inode_tree);
5806 spin_unlock(&root->inode_lock);
5808 btrfs_add_dead_root(root);
5813 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5815 struct btrfs_iget_args *args = p;
5817 inode->i_ino = args->ino;
5818 BTRFS_I(inode)->location.objectid = args->ino;
5819 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5820 BTRFS_I(inode)->location.offset = 0;
5821 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5822 BUG_ON(args->root && !BTRFS_I(inode)->root);
5826 static int btrfs_find_actor(struct inode *inode, void *opaque)
5828 struct btrfs_iget_args *args = opaque;
5830 return args->ino == BTRFS_I(inode)->location.objectid &&
5831 args->root == BTRFS_I(inode)->root;
5834 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5835 struct btrfs_root *root)
5837 struct inode *inode;
5838 struct btrfs_iget_args args;
5839 unsigned long hashval = btrfs_inode_hash(ino, root);
5844 inode = iget5_locked(s, hashval, btrfs_find_actor,
5845 btrfs_init_locked_inode,
5851 * Get an inode object given its inode number and corresponding root.
5852 * Path can be preallocated to prevent recursing back to iget through
5853 * allocator. NULL is also valid but may require an additional allocation
5856 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5857 struct btrfs_root *root, struct btrfs_path *path)
5859 struct inode *inode;
5861 inode = btrfs_iget_locked(s, ino, root);
5863 return ERR_PTR(-ENOMEM);
5865 if (inode->i_state & I_NEW) {
5868 ret = btrfs_read_locked_inode(inode, path);
5870 inode_tree_add(inode);
5871 unlock_new_inode(inode);
5875 * ret > 0 can come from btrfs_search_slot called by
5876 * btrfs_read_locked_inode, this means the inode item
5881 inode = ERR_PTR(ret);
5888 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5890 return btrfs_iget_path(s, ino, root, NULL);
5893 static struct inode *new_simple_dir(struct super_block *s,
5894 struct btrfs_key *key,
5895 struct btrfs_root *root)
5897 struct inode *inode = new_inode(s);
5900 return ERR_PTR(-ENOMEM);
5902 BTRFS_I(inode)->root = btrfs_grab_root(root);
5903 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5904 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5906 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5908 * We only need lookup, the rest is read-only and there's no inode
5909 * associated with the dentry
5911 inode->i_op = &simple_dir_inode_operations;
5912 inode->i_opflags &= ~IOP_XATTR;
5913 inode->i_fop = &simple_dir_operations;
5914 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5915 inode->i_mtime = current_time(inode);
5916 inode->i_atime = inode->i_mtime;
5917 inode->i_ctime = inode->i_mtime;
5918 BTRFS_I(inode)->i_otime = inode->i_mtime;
5923 static inline u8 btrfs_inode_type(struct inode *inode)
5926 * Compile-time asserts that generic FT_* types still match
5929 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5930 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5931 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5932 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5933 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5934 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5935 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5936 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5938 return fs_umode_to_ftype(inode->i_mode);
5941 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5943 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5944 struct inode *inode;
5945 struct btrfs_root *root = BTRFS_I(dir)->root;
5946 struct btrfs_root *sub_root = root;
5947 struct btrfs_key location;
5951 if (dentry->d_name.len > BTRFS_NAME_LEN)
5952 return ERR_PTR(-ENAMETOOLONG);
5954 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5956 return ERR_PTR(ret);
5958 if (location.type == BTRFS_INODE_ITEM_KEY) {
5959 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5963 /* Do extra check against inode mode with di_type */
5964 if (btrfs_inode_type(inode) != di_type) {
5966 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5967 inode->i_mode, btrfs_inode_type(inode),
5970 return ERR_PTR(-EUCLEAN);
5975 ret = fixup_tree_root_location(fs_info, dir, dentry,
5976 &location, &sub_root);
5979 inode = ERR_PTR(ret);
5981 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5983 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5985 if (root != sub_root)
5986 btrfs_put_root(sub_root);
5988 if (!IS_ERR(inode) && root != sub_root) {
5989 down_read(&fs_info->cleanup_work_sem);
5990 if (!sb_rdonly(inode->i_sb))
5991 ret = btrfs_orphan_cleanup(sub_root);
5992 up_read(&fs_info->cleanup_work_sem);
5995 inode = ERR_PTR(ret);
6002 static int btrfs_dentry_delete(const struct dentry *dentry)
6004 struct btrfs_root *root;
6005 struct inode *inode = d_inode(dentry);
6007 if (!inode && !IS_ROOT(dentry))
6008 inode = d_inode(dentry->d_parent);
6011 root = BTRFS_I(inode)->root;
6012 if (btrfs_root_refs(&root->root_item) == 0)
6015 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6021 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
6024 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
6026 if (inode == ERR_PTR(-ENOENT))
6028 return d_splice_alias(inode, dentry);
6032 * All this infrastructure exists because dir_emit can fault, and we are holding
6033 * the tree lock when doing readdir. For now just allocate a buffer and copy
6034 * our information into that, and then dir_emit from the buffer. This is
6035 * similar to what NFS does, only we don't keep the buffer around in pagecache
6036 * because I'm afraid I'll mess that up. Long term we need to make filldir do
6037 * copy_to_user_inatomic so we don't have to worry about page faulting under the
6040 static int btrfs_opendir(struct inode *inode, struct file *file)
6042 struct btrfs_file_private *private;
6044 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
6047 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6048 if (!private->filldir_buf) {
6052 file->private_data = private;
6063 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6066 struct dir_entry *entry = addr;
6067 char *name = (char *)(entry + 1);
6069 ctx->pos = get_unaligned(&entry->offset);
6070 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6071 get_unaligned(&entry->ino),
6072 get_unaligned(&entry->type)))
6074 addr += sizeof(struct dir_entry) +
6075 get_unaligned(&entry->name_len);
6081 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6083 struct inode *inode = file_inode(file);
6084 struct btrfs_root *root = BTRFS_I(inode)->root;
6085 struct btrfs_file_private *private = file->private_data;
6086 struct btrfs_dir_item *di;
6087 struct btrfs_key key;
6088 struct btrfs_key found_key;
6089 struct btrfs_path *path;
6091 struct list_head ins_list;
6092 struct list_head del_list;
6094 struct extent_buffer *leaf;
6101 struct btrfs_key location;
6103 if (!dir_emit_dots(file, ctx))
6106 path = btrfs_alloc_path();
6110 addr = private->filldir_buf;
6111 path->reada = READA_FORWARD;
6113 INIT_LIST_HEAD(&ins_list);
6114 INIT_LIST_HEAD(&del_list);
6115 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6118 key.type = BTRFS_DIR_INDEX_KEY;
6119 key.offset = ctx->pos;
6120 key.objectid = btrfs_ino(BTRFS_I(inode));
6122 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6127 struct dir_entry *entry;
6129 leaf = path->nodes[0];
6130 slot = path->slots[0];
6131 if (slot >= btrfs_header_nritems(leaf)) {
6132 ret = btrfs_next_leaf(root, path);
6140 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6142 if (found_key.objectid != key.objectid)
6144 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6146 if (found_key.offset < ctx->pos)
6148 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6150 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6151 name_len = btrfs_dir_name_len(leaf, di);
6152 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6154 btrfs_release_path(path);
6155 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6158 addr = private->filldir_buf;
6165 put_unaligned(name_len, &entry->name_len);
6166 name_ptr = (char *)(entry + 1);
6167 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6169 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6171 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6172 put_unaligned(location.objectid, &entry->ino);
6173 put_unaligned(found_key.offset, &entry->offset);
6175 addr += sizeof(struct dir_entry) + name_len;
6176 total_len += sizeof(struct dir_entry) + name_len;
6180 btrfs_release_path(path);
6182 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6186 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6191 * Stop new entries from being returned after we return the last
6194 * New directory entries are assigned a strictly increasing
6195 * offset. This means that new entries created during readdir
6196 * are *guaranteed* to be seen in the future by that readdir.
6197 * This has broken buggy programs which operate on names as
6198 * they're returned by readdir. Until we re-use freed offsets
6199 * we have this hack to stop new entries from being returned
6200 * under the assumption that they'll never reach this huge
6203 * This is being careful not to overflow 32bit loff_t unless the
6204 * last entry requires it because doing so has broken 32bit apps
6207 if (ctx->pos >= INT_MAX)
6208 ctx->pos = LLONG_MAX;
6215 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6216 btrfs_free_path(path);
6221 * This is somewhat expensive, updating the tree every time the
6222 * inode changes. But, it is most likely to find the inode in cache.
6223 * FIXME, needs more benchmarking...there are no reasons other than performance
6224 * to keep or drop this code.
6226 static int btrfs_dirty_inode(struct inode *inode)
6228 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6229 struct btrfs_root *root = BTRFS_I(inode)->root;
6230 struct btrfs_trans_handle *trans;
6233 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6236 trans = btrfs_join_transaction(root);
6238 return PTR_ERR(trans);
6240 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6241 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6242 /* whoops, lets try again with the full transaction */
6243 btrfs_end_transaction(trans);
6244 trans = btrfs_start_transaction(root, 1);
6246 return PTR_ERR(trans);
6248 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6250 btrfs_end_transaction(trans);
6251 if (BTRFS_I(inode)->delayed_node)
6252 btrfs_balance_delayed_items(fs_info);
6258 * This is a copy of file_update_time. We need this so we can return error on
6259 * ENOSPC for updating the inode in the case of file write and mmap writes.
6261 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6264 struct btrfs_root *root = BTRFS_I(inode)->root;
6265 bool dirty = flags & ~S_VERSION;
6267 if (btrfs_root_readonly(root))
6270 if (flags & S_VERSION)
6271 dirty |= inode_maybe_inc_iversion(inode, dirty);
6272 if (flags & S_CTIME)
6273 inode->i_ctime = *now;
6274 if (flags & S_MTIME)
6275 inode->i_mtime = *now;
6276 if (flags & S_ATIME)
6277 inode->i_atime = *now;
6278 return dirty ? btrfs_dirty_inode(inode) : 0;
6282 * find the highest existing sequence number in a directory
6283 * and then set the in-memory index_cnt variable to reflect
6284 * free sequence numbers
6286 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6288 struct btrfs_root *root = inode->root;
6289 struct btrfs_key key, found_key;
6290 struct btrfs_path *path;
6291 struct extent_buffer *leaf;
6294 key.objectid = btrfs_ino(inode);
6295 key.type = BTRFS_DIR_INDEX_KEY;
6296 key.offset = (u64)-1;
6298 path = btrfs_alloc_path();
6302 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6305 /* FIXME: we should be able to handle this */
6311 * MAGIC NUMBER EXPLANATION:
6312 * since we search a directory based on f_pos we have to start at 2
6313 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6314 * else has to start at 2
6316 if (path->slots[0] == 0) {
6317 inode->index_cnt = 2;
6323 leaf = path->nodes[0];
6324 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6326 if (found_key.objectid != btrfs_ino(inode) ||
6327 found_key.type != BTRFS_DIR_INDEX_KEY) {
6328 inode->index_cnt = 2;
6332 inode->index_cnt = found_key.offset + 1;
6334 btrfs_free_path(path);
6339 * helper to find a free sequence number in a given directory. This current
6340 * code is very simple, later versions will do smarter things in the btree
6342 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6346 if (dir->index_cnt == (u64)-1) {
6347 ret = btrfs_inode_delayed_dir_index_count(dir);
6349 ret = btrfs_set_inode_index_count(dir);
6355 *index = dir->index_cnt;
6361 static int btrfs_insert_inode_locked(struct inode *inode)
6363 struct btrfs_iget_args args;
6365 args.ino = BTRFS_I(inode)->location.objectid;
6366 args.root = BTRFS_I(inode)->root;
6368 return insert_inode_locked4(inode,
6369 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6370 btrfs_find_actor, &args);
6374 * Inherit flags from the parent inode.
6376 * Currently only the compression flags and the cow flags are inherited.
6378 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6385 flags = BTRFS_I(dir)->flags;
6387 if (flags & BTRFS_INODE_NOCOMPRESS) {
6388 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6389 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6390 } else if (flags & BTRFS_INODE_COMPRESS) {
6391 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6392 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6395 if (flags & BTRFS_INODE_NODATACOW) {
6396 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6397 if (S_ISREG(inode->i_mode))
6398 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6401 btrfs_sync_inode_flags_to_i_flags(inode);
6404 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6405 struct btrfs_root *root,
6407 const char *name, int name_len,
6408 u64 ref_objectid, u64 objectid,
6409 umode_t mode, u64 *index)
6411 struct btrfs_fs_info *fs_info = root->fs_info;
6412 struct inode *inode;
6413 struct btrfs_inode_item *inode_item;
6414 struct btrfs_key *location;
6415 struct btrfs_path *path;
6416 struct btrfs_inode_ref *ref;
6417 struct btrfs_key key[2];
6419 int nitems = name ? 2 : 1;
6421 unsigned int nofs_flag;
6424 path = btrfs_alloc_path();
6426 return ERR_PTR(-ENOMEM);
6428 nofs_flag = memalloc_nofs_save();
6429 inode = new_inode(fs_info->sb);
6430 memalloc_nofs_restore(nofs_flag);
6432 btrfs_free_path(path);
6433 return ERR_PTR(-ENOMEM);
6437 * O_TMPFILE, set link count to 0, so that after this point,
6438 * we fill in an inode item with the correct link count.
6441 set_nlink(inode, 0);
6444 * we have to initialize this early, so we can reclaim the inode
6445 * number if we fail afterwards in this function.
6447 inode->i_ino = objectid;
6450 trace_btrfs_inode_request(dir);
6452 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6454 btrfs_free_path(path);
6456 return ERR_PTR(ret);
6462 * index_cnt is ignored for everything but a dir,
6463 * btrfs_set_inode_index_count has an explanation for the magic
6466 BTRFS_I(inode)->index_cnt = 2;
6467 BTRFS_I(inode)->dir_index = *index;
6468 BTRFS_I(inode)->root = btrfs_grab_root(root);
6469 BTRFS_I(inode)->generation = trans->transid;
6470 inode->i_generation = BTRFS_I(inode)->generation;
6473 * We could have gotten an inode number from somebody who was fsynced
6474 * and then removed in this same transaction, so let's just set full
6475 * sync since it will be a full sync anyway and this will blow away the
6476 * old info in the log.
6478 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6480 key[0].objectid = objectid;
6481 key[0].type = BTRFS_INODE_ITEM_KEY;
6484 sizes[0] = sizeof(struct btrfs_inode_item);
6488 * Start new inodes with an inode_ref. This is slightly more
6489 * efficient for small numbers of hard links since they will
6490 * be packed into one item. Extended refs will kick in if we
6491 * add more hard links than can fit in the ref item.
6493 key[1].objectid = objectid;
6494 key[1].type = BTRFS_INODE_REF_KEY;
6495 key[1].offset = ref_objectid;
6497 sizes[1] = name_len + sizeof(*ref);
6500 location = &BTRFS_I(inode)->location;
6501 location->objectid = objectid;
6502 location->offset = 0;
6503 location->type = BTRFS_INODE_ITEM_KEY;
6505 ret = btrfs_insert_inode_locked(inode);
6511 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6515 inode_init_owner(&init_user_ns, inode, dir, mode);
6516 inode_set_bytes(inode, 0);
6518 inode->i_mtime = current_time(inode);
6519 inode->i_atime = inode->i_mtime;
6520 inode->i_ctime = inode->i_mtime;
6521 BTRFS_I(inode)->i_otime = inode->i_mtime;
6523 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6524 struct btrfs_inode_item);
6525 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6526 sizeof(*inode_item));
6527 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6530 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6531 struct btrfs_inode_ref);
6532 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6533 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6534 ptr = (unsigned long)(ref + 1);
6535 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6538 btrfs_mark_buffer_dirty(path->nodes[0]);
6539 btrfs_free_path(path);
6541 btrfs_inherit_iflags(inode, dir);
6543 if (S_ISREG(mode)) {
6544 if (btrfs_test_opt(fs_info, NODATASUM))
6545 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6546 if (btrfs_test_opt(fs_info, NODATACOW))
6547 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6548 BTRFS_INODE_NODATASUM;
6551 inode_tree_add(inode);
6553 trace_btrfs_inode_new(inode);
6554 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6556 btrfs_update_root_times(trans, root);
6558 ret = btrfs_inode_inherit_props(trans, inode, dir);
6561 "error inheriting props for ino %llu (root %llu): %d",
6562 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6567 discard_new_inode(inode);
6570 BTRFS_I(dir)->index_cnt--;
6571 btrfs_free_path(path);
6572 return ERR_PTR(ret);
6576 * utility function to add 'inode' into 'parent_inode' with
6577 * a give name and a given sequence number.
6578 * if 'add_backref' is true, also insert a backref from the
6579 * inode to the parent directory.
6581 int btrfs_add_link(struct btrfs_trans_handle *trans,
6582 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6583 const char *name, int name_len, int add_backref, u64 index)
6586 struct btrfs_key key;
6587 struct btrfs_root *root = parent_inode->root;
6588 u64 ino = btrfs_ino(inode);
6589 u64 parent_ino = btrfs_ino(parent_inode);
6591 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6592 memcpy(&key, &inode->root->root_key, sizeof(key));
6595 key.type = BTRFS_INODE_ITEM_KEY;
6599 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6600 ret = btrfs_add_root_ref(trans, key.objectid,
6601 root->root_key.objectid, parent_ino,
6602 index, name, name_len);
6603 } else if (add_backref) {
6604 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6608 /* Nothing to clean up yet */
6612 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6613 btrfs_inode_type(&inode->vfs_inode), index);
6614 if (ret == -EEXIST || ret == -EOVERFLOW)
6617 btrfs_abort_transaction(trans, ret);
6621 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6623 inode_inc_iversion(&parent_inode->vfs_inode);
6625 * If we are replaying a log tree, we do not want to update the mtime
6626 * and ctime of the parent directory with the current time, since the
6627 * log replay procedure is responsible for setting them to their correct
6628 * values (the ones it had when the fsync was done).
6630 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6631 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6633 parent_inode->vfs_inode.i_mtime = now;
6634 parent_inode->vfs_inode.i_ctime = now;
6636 ret = btrfs_update_inode(trans, root, parent_inode);
6638 btrfs_abort_transaction(trans, ret);
6642 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6645 err = btrfs_del_root_ref(trans, key.objectid,
6646 root->root_key.objectid, parent_ino,
6647 &local_index, name, name_len);
6649 btrfs_abort_transaction(trans, err);
6650 } else if (add_backref) {
6654 err = btrfs_del_inode_ref(trans, root, name, name_len,
6655 ino, parent_ino, &local_index);
6657 btrfs_abort_transaction(trans, err);
6660 /* Return the original error code */
6664 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6665 struct btrfs_inode *dir, struct dentry *dentry,
6666 struct btrfs_inode *inode, int backref, u64 index)
6668 int err = btrfs_add_link(trans, dir, inode,
6669 dentry->d_name.name, dentry->d_name.len,
6676 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6677 struct dentry *dentry, umode_t mode, dev_t rdev)
6679 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6680 struct btrfs_trans_handle *trans;
6681 struct btrfs_root *root = BTRFS_I(dir)->root;
6682 struct inode *inode = NULL;
6688 * 2 for inode item and ref
6690 * 1 for xattr if selinux is on
6692 trans = btrfs_start_transaction(root, 5);
6694 return PTR_ERR(trans);
6696 err = btrfs_get_free_objectid(root, &objectid);
6700 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6701 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6703 if (IS_ERR(inode)) {
6704 err = PTR_ERR(inode);
6710 * If the active LSM wants to access the inode during
6711 * d_instantiate it needs these. Smack checks to see
6712 * if the filesystem supports xattrs by looking at the
6715 inode->i_op = &btrfs_special_inode_operations;
6716 init_special_inode(inode, inode->i_mode, rdev);
6718 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6722 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6727 btrfs_update_inode(trans, root, BTRFS_I(inode));
6728 d_instantiate_new(dentry, inode);
6731 btrfs_end_transaction(trans);
6732 btrfs_btree_balance_dirty(fs_info);
6734 inode_dec_link_count(inode);
6735 discard_new_inode(inode);
6740 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6741 struct dentry *dentry, umode_t mode, bool excl)
6743 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6744 struct btrfs_trans_handle *trans;
6745 struct btrfs_root *root = BTRFS_I(dir)->root;
6746 struct inode *inode = NULL;
6752 * 2 for inode item and ref
6754 * 1 for xattr if selinux is on
6756 trans = btrfs_start_transaction(root, 5);
6758 return PTR_ERR(trans);
6760 err = btrfs_get_free_objectid(root, &objectid);
6764 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6765 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6767 if (IS_ERR(inode)) {
6768 err = PTR_ERR(inode);
6773 * If the active LSM wants to access the inode during
6774 * d_instantiate it needs these. Smack checks to see
6775 * if the filesystem supports xattrs by looking at the
6778 inode->i_fop = &btrfs_file_operations;
6779 inode->i_op = &btrfs_file_inode_operations;
6780 inode->i_mapping->a_ops = &btrfs_aops;
6782 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6786 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6790 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6795 d_instantiate_new(dentry, inode);
6798 btrfs_end_transaction(trans);
6800 inode_dec_link_count(inode);
6801 discard_new_inode(inode);
6803 btrfs_btree_balance_dirty(fs_info);
6807 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6808 struct dentry *dentry)
6810 struct btrfs_trans_handle *trans = NULL;
6811 struct btrfs_root *root = BTRFS_I(dir)->root;
6812 struct inode *inode = d_inode(old_dentry);
6813 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6818 /* do not allow sys_link's with other subvols of the same device */
6819 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6822 if (inode->i_nlink >= BTRFS_LINK_MAX)
6825 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6830 * 2 items for inode and inode ref
6831 * 2 items for dir items
6832 * 1 item for parent inode
6833 * 1 item for orphan item deletion if O_TMPFILE
6835 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6836 if (IS_ERR(trans)) {
6837 err = PTR_ERR(trans);
6842 /* There are several dir indexes for this inode, clear the cache. */
6843 BTRFS_I(inode)->dir_index = 0ULL;
6845 inode_inc_iversion(inode);
6846 inode->i_ctime = current_time(inode);
6848 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6850 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6856 struct dentry *parent = dentry->d_parent;
6858 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6861 if (inode->i_nlink == 1) {
6863 * If new hard link count is 1, it's a file created
6864 * with open(2) O_TMPFILE flag.
6866 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6870 d_instantiate(dentry, inode);
6871 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6876 btrfs_end_transaction(trans);
6878 inode_dec_link_count(inode);
6881 btrfs_btree_balance_dirty(fs_info);
6885 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6886 struct dentry *dentry, umode_t mode)
6888 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6889 struct inode *inode = NULL;
6890 struct btrfs_trans_handle *trans;
6891 struct btrfs_root *root = BTRFS_I(dir)->root;
6897 * 2 items for inode and ref
6898 * 2 items for dir items
6899 * 1 for xattr if selinux is on
6901 trans = btrfs_start_transaction(root, 5);
6903 return PTR_ERR(trans);
6905 err = btrfs_get_free_objectid(root, &objectid);
6909 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6910 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6911 S_IFDIR | mode, &index);
6912 if (IS_ERR(inode)) {
6913 err = PTR_ERR(inode);
6918 /* these must be set before we unlock the inode */
6919 inode->i_op = &btrfs_dir_inode_operations;
6920 inode->i_fop = &btrfs_dir_file_operations;
6922 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6926 btrfs_i_size_write(BTRFS_I(inode), 0);
6927 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6931 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6932 dentry->d_name.name,
6933 dentry->d_name.len, 0, index);
6937 d_instantiate_new(dentry, inode);
6940 btrfs_end_transaction(trans);
6942 inode_dec_link_count(inode);
6943 discard_new_inode(inode);
6945 btrfs_btree_balance_dirty(fs_info);
6949 static noinline int uncompress_inline(struct btrfs_path *path,
6951 size_t pg_offset, u64 extent_offset,
6952 struct btrfs_file_extent_item *item)
6955 struct extent_buffer *leaf = path->nodes[0];
6958 unsigned long inline_size;
6962 WARN_ON(pg_offset != 0);
6963 compress_type = btrfs_file_extent_compression(leaf, item);
6964 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6965 inline_size = btrfs_file_extent_inline_item_len(leaf,
6966 btrfs_item_nr(path->slots[0]));
6967 tmp = kmalloc(inline_size, GFP_NOFS);
6970 ptr = btrfs_file_extent_inline_start(item);
6972 read_extent_buffer(leaf, tmp, ptr, inline_size);
6974 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6975 ret = btrfs_decompress(compress_type, tmp, page,
6976 extent_offset, inline_size, max_size);
6979 * decompression code contains a memset to fill in any space between the end
6980 * of the uncompressed data and the end of max_size in case the decompressed
6981 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6982 * the end of an inline extent and the beginning of the next block, so we
6983 * cover that region here.
6986 if (max_size + pg_offset < PAGE_SIZE)
6987 memzero_page(page, pg_offset + max_size,
6988 PAGE_SIZE - max_size - pg_offset);
6994 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6995 * @inode: file to search in
6996 * @page: page to read extent data into if the extent is inline
6997 * @pg_offset: offset into @page to copy to
6998 * @start: file offset
6999 * @len: length of range starting at @start
7001 * This returns the first &struct extent_map which overlaps with the given
7002 * range, reading it from the B-tree and caching it if necessary. Note that
7003 * there may be more extents which overlap the given range after the returned
7006 * If @page is not NULL and the extent is inline, this also reads the extent
7007 * data directly into the page and marks the extent up to date in the io_tree.
7009 * Return: ERR_PTR on error, non-NULL extent_map on success.
7011 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
7012 struct page *page, size_t pg_offset,
7015 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7017 u64 extent_start = 0;
7019 u64 objectid = btrfs_ino(inode);
7020 int extent_type = -1;
7021 struct btrfs_path *path = NULL;
7022 struct btrfs_root *root = inode->root;
7023 struct btrfs_file_extent_item *item;
7024 struct extent_buffer *leaf;
7025 struct btrfs_key found_key;
7026 struct extent_map *em = NULL;
7027 struct extent_map_tree *em_tree = &inode->extent_tree;
7028 struct extent_io_tree *io_tree = &inode->io_tree;
7030 read_lock(&em_tree->lock);
7031 em = lookup_extent_mapping(em_tree, start, len);
7032 read_unlock(&em_tree->lock);
7035 if (em->start > start || em->start + em->len <= start)
7036 free_extent_map(em);
7037 else if (em->block_start == EXTENT_MAP_INLINE && page)
7038 free_extent_map(em);
7042 em = alloc_extent_map();
7047 em->start = EXTENT_MAP_HOLE;
7048 em->orig_start = EXTENT_MAP_HOLE;
7050 em->block_len = (u64)-1;
7052 path = btrfs_alloc_path();
7058 /* Chances are we'll be called again, so go ahead and do readahead */
7059 path->reada = READA_FORWARD;
7062 * The same explanation in load_free_space_cache applies here as well,
7063 * we only read when we're loading the free space cache, and at that
7064 * point the commit_root has everything we need.
7066 if (btrfs_is_free_space_inode(inode)) {
7067 path->search_commit_root = 1;
7068 path->skip_locking = 1;
7071 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7074 } else if (ret > 0) {
7075 if (path->slots[0] == 0)
7081 leaf = path->nodes[0];
7082 item = btrfs_item_ptr(leaf, path->slots[0],
7083 struct btrfs_file_extent_item);
7084 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7085 if (found_key.objectid != objectid ||
7086 found_key.type != BTRFS_EXTENT_DATA_KEY) {
7088 * If we backup past the first extent we want to move forward
7089 * and see if there is an extent in front of us, otherwise we'll
7090 * say there is a hole for our whole search range which can
7097 extent_type = btrfs_file_extent_type(leaf, item);
7098 extent_start = found_key.offset;
7099 extent_end = btrfs_file_extent_end(path);
7100 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7101 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7102 /* Only regular file could have regular/prealloc extent */
7103 if (!S_ISREG(inode->vfs_inode.i_mode)) {
7106 "regular/prealloc extent found for non-regular inode %llu",
7110 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7112 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7113 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7118 if (start >= extent_end) {
7120 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7121 ret = btrfs_next_leaf(root, path);
7127 leaf = path->nodes[0];
7129 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7130 if (found_key.objectid != objectid ||
7131 found_key.type != BTRFS_EXTENT_DATA_KEY)
7133 if (start + len <= found_key.offset)
7135 if (start > found_key.offset)
7138 /* New extent overlaps with existing one */
7140 em->orig_start = start;
7141 em->len = found_key.offset - start;
7142 em->block_start = EXTENT_MAP_HOLE;
7146 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
7148 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7149 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7151 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7155 size_t extent_offset;
7161 size = btrfs_file_extent_ram_bytes(leaf, item);
7162 extent_offset = page_offset(page) + pg_offset - extent_start;
7163 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7164 size - extent_offset);
7165 em->start = extent_start + extent_offset;
7166 em->len = ALIGN(copy_size, fs_info->sectorsize);
7167 em->orig_block_len = em->len;
7168 em->orig_start = em->start;
7169 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7171 if (!PageUptodate(page)) {
7172 if (btrfs_file_extent_compression(leaf, item) !=
7173 BTRFS_COMPRESS_NONE) {
7174 ret = uncompress_inline(path, page, pg_offset,
7175 extent_offset, item);
7179 map = kmap_local_page(page);
7180 read_extent_buffer(leaf, map + pg_offset, ptr,
7182 if (pg_offset + copy_size < PAGE_SIZE) {
7183 memset(map + pg_offset + copy_size, 0,
7184 PAGE_SIZE - pg_offset -
7189 flush_dcache_page(page);
7191 set_extent_uptodate(io_tree, em->start,
7192 extent_map_end(em) - 1, NULL, GFP_NOFS);
7197 em->orig_start = start;
7199 em->block_start = EXTENT_MAP_HOLE;
7202 btrfs_release_path(path);
7203 if (em->start > start || extent_map_end(em) <= start) {
7205 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7206 em->start, em->len, start, len);
7211 write_lock(&em_tree->lock);
7212 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7213 write_unlock(&em_tree->lock);
7215 btrfs_free_path(path);
7217 trace_btrfs_get_extent(root, inode, em);
7220 free_extent_map(em);
7221 return ERR_PTR(ret);
7226 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7229 struct extent_map *em;
7230 struct extent_map *hole_em = NULL;
7231 u64 delalloc_start = start;
7237 em = btrfs_get_extent(inode, NULL, 0, start, len);
7241 * If our em maps to:
7243 * - a pre-alloc extent,
7244 * there might actually be delalloc bytes behind it.
7246 if (em->block_start != EXTENT_MAP_HOLE &&
7247 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7252 /* check to see if we've wrapped (len == -1 or similar) */
7261 /* ok, we didn't find anything, lets look for delalloc */
7262 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7263 end, len, EXTENT_DELALLOC, 1);
7264 delalloc_end = delalloc_start + delalloc_len;
7265 if (delalloc_end < delalloc_start)
7266 delalloc_end = (u64)-1;
7269 * We didn't find anything useful, return the original results from
7272 if (delalloc_start > end || delalloc_end <= start) {
7279 * Adjust the delalloc_start to make sure it doesn't go backwards from
7280 * the start they passed in
7282 delalloc_start = max(start, delalloc_start);
7283 delalloc_len = delalloc_end - delalloc_start;
7285 if (delalloc_len > 0) {
7288 const u64 hole_end = extent_map_end(hole_em);
7290 em = alloc_extent_map();
7298 * When btrfs_get_extent can't find anything it returns one
7301 * Make sure what it found really fits our range, and adjust to
7302 * make sure it is based on the start from the caller
7304 if (hole_end <= start || hole_em->start > end) {
7305 free_extent_map(hole_em);
7308 hole_start = max(hole_em->start, start);
7309 hole_len = hole_end - hole_start;
7312 if (hole_em && delalloc_start > hole_start) {
7314 * Our hole starts before our delalloc, so we have to
7315 * return just the parts of the hole that go until the
7318 em->len = min(hole_len, delalloc_start - hole_start);
7319 em->start = hole_start;
7320 em->orig_start = hole_start;
7322 * Don't adjust block start at all, it is fixed at
7325 em->block_start = hole_em->block_start;
7326 em->block_len = hole_len;
7327 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7328 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7331 * Hole is out of passed range or it starts after
7334 em->start = delalloc_start;
7335 em->len = delalloc_len;
7336 em->orig_start = delalloc_start;
7337 em->block_start = EXTENT_MAP_DELALLOC;
7338 em->block_len = delalloc_len;
7345 free_extent_map(hole_em);
7347 free_extent_map(em);
7348 return ERR_PTR(err);
7353 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7356 const u64 orig_start,
7357 const u64 block_start,
7358 const u64 block_len,
7359 const u64 orig_block_len,
7360 const u64 ram_bytes,
7363 struct extent_map *em = NULL;
7366 if (type != BTRFS_ORDERED_NOCOW) {
7367 em = create_io_em(inode, start, len, orig_start, block_start,
7368 block_len, orig_block_len, ram_bytes,
7369 BTRFS_COMPRESS_NONE, /* compress_type */
7374 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7378 free_extent_map(em);
7379 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7388 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7391 struct btrfs_root *root = inode->root;
7392 struct btrfs_fs_info *fs_info = root->fs_info;
7393 struct extent_map *em;
7394 struct btrfs_key ins;
7398 alloc_hint = get_extent_allocation_hint(inode, start, len);
7399 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7400 0, alloc_hint, &ins, 1, 1);
7402 return ERR_PTR(ret);
7404 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7405 ins.objectid, ins.offset, ins.offset,
7406 ins.offset, BTRFS_ORDERED_REGULAR);
7407 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7409 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7415 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7417 struct btrfs_block_group *block_group;
7418 bool readonly = false;
7420 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7421 if (!block_group || block_group->ro)
7424 btrfs_put_block_group(block_group);
7429 * Check if we can do nocow write into the range [@offset, @offset + @len)
7431 * @offset: File offset
7432 * @len: The length to write, will be updated to the nocow writeable
7434 * @orig_start: (optional) Return the original file offset of the file extent
7435 * @orig_len: (optional) Return the original on-disk length of the file extent
7436 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7437 * @strict: if true, omit optimizations that might force us into unnecessary
7438 * cow. e.g., don't trust generation number.
7441 * >0 and update @len if we can do nocow write
7442 * 0 if we can't do nocow write
7443 * <0 if error happened
7445 * NOTE: This only checks the file extents, caller is responsible to wait for
7446 * any ordered extents.
7448 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7449 u64 *orig_start, u64 *orig_block_len,
7450 u64 *ram_bytes, bool strict)
7452 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7453 struct btrfs_path *path;
7455 struct extent_buffer *leaf;
7456 struct btrfs_root *root = BTRFS_I(inode)->root;
7457 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7458 struct btrfs_file_extent_item *fi;
7459 struct btrfs_key key;
7466 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7468 path = btrfs_alloc_path();
7472 ret = btrfs_lookup_file_extent(NULL, root, path,
7473 btrfs_ino(BTRFS_I(inode)), offset, 0);
7477 slot = path->slots[0];
7480 /* can't find the item, must cow */
7487 leaf = path->nodes[0];
7488 btrfs_item_key_to_cpu(leaf, &key, slot);
7489 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7490 key.type != BTRFS_EXTENT_DATA_KEY) {
7491 /* not our file or wrong item type, must cow */
7495 if (key.offset > offset) {
7496 /* Wrong offset, must cow */
7500 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7501 found_type = btrfs_file_extent_type(leaf, fi);
7502 if (found_type != BTRFS_FILE_EXTENT_REG &&
7503 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7504 /* not a regular extent, must cow */
7508 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7511 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7512 if (extent_end <= offset)
7515 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7516 if (disk_bytenr == 0)
7519 if (btrfs_file_extent_compression(leaf, fi) ||
7520 btrfs_file_extent_encryption(leaf, fi) ||
7521 btrfs_file_extent_other_encoding(leaf, fi))
7525 * Do the same check as in btrfs_cross_ref_exist but without the
7526 * unnecessary search.
7529 (btrfs_file_extent_generation(leaf, fi) <=
7530 btrfs_root_last_snapshot(&root->root_item)))
7533 backref_offset = btrfs_file_extent_offset(leaf, fi);
7536 *orig_start = key.offset - backref_offset;
7537 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7538 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7541 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7544 num_bytes = min(offset + *len, extent_end) - offset;
7545 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7548 range_end = round_up(offset + num_bytes,
7549 root->fs_info->sectorsize) - 1;
7550 ret = test_range_bit(io_tree, offset, range_end,
7551 EXTENT_DELALLOC, 0, NULL);
7558 btrfs_release_path(path);
7561 * look for other files referencing this extent, if we
7562 * find any we must cow
7565 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7566 key.offset - backref_offset, disk_bytenr,
7574 * adjust disk_bytenr and num_bytes to cover just the bytes
7575 * in this extent we are about to write. If there
7576 * are any csums in that range we have to cow in order
7577 * to keep the csums correct
7579 disk_bytenr += backref_offset;
7580 disk_bytenr += offset - key.offset;
7581 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7584 * all of the above have passed, it is safe to overwrite this extent
7590 btrfs_free_path(path);
7594 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7595 struct extent_state **cached_state, bool writing)
7597 struct btrfs_ordered_extent *ordered;
7601 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7604 * We're concerned with the entire range that we're going to be
7605 * doing DIO to, so we need to make sure there's no ordered
7606 * extents in this range.
7608 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7609 lockend - lockstart + 1);
7612 * We need to make sure there are no buffered pages in this
7613 * range either, we could have raced between the invalidate in
7614 * generic_file_direct_write and locking the extent. The
7615 * invalidate needs to happen so that reads after a write do not
7619 (!writing || !filemap_range_has_page(inode->i_mapping,
7620 lockstart, lockend)))
7623 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7628 * If we are doing a DIO read and the ordered extent we
7629 * found is for a buffered write, we can not wait for it
7630 * to complete and retry, because if we do so we can
7631 * deadlock with concurrent buffered writes on page
7632 * locks. This happens only if our DIO read covers more
7633 * than one extent map, if at this point has already
7634 * created an ordered extent for a previous extent map
7635 * and locked its range in the inode's io tree, and a
7636 * concurrent write against that previous extent map's
7637 * range and this range started (we unlock the ranges
7638 * in the io tree only when the bios complete and
7639 * buffered writes always lock pages before attempting
7640 * to lock range in the io tree).
7643 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7644 btrfs_start_ordered_extent(ordered, 1);
7647 btrfs_put_ordered_extent(ordered);
7650 * We could trigger writeback for this range (and wait
7651 * for it to complete) and then invalidate the pages for
7652 * this range (through invalidate_inode_pages2_range()),
7653 * but that can lead us to a deadlock with a concurrent
7654 * call to readahead (a buffered read or a defrag call
7655 * triggered a readahead) on a page lock due to an
7656 * ordered dio extent we created before but did not have
7657 * yet a corresponding bio submitted (whence it can not
7658 * complete), which makes readahead wait for that
7659 * ordered extent to complete while holding a lock on
7674 /* The callers of this must take lock_extent() */
7675 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7676 u64 len, u64 orig_start, u64 block_start,
7677 u64 block_len, u64 orig_block_len,
7678 u64 ram_bytes, int compress_type,
7681 struct extent_map_tree *em_tree;
7682 struct extent_map *em;
7685 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7686 type == BTRFS_ORDERED_COMPRESSED ||
7687 type == BTRFS_ORDERED_NOCOW ||
7688 type == BTRFS_ORDERED_REGULAR);
7690 em_tree = &inode->extent_tree;
7691 em = alloc_extent_map();
7693 return ERR_PTR(-ENOMEM);
7696 em->orig_start = orig_start;
7698 em->block_len = block_len;
7699 em->block_start = block_start;
7700 em->orig_block_len = orig_block_len;
7701 em->ram_bytes = ram_bytes;
7702 em->generation = -1;
7703 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7704 if (type == BTRFS_ORDERED_PREALLOC) {
7705 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7706 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7707 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7708 em->compress_type = compress_type;
7712 btrfs_drop_extent_cache(inode, em->start,
7713 em->start + em->len - 1, 0);
7714 write_lock(&em_tree->lock);
7715 ret = add_extent_mapping(em_tree, em, 1);
7716 write_unlock(&em_tree->lock);
7718 * The caller has taken lock_extent(), who could race with us
7721 } while (ret == -EEXIST);
7724 free_extent_map(em);
7725 return ERR_PTR(ret);
7728 /* em got 2 refs now, callers needs to do free_extent_map once. */
7733 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7734 struct inode *inode,
7735 struct btrfs_dio_data *dio_data,
7738 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7739 struct extent_map *em = *map;
7743 * We don't allocate a new extent in the following cases
7745 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7747 * 2) The extent is marked as PREALLOC. We're good to go here and can
7748 * just use the extent.
7751 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7752 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7753 em->block_start != EXTENT_MAP_HOLE)) {
7755 u64 block_start, orig_start, orig_block_len, ram_bytes;
7757 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7758 type = BTRFS_ORDERED_PREALLOC;
7760 type = BTRFS_ORDERED_NOCOW;
7761 len = min(len, em->len - (start - em->start));
7762 block_start = em->block_start + (start - em->start);
7764 if (can_nocow_extent(inode, start, &len, &orig_start,
7765 &orig_block_len, &ram_bytes, false) == 1 &&
7766 btrfs_inc_nocow_writers(fs_info, block_start)) {
7767 struct extent_map *em2;
7769 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7770 orig_start, block_start,
7771 len, orig_block_len,
7773 btrfs_dec_nocow_writers(fs_info, block_start);
7774 if (type == BTRFS_ORDERED_PREALLOC) {
7775 free_extent_map(em);
7779 if (em2 && IS_ERR(em2)) {
7784 * For inode marked NODATACOW or extent marked PREALLOC,
7785 * use the existing or preallocated extent, so does not
7786 * need to adjust btrfs_space_info's bytes_may_use.
7788 btrfs_free_reserved_data_space_noquota(fs_info, len);
7793 /* this will cow the extent */
7794 free_extent_map(em);
7795 *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7801 len = min(len, em->len - (start - em->start));
7805 * Need to update the i_size under the extent lock so buffered
7806 * readers will get the updated i_size when we unlock.
7808 if (start + len > i_size_read(inode))
7809 i_size_write(inode, start + len);
7811 dio_data->reserve -= len;
7816 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7817 loff_t length, unsigned int flags, struct iomap *iomap,
7818 struct iomap *srcmap)
7820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7821 struct extent_map *em;
7822 struct extent_state *cached_state = NULL;
7823 struct btrfs_dio_data *dio_data = NULL;
7824 u64 lockstart, lockend;
7825 const bool write = !!(flags & IOMAP_WRITE);
7828 bool unlock_extents = false;
7831 len = min_t(u64, len, fs_info->sectorsize);
7834 lockend = start + len - 1;
7837 * The generic stuff only does filemap_write_and_wait_range, which
7838 * isn't enough if we've written compressed pages to this area, so we
7839 * need to flush the dirty pages again to make absolutely sure that any
7840 * outstanding dirty pages are on disk.
7842 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7843 &BTRFS_I(inode)->runtime_flags)) {
7844 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7845 start + length - 1);
7850 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7854 dio_data->length = length;
7856 dio_data->reserve = round_up(length, fs_info->sectorsize);
7857 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7858 &dio_data->data_reserved,
7859 start, dio_data->reserve);
7861 extent_changeset_free(dio_data->data_reserved);
7866 iomap->private = dio_data;
7870 * If this errors out it's because we couldn't invalidate pagecache for
7871 * this range and we need to fallback to buffered.
7873 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7878 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7885 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7886 * io. INLINE is special, and we could probably kludge it in here, but
7887 * it's still buffered so for safety lets just fall back to the generic
7890 * For COMPRESSED we _have_ to read the entire extent in so we can
7891 * decompress it, so there will be buffering required no matter what we
7892 * do, so go ahead and fallback to buffered.
7894 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7895 * to buffered IO. Don't blame me, this is the price we pay for using
7898 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7899 em->block_start == EXTENT_MAP_INLINE) {
7900 free_extent_map(em);
7905 len = min(len, em->len - (start - em->start));
7907 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7911 unlock_extents = true;
7912 /* Recalc len in case the new em is smaller than requested */
7913 len = min(len, em->len - (start - em->start));
7916 * We need to unlock only the end area that we aren't using.
7917 * The rest is going to be unlocked by the endio routine.
7919 lockstart = start + len;
7920 if (lockstart < lockend)
7921 unlock_extents = true;
7925 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7926 lockstart, lockend, &cached_state);
7928 free_extent_state(cached_state);
7931 * Translate extent map information to iomap.
7932 * We trim the extents (and move the addr) even though iomap code does
7933 * that, since we have locked only the parts we are performing I/O in.
7935 if ((em->block_start == EXTENT_MAP_HOLE) ||
7936 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7937 iomap->addr = IOMAP_NULL_ADDR;
7938 iomap->type = IOMAP_HOLE;
7940 iomap->addr = em->block_start + (start - em->start);
7941 iomap->type = IOMAP_MAPPED;
7943 iomap->offset = start;
7944 iomap->bdev = fs_info->fs_devices->latest_bdev;
7945 iomap->length = len;
7947 if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
7948 iomap->flags |= IOMAP_F_ZONE_APPEND;
7950 free_extent_map(em);
7955 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7959 btrfs_delalloc_release_space(BTRFS_I(inode),
7960 dio_data->data_reserved, start,
7961 dio_data->reserve, true);
7962 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7963 extent_changeset_free(dio_data->data_reserved);
7969 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7970 ssize_t written, unsigned int flags, struct iomap *iomap)
7973 struct btrfs_dio_data *dio_data = iomap->private;
7974 size_t submitted = dio_data->submitted;
7975 const bool write = !!(flags & IOMAP_WRITE);
7977 if (!write && (iomap->type == IOMAP_HOLE)) {
7978 /* If reading from a hole, unlock and return */
7979 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7983 if (submitted < length) {
7985 length -= submitted;
7987 __endio_write_update_ordered(BTRFS_I(inode), pos,
7990 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7996 if (dio_data->reserve)
7997 btrfs_delalloc_release_space(BTRFS_I(inode),
7998 dio_data->data_reserved, pos,
7999 dio_data->reserve, true);
8000 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
8001 extent_changeset_free(dio_data->data_reserved);
8005 iomap->private = NULL;
8010 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
8013 * This implies a barrier so that stores to dio_bio->bi_status before
8014 * this and loads of dio_bio->bi_status after this are fully ordered.
8016 if (!refcount_dec_and_test(&dip->refs))
8019 if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
8020 __endio_write_update_ordered(BTRFS_I(dip->inode),
8021 dip->logical_offset,
8023 !dip->dio_bio->bi_status);
8025 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
8026 dip->logical_offset,
8027 dip->logical_offset + dip->bytes - 1);
8030 bio_endio(dip->dio_bio);
8034 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
8036 unsigned long bio_flags)
8038 struct btrfs_dio_private *dip = bio->bi_private;
8039 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8042 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
8044 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8048 refcount_inc(&dip->refs);
8049 ret = btrfs_map_bio(fs_info, bio, mirror_num);
8051 refcount_dec(&dip->refs);
8055 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
8056 struct btrfs_io_bio *io_bio,
8057 const bool uptodate)
8059 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
8060 const u32 sectorsize = fs_info->sectorsize;
8061 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
8062 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8063 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8064 struct bio_vec bvec;
8065 struct bvec_iter iter;
8066 u64 start = io_bio->logical;
8068 blk_status_t err = BLK_STS_OK;
8070 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
8071 unsigned int i, nr_sectors, pgoff;
8073 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8074 pgoff = bvec.bv_offset;
8075 for (i = 0; i < nr_sectors; i++) {
8076 ASSERT(pgoff < PAGE_SIZE);
8078 (!csum || !check_data_csum(inode, io_bio,
8079 bio_offset, bvec.bv_page,
8081 clean_io_failure(fs_info, failure_tree, io_tree,
8082 start, bvec.bv_page,
8083 btrfs_ino(BTRFS_I(inode)),
8088 ASSERT((start - io_bio->logical) < UINT_MAX);
8089 ret = btrfs_repair_one_sector(inode,
8091 start - io_bio->logical,
8092 bvec.bv_page, pgoff,
8093 start, io_bio->mirror_num,
8094 submit_dio_repair_bio);
8096 err = errno_to_blk_status(ret);
8098 start += sectorsize;
8099 ASSERT(bio_offset + sectorsize > bio_offset);
8100 bio_offset += sectorsize;
8101 pgoff += sectorsize;
8107 static void __endio_write_update_ordered(struct btrfs_inode *inode,
8108 const u64 offset, const u64 bytes,
8109 const bool uptodate)
8111 btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes,
8112 finish_ordered_fn, uptodate);
8115 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
8117 u64 dio_file_offset)
8119 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, 1);
8122 static void btrfs_end_dio_bio(struct bio *bio)
8124 struct btrfs_dio_private *dip = bio->bi_private;
8125 blk_status_t err = bio->bi_status;
8128 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8129 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8130 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8131 bio->bi_opf, bio->bi_iter.bi_sector,
8132 bio->bi_iter.bi_size, err);
8134 if (bio_op(bio) == REQ_OP_READ) {
8135 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
8140 dip->dio_bio->bi_status = err;
8142 btrfs_record_physical_zoned(dip->inode, dip->logical_offset, bio);
8145 btrfs_dio_private_put(dip);
8148 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8149 struct inode *inode, u64 file_offset, int async_submit)
8151 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8152 struct btrfs_dio_private *dip = bio->bi_private;
8153 bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
8156 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8158 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8161 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8166 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8169 if (write && async_submit) {
8170 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
8171 btrfs_submit_bio_start_direct_io);
8175 * If we aren't doing async submit, calculate the csum of the
8178 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
8184 csum_offset = file_offset - dip->logical_offset;
8185 csum_offset >>= fs_info->sectorsize_bits;
8186 csum_offset *= fs_info->csum_size;
8187 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
8190 ret = btrfs_map_bio(fs_info, bio, 0);
8196 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
8197 * or ordered extents whether or not we submit any bios.
8199 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
8200 struct inode *inode,
8203 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8204 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8206 struct btrfs_dio_private *dip;
8208 dip_size = sizeof(*dip);
8209 if (!write && csum) {
8210 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8213 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
8214 dip_size += fs_info->csum_size * nblocks;
8217 dip = kzalloc(dip_size, GFP_NOFS);
8222 dip->logical_offset = file_offset;
8223 dip->bytes = dio_bio->bi_iter.bi_size;
8224 dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
8225 dip->dio_bio = dio_bio;
8226 refcount_set(&dip->refs, 1);
8230 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
8231 struct bio *dio_bio, loff_t file_offset)
8233 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8234 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8235 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8236 BTRFS_BLOCK_GROUP_RAID56_MASK);
8237 struct btrfs_dio_private *dip;
8240 int async_submit = 0;
8242 u64 clone_offset = 0;
8246 blk_status_t status;
8247 struct btrfs_io_geometry geom;
8248 struct btrfs_dio_data *dio_data = iomap->private;
8249 struct extent_map *em = NULL;
8251 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
8254 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8255 file_offset + dio_bio->bi_iter.bi_size - 1);
8257 dio_bio->bi_status = BLK_STS_RESOURCE;
8259 return BLK_QC_T_NONE;
8264 * Load the csums up front to reduce csum tree searches and
8265 * contention when submitting bios.
8267 * If we have csums disabled this will do nothing.
8269 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8270 if (status != BLK_STS_OK)
8274 start_sector = dio_bio->bi_iter.bi_sector;
8275 submit_len = dio_bio->bi_iter.bi_size;
8278 logical = start_sector << 9;
8279 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8281 status = errno_to_blk_status(PTR_ERR(em));
8285 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8288 status = errno_to_blk_status(ret);
8292 clone_len = min(submit_len, geom.len);
8293 ASSERT(clone_len <= UINT_MAX);
8296 * This will never fail as it's passing GPF_NOFS and
8297 * the allocation is backed by btrfs_bioset.
8299 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8300 bio->bi_private = dip;
8301 bio->bi_end_io = btrfs_end_dio_bio;
8302 btrfs_io_bio(bio)->logical = file_offset;
8304 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8305 status = extract_ordered_extent(BTRFS_I(inode), bio,
8313 ASSERT(submit_len >= clone_len);
8314 submit_len -= clone_len;
8317 * Increase the count before we submit the bio so we know
8318 * the end IO handler won't happen before we increase the
8319 * count. Otherwise, the dip might get freed before we're
8320 * done setting it up.
8322 * We transfer the initial reference to the last bio, so we
8323 * don't need to increment the reference count for the last one.
8325 if (submit_len > 0) {
8326 refcount_inc(&dip->refs);
8328 * If we are submitting more than one bio, submit them
8329 * all asynchronously. The exception is RAID 5 or 6, as
8330 * asynchronous checksums make it difficult to collect
8331 * full stripe writes.
8337 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8342 refcount_dec(&dip->refs);
8346 dio_data->submitted += clone_len;
8347 clone_offset += clone_len;
8348 start_sector += clone_len >> 9;
8349 file_offset += clone_len;
8351 free_extent_map(em);
8352 } while (submit_len > 0);
8353 return BLK_QC_T_NONE;
8356 free_extent_map(em);
8358 dip->dio_bio->bi_status = status;
8359 btrfs_dio_private_put(dip);
8361 return BLK_QC_T_NONE;
8364 const struct iomap_ops btrfs_dio_iomap_ops = {
8365 .iomap_begin = btrfs_dio_iomap_begin,
8366 .iomap_end = btrfs_dio_iomap_end,
8369 const struct iomap_dio_ops btrfs_dio_ops = {
8370 .submit_io = btrfs_submit_direct,
8373 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8378 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8382 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8385 int btrfs_readpage(struct file *file, struct page *page)
8387 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8388 u64 start = page_offset(page);
8389 u64 end = start + PAGE_SIZE - 1;
8390 struct btrfs_bio_ctrl bio_ctrl = { 0 };
8393 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8395 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
8397 ret = submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags);
8401 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8403 struct inode *inode = page->mapping->host;
8406 if (current->flags & PF_MEMALLOC) {
8407 redirty_page_for_writepage(wbc, page);
8413 * If we are under memory pressure we will call this directly from the
8414 * VM, we need to make sure we have the inode referenced for the ordered
8415 * extent. If not just return like we didn't do anything.
8417 if (!igrab(inode)) {
8418 redirty_page_for_writepage(wbc, page);
8419 return AOP_WRITEPAGE_ACTIVATE;
8421 ret = extent_write_full_page(page, wbc);
8422 btrfs_add_delayed_iput(inode);
8426 static int btrfs_writepages(struct address_space *mapping,
8427 struct writeback_control *wbc)
8429 return extent_writepages(mapping, wbc);
8432 static void btrfs_readahead(struct readahead_control *rac)
8434 extent_readahead(rac);
8438 * For releasepage() and invalidatepage() we have a race window where
8439 * end_page_writeback() is called but the subpage spinlock is not yet released.
8440 * If we continue to release/invalidate the page, we could cause use-after-free
8441 * for subpage spinlock. So this function is to spin and wait for subpage
8444 static void wait_subpage_spinlock(struct page *page)
8446 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
8447 struct btrfs_subpage *subpage;
8449 if (fs_info->sectorsize == PAGE_SIZE)
8452 ASSERT(PagePrivate(page) && page->private);
8453 subpage = (struct btrfs_subpage *)page->private;
8456 * This may look insane as we just acquire the spinlock and release it,
8457 * without doing anything. But we just want to make sure no one is
8458 * still holding the subpage spinlock.
8459 * And since the page is not dirty nor writeback, and we have page
8460 * locked, the only possible way to hold a spinlock is from the endio
8461 * function to clear page writeback.
8463 * Here we just acquire the spinlock so that all existing callers
8464 * should exit and we're safe to release/invalidate the page.
8466 spin_lock_irq(&subpage->lock);
8467 spin_unlock_irq(&subpage->lock);
8470 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8472 int ret = try_release_extent_mapping(page, gfp_flags);
8475 wait_subpage_spinlock(page);
8476 clear_page_extent_mapped(page);
8481 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8483 if (PageWriteback(page) || PageDirty(page))
8485 return __btrfs_releasepage(page, gfp_flags);
8488 #ifdef CONFIG_MIGRATION
8489 static int btrfs_migratepage(struct address_space *mapping,
8490 struct page *newpage, struct page *page,
8491 enum migrate_mode mode)
8495 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8496 if (ret != MIGRATEPAGE_SUCCESS)
8499 if (page_has_private(page))
8500 attach_page_private(newpage, detach_page_private(page));
8502 if (PageOrdered(page)) {
8503 ClearPageOrdered(page);
8504 SetPageOrdered(newpage);
8507 if (mode != MIGRATE_SYNC_NO_COPY)
8508 migrate_page_copy(newpage, page);
8510 migrate_page_states(newpage, page);
8511 return MIGRATEPAGE_SUCCESS;
8515 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8516 unsigned int length)
8518 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8519 struct btrfs_fs_info *fs_info = inode->root->fs_info;
8520 struct extent_io_tree *tree = &inode->io_tree;
8521 struct extent_state *cached_state = NULL;
8522 u64 page_start = page_offset(page);
8523 u64 page_end = page_start + PAGE_SIZE - 1;
8525 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8528 * We have page locked so no new ordered extent can be created on this
8529 * page, nor bio can be submitted for this page.
8531 * But already submitted bio can still be finished on this page.
8532 * Furthermore, endio function won't skip page which has Ordered
8533 * (Private2) already cleared, so it's possible for endio and
8534 * invalidatepage to do the same ordered extent accounting twice
8537 * So here we wait for any submitted bios to finish, so that we won't
8538 * do double ordered extent accounting on the same page.
8540 wait_on_page_writeback(page);
8541 wait_subpage_spinlock(page);
8544 * For subpage case, we have call sites like
8545 * btrfs_punch_hole_lock_range() which passes range not aligned to
8547 * If the range doesn't cover the full page, we don't need to and
8548 * shouldn't clear page extent mapped, as page->private can still
8549 * record subpage dirty bits for other part of the range.
8551 * For cases that can invalidate the full even the range doesn't
8552 * cover the full page, like invalidating the last page, we're
8553 * still safe to wait for ordered extent to finish.
8555 if (!(offset == 0 && length == PAGE_SIZE)) {
8556 btrfs_releasepage(page, GFP_NOFS);
8560 if (!inode_evicting)
8561 lock_extent_bits(tree, page_start, page_end, &cached_state);
8564 while (cur < page_end) {
8565 struct btrfs_ordered_extent *ordered;
8570 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8571 page_end + 1 - cur);
8573 range_end = page_end;
8575 * No ordered extent covering this range, we are safe
8576 * to delete all extent states in the range.
8578 delete_states = true;
8581 if (ordered->file_offset > cur) {
8583 * There is a range between [cur, oe->file_offset) not
8584 * covered by any ordered extent.
8585 * We are safe to delete all extent states, and handle
8586 * the ordered extent in the next iteration.
8588 range_end = ordered->file_offset - 1;
8589 delete_states = true;
8593 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8595 ASSERT(range_end + 1 - cur < U32_MAX);
8596 range_len = range_end + 1 - cur;
8597 if (!btrfs_page_test_ordered(fs_info, page, cur, range_len)) {
8599 * If Ordered (Private2) is cleared, it means endio has
8600 * already been executed for the range.
8601 * We can't delete the extent states as
8602 * btrfs_finish_ordered_io() may still use some of them.
8604 delete_states = false;
8607 btrfs_page_clear_ordered(fs_info, page, cur, range_len);
8610 * IO on this page will never be started, so we need to account
8611 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8612 * here, must leave that up for the ordered extent completion.
8614 * This will also unlock the range for incoming
8615 * btrfs_finish_ordered_io().
8617 if (!inode_evicting)
8618 clear_extent_bit(tree, cur, range_end,
8620 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8621 EXTENT_DEFRAG, 1, 0, &cached_state);
8623 spin_lock_irq(&inode->ordered_tree.lock);
8624 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8625 ordered->truncated_len = min(ordered->truncated_len,
8626 cur - ordered->file_offset);
8627 spin_unlock_irq(&inode->ordered_tree.lock);
8629 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8630 cur, range_end + 1 - cur)) {
8631 btrfs_finish_ordered_io(ordered);
8633 * The ordered extent has finished, now we're again
8634 * safe to delete all extent states of the range.
8636 delete_states = true;
8639 * btrfs_finish_ordered_io() will get executed by endio
8640 * of other pages, thus we can't delete extent states
8643 delete_states = false;
8647 btrfs_put_ordered_extent(ordered);
8649 * Qgroup reserved space handler
8650 * Sector(s) here will be either:
8652 * 1) Already written to disk or bio already finished
8653 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8654 * Qgroup will be handled by its qgroup_record then.
8655 * btrfs_qgroup_free_data() call will do nothing here.
8657 * 2) Not written to disk yet
8658 * Then btrfs_qgroup_free_data() call will clear the
8659 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8660 * reserved data space.
8661 * Since the IO will never happen for this page.
8663 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8664 if (!inode_evicting) {
8665 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8666 EXTENT_DELALLOC | EXTENT_UPTODATE |
8667 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8668 delete_states, &cached_state);
8670 cur = range_end + 1;
8673 * We have iterated through all ordered extents of the page, the page
8674 * should not have Ordered (Private2) anymore, or the above iteration
8675 * did something wrong.
8677 ASSERT(!PageOrdered(page));
8678 if (!inode_evicting)
8679 __btrfs_releasepage(page, GFP_NOFS);
8680 ClearPageChecked(page);
8681 clear_page_extent_mapped(page);
8685 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8686 * called from a page fault handler when a page is first dirtied. Hence we must
8687 * be careful to check for EOF conditions here. We set the page up correctly
8688 * for a written page which means we get ENOSPC checking when writing into
8689 * holes and correct delalloc and unwritten extent mapping on filesystems that
8690 * support these features.
8692 * We are not allowed to take the i_mutex here so we have to play games to
8693 * protect against truncate races as the page could now be beyond EOF. Because
8694 * truncate_setsize() writes the inode size before removing pages, once we have
8695 * the page lock we can determine safely if the page is beyond EOF. If it is not
8696 * beyond EOF, then the page is guaranteed safe against truncation until we
8699 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8701 struct page *page = vmf->page;
8702 struct inode *inode = file_inode(vmf->vma->vm_file);
8703 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8704 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8705 struct btrfs_ordered_extent *ordered;
8706 struct extent_state *cached_state = NULL;
8707 struct extent_changeset *data_reserved = NULL;
8708 unsigned long zero_start;
8718 reserved_space = PAGE_SIZE;
8720 sb_start_pagefault(inode->i_sb);
8721 page_start = page_offset(page);
8722 page_end = page_start + PAGE_SIZE - 1;
8726 * Reserving delalloc space after obtaining the page lock can lead to
8727 * deadlock. For example, if a dirty page is locked by this function
8728 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8729 * dirty page write out, then the btrfs_writepage() function could
8730 * end up waiting indefinitely to get a lock on the page currently
8731 * being processed by btrfs_page_mkwrite() function.
8733 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8734 page_start, reserved_space);
8736 ret2 = file_update_time(vmf->vma->vm_file);
8740 ret = vmf_error(ret2);
8746 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8748 down_read(&BTRFS_I(inode)->i_mmap_lock);
8750 size = i_size_read(inode);
8752 if ((page->mapping != inode->i_mapping) ||
8753 (page_start >= size)) {
8754 /* page got truncated out from underneath us */
8757 wait_on_page_writeback(page);
8759 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8760 ret2 = set_page_extent_mapped(page);
8762 ret = vmf_error(ret2);
8763 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8768 * we can't set the delalloc bits if there are pending ordered
8769 * extents. Drop our locks and wait for them to finish
8771 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8774 unlock_extent_cached(io_tree, page_start, page_end,
8777 up_read(&BTRFS_I(inode)->i_mmap_lock);
8778 btrfs_start_ordered_extent(ordered, 1);
8779 btrfs_put_ordered_extent(ordered);
8783 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8784 reserved_space = round_up(size - page_start,
8785 fs_info->sectorsize);
8786 if (reserved_space < PAGE_SIZE) {
8787 end = page_start + reserved_space - 1;
8788 btrfs_delalloc_release_space(BTRFS_I(inode),
8789 data_reserved, page_start,
8790 PAGE_SIZE - reserved_space, true);
8795 * page_mkwrite gets called when the page is firstly dirtied after it's
8796 * faulted in, but write(2) could also dirty a page and set delalloc
8797 * bits, thus in this case for space account reason, we still need to
8798 * clear any delalloc bits within this page range since we have to
8799 * reserve data&meta space before lock_page() (see above comments).
8801 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8802 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8803 EXTENT_DEFRAG, 0, 0, &cached_state);
8805 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8808 unlock_extent_cached(io_tree, page_start, page_end,
8810 ret = VM_FAULT_SIGBUS;
8814 /* page is wholly or partially inside EOF */
8815 if (page_start + PAGE_SIZE > size)
8816 zero_start = offset_in_page(size);
8818 zero_start = PAGE_SIZE;
8820 if (zero_start != PAGE_SIZE) {
8821 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8822 flush_dcache_page(page);
8824 ClearPageChecked(page);
8825 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8826 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8828 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8830 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8831 up_read(&BTRFS_I(inode)->i_mmap_lock);
8833 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8834 sb_end_pagefault(inode->i_sb);
8835 extent_changeset_free(data_reserved);
8836 return VM_FAULT_LOCKED;
8840 up_read(&BTRFS_I(inode)->i_mmap_lock);
8842 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8843 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8844 reserved_space, (ret != 0));
8846 sb_end_pagefault(inode->i_sb);
8847 extent_changeset_free(data_reserved);
8851 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8853 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8854 struct btrfs_root *root = BTRFS_I(inode)->root;
8855 struct btrfs_block_rsv *rsv;
8857 struct btrfs_trans_handle *trans;
8858 u64 mask = fs_info->sectorsize - 1;
8859 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8860 u64 extents_found = 0;
8862 if (!skip_writeback) {
8863 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8870 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8871 * things going on here:
8873 * 1) We need to reserve space to update our inode.
8875 * 2) We need to have something to cache all the space that is going to
8876 * be free'd up by the truncate operation, but also have some slack
8877 * space reserved in case it uses space during the truncate (thank you
8878 * very much snapshotting).
8880 * And we need these to be separate. The fact is we can use a lot of
8881 * space doing the truncate, and we have no earthly idea how much space
8882 * we will use, so we need the truncate reservation to be separate so it
8883 * doesn't end up using space reserved for updating the inode. We also
8884 * need to be able to stop the transaction and start a new one, which
8885 * means we need to be able to update the inode several times, and we
8886 * have no idea of knowing how many times that will be, so we can't just
8887 * reserve 1 item for the entirety of the operation, so that has to be
8888 * done separately as well.
8890 * So that leaves us with
8892 * 1) rsv - for the truncate reservation, which we will steal from the
8893 * transaction reservation.
8894 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8895 * updating the inode.
8897 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8900 rsv->size = min_size;
8904 * 1 for the truncate slack space
8905 * 1 for updating the inode.
8907 trans = btrfs_start_transaction(root, 2);
8908 if (IS_ERR(trans)) {
8909 ret = PTR_ERR(trans);
8913 /* Migrate the slack space for the truncate to our reserve */
8914 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8918 trans->block_rsv = rsv;
8921 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
8923 BTRFS_EXTENT_DATA_KEY,
8925 trans->block_rsv = &fs_info->trans_block_rsv;
8926 if (ret != -ENOSPC && ret != -EAGAIN)
8929 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8933 btrfs_end_transaction(trans);
8934 btrfs_btree_balance_dirty(fs_info);
8936 trans = btrfs_start_transaction(root, 2);
8937 if (IS_ERR(trans)) {
8938 ret = PTR_ERR(trans);
8943 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8944 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8945 rsv, min_size, false);
8946 BUG_ON(ret); /* shouldn't happen */
8947 trans->block_rsv = rsv;
8951 * We can't call btrfs_truncate_block inside a trans handle as we could
8952 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8953 * we've truncated everything except the last little bit, and can do
8954 * btrfs_truncate_block and then update the disk_i_size.
8956 if (ret == NEED_TRUNCATE_BLOCK) {
8957 btrfs_end_transaction(trans);
8958 btrfs_btree_balance_dirty(fs_info);
8960 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8963 trans = btrfs_start_transaction(root, 1);
8964 if (IS_ERR(trans)) {
8965 ret = PTR_ERR(trans);
8968 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8974 trans->block_rsv = &fs_info->trans_block_rsv;
8975 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8979 ret2 = btrfs_end_transaction(trans);
8982 btrfs_btree_balance_dirty(fs_info);
8985 btrfs_free_block_rsv(fs_info, rsv);
8987 * So if we truncate and then write and fsync we normally would just
8988 * write the extents that changed, which is a problem if we need to
8989 * first truncate that entire inode. So set this flag so we write out
8990 * all of the extents in the inode to the sync log so we're completely
8993 * If no extents were dropped or trimmed we don't need to force the next
8994 * fsync to truncate all the inode's items from the log and re-log them
8995 * all. This means the truncate operation did not change the file size,
8996 * or changed it to a smaller size but there was only an implicit hole
8997 * between the old i_size and the new i_size, and there were no prealloc
8998 * extents beyond i_size to drop.
9000 if (extents_found > 0)
9001 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9007 * create a new subvolume directory/inode (helper for the ioctl).
9009 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9010 struct btrfs_root *new_root,
9011 struct btrfs_root *parent_root)
9013 struct inode *inode;
9018 err = btrfs_get_free_objectid(new_root, &ino);
9022 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, ino, ino,
9023 S_IFDIR | (~current_umask() & S_IRWXUGO),
9026 return PTR_ERR(inode);
9027 inode->i_op = &btrfs_dir_inode_operations;
9028 inode->i_fop = &btrfs_dir_file_operations;
9030 set_nlink(inode, 1);
9031 btrfs_i_size_write(BTRFS_I(inode), 0);
9032 unlock_new_inode(inode);
9034 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9036 btrfs_err(new_root->fs_info,
9037 "error inheriting subvolume %llu properties: %d",
9038 new_root->root_key.objectid, err);
9040 err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
9046 struct inode *btrfs_alloc_inode(struct super_block *sb)
9048 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9049 struct btrfs_inode *ei;
9050 struct inode *inode;
9052 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9059 ei->last_sub_trans = 0;
9060 ei->logged_trans = 0;
9061 ei->delalloc_bytes = 0;
9062 ei->new_delalloc_bytes = 0;
9063 ei->defrag_bytes = 0;
9064 ei->disk_i_size = 0;
9067 ei->index_cnt = (u64)-1;
9069 ei->last_unlink_trans = 0;
9070 ei->last_reflink_trans = 0;
9071 ei->last_log_commit = 0;
9073 spin_lock_init(&ei->lock);
9074 ei->outstanding_extents = 0;
9075 if (sb->s_magic != BTRFS_TEST_MAGIC)
9076 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9077 BTRFS_BLOCK_RSV_DELALLOC);
9078 ei->runtime_flags = 0;
9079 ei->prop_compress = BTRFS_COMPRESS_NONE;
9080 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9082 ei->delayed_node = NULL;
9084 ei->i_otime.tv_sec = 0;
9085 ei->i_otime.tv_nsec = 0;
9087 inode = &ei->vfs_inode;
9088 extent_map_tree_init(&ei->extent_tree);
9089 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9090 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9091 IO_TREE_INODE_IO_FAILURE, inode);
9092 extent_io_tree_init(fs_info, &ei->file_extent_tree,
9093 IO_TREE_INODE_FILE_EXTENT, inode);
9094 ei->io_tree.track_uptodate = true;
9095 ei->io_failure_tree.track_uptodate = true;
9096 atomic_set(&ei->sync_writers, 0);
9097 mutex_init(&ei->log_mutex);
9098 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9099 INIT_LIST_HEAD(&ei->delalloc_inodes);
9100 INIT_LIST_HEAD(&ei->delayed_iput);
9101 RB_CLEAR_NODE(&ei->rb_node);
9102 init_rwsem(&ei->i_mmap_lock);
9107 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9108 void btrfs_test_destroy_inode(struct inode *inode)
9110 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9111 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9115 void btrfs_free_inode(struct inode *inode)
9117 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9120 void btrfs_destroy_inode(struct inode *vfs_inode)
9122 struct btrfs_ordered_extent *ordered;
9123 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
9124 struct btrfs_root *root = inode->root;
9126 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
9127 WARN_ON(vfs_inode->i_data.nrpages);
9128 WARN_ON(inode->block_rsv.reserved);
9129 WARN_ON(inode->block_rsv.size);
9130 WARN_ON(inode->outstanding_extents);
9131 WARN_ON(inode->delalloc_bytes);
9132 WARN_ON(inode->new_delalloc_bytes);
9133 WARN_ON(inode->csum_bytes);
9134 WARN_ON(inode->defrag_bytes);
9137 * This can happen where we create an inode, but somebody else also
9138 * created the same inode and we need to destroy the one we already
9145 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9149 btrfs_err(root->fs_info,
9150 "found ordered extent %llu %llu on inode cleanup",
9151 ordered->file_offset, ordered->num_bytes);
9152 btrfs_remove_ordered_extent(inode, ordered);
9153 btrfs_put_ordered_extent(ordered);
9154 btrfs_put_ordered_extent(ordered);
9157 btrfs_qgroup_check_reserved_leak(inode);
9158 inode_tree_del(inode);
9159 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9160 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
9161 btrfs_put_root(inode->root);
9164 int btrfs_drop_inode(struct inode *inode)
9166 struct btrfs_root *root = BTRFS_I(inode)->root;
9171 /* the snap/subvol tree is on deleting */
9172 if (btrfs_root_refs(&root->root_item) == 0)
9175 return generic_drop_inode(inode);
9178 static void init_once(void *foo)
9180 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9182 inode_init_once(&ei->vfs_inode);
9185 void __cold btrfs_destroy_cachep(void)
9188 * Make sure all delayed rcu free inodes are flushed before we
9192 kmem_cache_destroy(btrfs_inode_cachep);
9193 kmem_cache_destroy(btrfs_trans_handle_cachep);
9194 kmem_cache_destroy(btrfs_path_cachep);
9195 kmem_cache_destroy(btrfs_free_space_cachep);
9196 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
9199 int __init btrfs_init_cachep(void)
9201 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9202 sizeof(struct btrfs_inode), 0,
9203 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9205 if (!btrfs_inode_cachep)
9208 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9209 sizeof(struct btrfs_trans_handle), 0,
9210 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9211 if (!btrfs_trans_handle_cachep)
9214 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9215 sizeof(struct btrfs_path), 0,
9216 SLAB_MEM_SPREAD, NULL);
9217 if (!btrfs_path_cachep)
9220 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9221 sizeof(struct btrfs_free_space), 0,
9222 SLAB_MEM_SPREAD, NULL);
9223 if (!btrfs_free_space_cachep)
9226 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9227 PAGE_SIZE, PAGE_SIZE,
9228 SLAB_MEM_SPREAD, NULL);
9229 if (!btrfs_free_space_bitmap_cachep)
9234 btrfs_destroy_cachep();
9238 static int btrfs_getattr(struct user_namespace *mnt_userns,
9239 const struct path *path, struct kstat *stat,
9240 u32 request_mask, unsigned int flags)
9244 struct inode *inode = d_inode(path->dentry);
9245 u32 blocksize = inode->i_sb->s_blocksize;
9246 u32 bi_flags = BTRFS_I(inode)->flags;
9248 stat->result_mask |= STATX_BTIME;
9249 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9250 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9251 if (bi_flags & BTRFS_INODE_APPEND)
9252 stat->attributes |= STATX_ATTR_APPEND;
9253 if (bi_flags & BTRFS_INODE_COMPRESS)
9254 stat->attributes |= STATX_ATTR_COMPRESSED;
9255 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9256 stat->attributes |= STATX_ATTR_IMMUTABLE;
9257 if (bi_flags & BTRFS_INODE_NODUMP)
9258 stat->attributes |= STATX_ATTR_NODUMP;
9260 stat->attributes_mask |= (STATX_ATTR_APPEND |
9261 STATX_ATTR_COMPRESSED |
9262 STATX_ATTR_IMMUTABLE |
9265 generic_fillattr(&init_user_ns, inode, stat);
9266 stat->dev = BTRFS_I(inode)->root->anon_dev;
9268 spin_lock(&BTRFS_I(inode)->lock);
9269 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9270 inode_bytes = inode_get_bytes(inode);
9271 spin_unlock(&BTRFS_I(inode)->lock);
9272 stat->blocks = (ALIGN(inode_bytes, blocksize) +
9273 ALIGN(delalloc_bytes, blocksize)) >> 9;
9277 static int btrfs_rename_exchange(struct inode *old_dir,
9278 struct dentry *old_dentry,
9279 struct inode *new_dir,
9280 struct dentry *new_dentry)
9282 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9283 struct btrfs_trans_handle *trans;
9284 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9285 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9286 struct inode *new_inode = new_dentry->d_inode;
9287 struct inode *old_inode = old_dentry->d_inode;
9288 struct timespec64 ctime = current_time(old_inode);
9289 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9290 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9295 bool root_log_pinned = false;
9296 bool dest_log_pinned = false;
9297 bool need_abort = false;
9300 * For non-subvolumes allow exchange only within one subvolume, in the
9301 * same inode namespace. Two subvolumes (represented as directory) can
9302 * be exchanged as they're a logical link and have a fixed inode number.
9305 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9306 new_ino != BTRFS_FIRST_FREE_OBJECTID))
9309 /* close the race window with snapshot create/destroy ioctl */
9310 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9311 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9312 down_read(&fs_info->subvol_sem);
9315 * We want to reserve the absolute worst case amount of items. So if
9316 * both inodes are subvols and we need to unlink them then that would
9317 * require 4 item modifications, but if they are both normal inodes it
9318 * would require 5 item modifications, so we'll assume their normal
9319 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9320 * should cover the worst case number of items we'll modify.
9322 trans = btrfs_start_transaction(root, 12);
9323 if (IS_ERR(trans)) {
9324 ret = PTR_ERR(trans);
9329 ret = btrfs_record_root_in_trans(trans, dest);
9335 * We need to find a free sequence number both in the source and
9336 * in the destination directory for the exchange.
9338 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9341 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9345 BTRFS_I(old_inode)->dir_index = 0ULL;
9346 BTRFS_I(new_inode)->dir_index = 0ULL;
9348 /* Reference for the source. */
9349 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9350 /* force full log commit if subvolume involved. */
9351 btrfs_set_log_full_commit(trans);
9353 btrfs_pin_log_trans(root);
9354 root_log_pinned = true;
9355 ret = btrfs_insert_inode_ref(trans, dest,
9356 new_dentry->d_name.name,
9357 new_dentry->d_name.len,
9359 btrfs_ino(BTRFS_I(new_dir)),
9366 /* And now for the dest. */
9367 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9368 /* force full log commit if subvolume involved. */
9369 btrfs_set_log_full_commit(trans);
9371 btrfs_pin_log_trans(dest);
9372 dest_log_pinned = true;
9373 ret = btrfs_insert_inode_ref(trans, root,
9374 old_dentry->d_name.name,
9375 old_dentry->d_name.len,
9377 btrfs_ino(BTRFS_I(old_dir)),
9381 btrfs_abort_transaction(trans, ret);
9386 /* Update inode version and ctime/mtime. */
9387 inode_inc_iversion(old_dir);
9388 inode_inc_iversion(new_dir);
9389 inode_inc_iversion(old_inode);
9390 inode_inc_iversion(new_inode);
9391 old_dir->i_ctime = old_dir->i_mtime = ctime;
9392 new_dir->i_ctime = new_dir->i_mtime = ctime;
9393 old_inode->i_ctime = ctime;
9394 new_inode->i_ctime = ctime;
9396 if (old_dentry->d_parent != new_dentry->d_parent) {
9397 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9398 BTRFS_I(old_inode), 1);
9399 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9400 BTRFS_I(new_inode), 1);
9403 /* src is a subvolume */
9404 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9405 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9406 } else { /* src is an inode */
9407 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9408 BTRFS_I(old_dentry->d_inode),
9409 old_dentry->d_name.name,
9410 old_dentry->d_name.len);
9412 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9415 btrfs_abort_transaction(trans, ret);
9419 /* dest is a subvolume */
9420 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9421 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9422 } else { /* dest is an inode */
9423 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9424 BTRFS_I(new_dentry->d_inode),
9425 new_dentry->d_name.name,
9426 new_dentry->d_name.len);
9428 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9431 btrfs_abort_transaction(trans, ret);
9435 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9436 new_dentry->d_name.name,
9437 new_dentry->d_name.len, 0, old_idx);
9439 btrfs_abort_transaction(trans, ret);
9443 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9444 old_dentry->d_name.name,
9445 old_dentry->d_name.len, 0, new_idx);
9447 btrfs_abort_transaction(trans, ret);
9451 if (old_inode->i_nlink == 1)
9452 BTRFS_I(old_inode)->dir_index = old_idx;
9453 if (new_inode->i_nlink == 1)
9454 BTRFS_I(new_inode)->dir_index = new_idx;
9456 if (root_log_pinned) {
9457 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9458 new_dentry->d_parent);
9459 btrfs_end_log_trans(root);
9460 root_log_pinned = false;
9462 if (dest_log_pinned) {
9463 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9464 old_dentry->d_parent);
9465 btrfs_end_log_trans(dest);
9466 dest_log_pinned = false;
9470 * If we have pinned a log and an error happened, we unpin tasks
9471 * trying to sync the log and force them to fallback to a transaction
9472 * commit if the log currently contains any of the inodes involved in
9473 * this rename operation (to ensure we do not persist a log with an
9474 * inconsistent state for any of these inodes or leading to any
9475 * inconsistencies when replayed). If the transaction was aborted, the
9476 * abortion reason is propagated to userspace when attempting to commit
9477 * the transaction. If the log does not contain any of these inodes, we
9478 * allow the tasks to sync it.
9480 if (ret && (root_log_pinned || dest_log_pinned)) {
9481 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9482 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9483 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9485 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9486 btrfs_set_log_full_commit(trans);
9488 if (root_log_pinned) {
9489 btrfs_end_log_trans(root);
9490 root_log_pinned = false;
9492 if (dest_log_pinned) {
9493 btrfs_end_log_trans(dest);
9494 dest_log_pinned = false;
9497 ret2 = btrfs_end_transaction(trans);
9498 ret = ret ? ret : ret2;
9500 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9501 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9502 up_read(&fs_info->subvol_sem);
9507 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9508 struct btrfs_root *root,
9510 struct dentry *dentry)
9513 struct inode *inode;
9517 ret = btrfs_get_free_objectid(root, &objectid);
9521 inode = btrfs_new_inode(trans, root, dir,
9522 dentry->d_name.name,
9524 btrfs_ino(BTRFS_I(dir)),
9526 S_IFCHR | WHITEOUT_MODE,
9529 if (IS_ERR(inode)) {
9530 ret = PTR_ERR(inode);
9534 inode->i_op = &btrfs_special_inode_operations;
9535 init_special_inode(inode, inode->i_mode,
9538 ret = btrfs_init_inode_security(trans, inode, dir,
9543 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9544 BTRFS_I(inode), 0, index);
9548 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9550 unlock_new_inode(inode);
9552 inode_dec_link_count(inode);
9558 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9559 struct inode *new_dir, struct dentry *new_dentry,
9562 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9563 struct btrfs_trans_handle *trans;
9564 unsigned int trans_num_items;
9565 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9566 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9567 struct inode *new_inode = d_inode(new_dentry);
9568 struct inode *old_inode = d_inode(old_dentry);
9572 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9573 bool log_pinned = false;
9575 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9578 /* we only allow rename subvolume link between subvolumes */
9579 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9582 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9583 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9586 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9587 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9591 /* check for collisions, even if the name isn't there */
9592 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9593 new_dentry->d_name.name,
9594 new_dentry->d_name.len);
9597 if (ret == -EEXIST) {
9599 * eexist without a new_inode */
9600 if (WARN_ON(!new_inode)) {
9604 /* maybe -EOVERFLOW */
9611 * we're using rename to replace one file with another. Start IO on it
9612 * now so we don't add too much work to the end of the transaction
9614 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9615 filemap_flush(old_inode->i_mapping);
9617 /* close the racy window with snapshot create/destroy ioctl */
9618 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9619 down_read(&fs_info->subvol_sem);
9621 * We want to reserve the absolute worst case amount of items. So if
9622 * both inodes are subvols and we need to unlink them then that would
9623 * require 4 item modifications, but if they are both normal inodes it
9624 * would require 5 item modifications, so we'll assume they are normal
9625 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9626 * should cover the worst case number of items we'll modify.
9627 * If our rename has the whiteout flag, we need more 5 units for the
9628 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9629 * when selinux is enabled).
9631 trans_num_items = 11;
9632 if (flags & RENAME_WHITEOUT)
9633 trans_num_items += 5;
9634 trans = btrfs_start_transaction(root, trans_num_items);
9635 if (IS_ERR(trans)) {
9636 ret = PTR_ERR(trans);
9641 ret = btrfs_record_root_in_trans(trans, dest);
9646 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9650 BTRFS_I(old_inode)->dir_index = 0ULL;
9651 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9652 /* force full log commit if subvolume involved. */
9653 btrfs_set_log_full_commit(trans);
9655 btrfs_pin_log_trans(root);
9657 ret = btrfs_insert_inode_ref(trans, dest,
9658 new_dentry->d_name.name,
9659 new_dentry->d_name.len,
9661 btrfs_ino(BTRFS_I(new_dir)), index);
9666 inode_inc_iversion(old_dir);
9667 inode_inc_iversion(new_dir);
9668 inode_inc_iversion(old_inode);
9669 old_dir->i_ctime = old_dir->i_mtime =
9670 new_dir->i_ctime = new_dir->i_mtime =
9671 old_inode->i_ctime = current_time(old_dir);
9673 if (old_dentry->d_parent != new_dentry->d_parent)
9674 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9675 BTRFS_I(old_inode), 1);
9677 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9678 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9680 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9681 BTRFS_I(d_inode(old_dentry)),
9682 old_dentry->d_name.name,
9683 old_dentry->d_name.len);
9685 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9688 btrfs_abort_transaction(trans, ret);
9693 inode_inc_iversion(new_inode);
9694 new_inode->i_ctime = current_time(new_inode);
9695 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9696 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9697 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9698 BUG_ON(new_inode->i_nlink == 0);
9700 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9701 BTRFS_I(d_inode(new_dentry)),
9702 new_dentry->d_name.name,
9703 new_dentry->d_name.len);
9705 if (!ret && new_inode->i_nlink == 0)
9706 ret = btrfs_orphan_add(trans,
9707 BTRFS_I(d_inode(new_dentry)));
9709 btrfs_abort_transaction(trans, ret);
9714 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9715 new_dentry->d_name.name,
9716 new_dentry->d_name.len, 0, index);
9718 btrfs_abort_transaction(trans, ret);
9722 if (old_inode->i_nlink == 1)
9723 BTRFS_I(old_inode)->dir_index = index;
9726 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9727 new_dentry->d_parent);
9728 btrfs_end_log_trans(root);
9732 if (flags & RENAME_WHITEOUT) {
9733 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9737 btrfs_abort_transaction(trans, ret);
9743 * If we have pinned the log and an error happened, we unpin tasks
9744 * trying to sync the log and force them to fallback to a transaction
9745 * commit if the log currently contains any of the inodes involved in
9746 * this rename operation (to ensure we do not persist a log with an
9747 * inconsistent state for any of these inodes or leading to any
9748 * inconsistencies when replayed). If the transaction was aborted, the
9749 * abortion reason is propagated to userspace when attempting to commit
9750 * the transaction. If the log does not contain any of these inodes, we
9751 * allow the tasks to sync it.
9753 if (ret && log_pinned) {
9754 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9755 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9756 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9758 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9759 btrfs_set_log_full_commit(trans);
9761 btrfs_end_log_trans(root);
9764 ret2 = btrfs_end_transaction(trans);
9765 ret = ret ? ret : ret2;
9767 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9768 up_read(&fs_info->subvol_sem);
9773 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9774 struct dentry *old_dentry, struct inode *new_dir,
9775 struct dentry *new_dentry, unsigned int flags)
9777 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9780 if (flags & RENAME_EXCHANGE)
9781 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9784 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9787 struct btrfs_delalloc_work {
9788 struct inode *inode;
9789 struct completion completion;
9790 struct list_head list;
9791 struct btrfs_work work;
9794 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9796 struct btrfs_delalloc_work *delalloc_work;
9797 struct inode *inode;
9799 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9801 inode = delalloc_work->inode;
9802 filemap_flush(inode->i_mapping);
9803 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9804 &BTRFS_I(inode)->runtime_flags))
9805 filemap_flush(inode->i_mapping);
9808 complete(&delalloc_work->completion);
9811 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9813 struct btrfs_delalloc_work *work;
9815 work = kmalloc(sizeof(*work), GFP_NOFS);
9819 init_completion(&work->completion);
9820 INIT_LIST_HEAD(&work->list);
9821 work->inode = inode;
9822 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9828 * some fairly slow code that needs optimization. This walks the list
9829 * of all the inodes with pending delalloc and forces them to disk.
9831 static int start_delalloc_inodes(struct btrfs_root *root,
9832 struct writeback_control *wbc, bool snapshot,
9833 bool in_reclaim_context)
9835 struct btrfs_inode *binode;
9836 struct inode *inode;
9837 struct btrfs_delalloc_work *work, *next;
9838 struct list_head works;
9839 struct list_head splice;
9841 bool full_flush = wbc->nr_to_write == LONG_MAX;
9843 INIT_LIST_HEAD(&works);
9844 INIT_LIST_HEAD(&splice);
9846 mutex_lock(&root->delalloc_mutex);
9847 spin_lock(&root->delalloc_lock);
9848 list_splice_init(&root->delalloc_inodes, &splice);
9849 while (!list_empty(&splice)) {
9850 binode = list_entry(splice.next, struct btrfs_inode,
9853 list_move_tail(&binode->delalloc_inodes,
9854 &root->delalloc_inodes);
9856 if (in_reclaim_context &&
9857 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9860 inode = igrab(&binode->vfs_inode);
9862 cond_resched_lock(&root->delalloc_lock);
9865 spin_unlock(&root->delalloc_lock);
9868 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9869 &binode->runtime_flags);
9871 work = btrfs_alloc_delalloc_work(inode);
9877 list_add_tail(&work->list, &works);
9878 btrfs_queue_work(root->fs_info->flush_workers,
9881 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9882 btrfs_add_delayed_iput(inode);
9883 if (ret || wbc->nr_to_write <= 0)
9887 spin_lock(&root->delalloc_lock);
9889 spin_unlock(&root->delalloc_lock);
9892 list_for_each_entry_safe(work, next, &works, list) {
9893 list_del_init(&work->list);
9894 wait_for_completion(&work->completion);
9898 if (!list_empty(&splice)) {
9899 spin_lock(&root->delalloc_lock);
9900 list_splice_tail(&splice, &root->delalloc_inodes);
9901 spin_unlock(&root->delalloc_lock);
9903 mutex_unlock(&root->delalloc_mutex);
9907 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9909 struct writeback_control wbc = {
9910 .nr_to_write = LONG_MAX,
9911 .sync_mode = WB_SYNC_NONE,
9913 .range_end = LLONG_MAX,
9915 struct btrfs_fs_info *fs_info = root->fs_info;
9917 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9920 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9923 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9924 bool in_reclaim_context)
9926 struct writeback_control wbc = {
9928 .sync_mode = WB_SYNC_NONE,
9930 .range_end = LLONG_MAX,
9932 struct btrfs_root *root;
9933 struct list_head splice;
9936 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9939 INIT_LIST_HEAD(&splice);
9941 mutex_lock(&fs_info->delalloc_root_mutex);
9942 spin_lock(&fs_info->delalloc_root_lock);
9943 list_splice_init(&fs_info->delalloc_roots, &splice);
9944 while (!list_empty(&splice)) {
9946 * Reset nr_to_write here so we know that we're doing a full
9950 wbc.nr_to_write = LONG_MAX;
9952 root = list_first_entry(&splice, struct btrfs_root,
9954 root = btrfs_grab_root(root);
9956 list_move_tail(&root->delalloc_root,
9957 &fs_info->delalloc_roots);
9958 spin_unlock(&fs_info->delalloc_root_lock);
9960 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9961 btrfs_put_root(root);
9962 if (ret < 0 || wbc.nr_to_write <= 0)
9964 spin_lock(&fs_info->delalloc_root_lock);
9966 spin_unlock(&fs_info->delalloc_root_lock);
9970 if (!list_empty(&splice)) {
9971 spin_lock(&fs_info->delalloc_root_lock);
9972 list_splice_tail(&splice, &fs_info->delalloc_roots);
9973 spin_unlock(&fs_info->delalloc_root_lock);
9975 mutex_unlock(&fs_info->delalloc_root_mutex);
9979 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9980 struct dentry *dentry, const char *symname)
9982 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9983 struct btrfs_trans_handle *trans;
9984 struct btrfs_root *root = BTRFS_I(dir)->root;
9985 struct btrfs_path *path;
9986 struct btrfs_key key;
9987 struct inode *inode = NULL;
9994 struct btrfs_file_extent_item *ei;
9995 struct extent_buffer *leaf;
9997 name_len = strlen(symname);
9998 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9999 return -ENAMETOOLONG;
10002 * 2 items for inode item and ref
10003 * 2 items for dir items
10004 * 1 item for updating parent inode item
10005 * 1 item for the inline extent item
10006 * 1 item for xattr if selinux is on
10008 trans = btrfs_start_transaction(root, 7);
10010 return PTR_ERR(trans);
10012 err = btrfs_get_free_objectid(root, &objectid);
10016 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10017 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10018 objectid, S_IFLNK|S_IRWXUGO, &index);
10019 if (IS_ERR(inode)) {
10020 err = PTR_ERR(inode);
10026 * If the active LSM wants to access the inode during
10027 * d_instantiate it needs these. Smack checks to see
10028 * if the filesystem supports xattrs by looking at the
10031 inode->i_fop = &btrfs_file_operations;
10032 inode->i_op = &btrfs_file_inode_operations;
10033 inode->i_mapping->a_ops = &btrfs_aops;
10035 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10039 path = btrfs_alloc_path();
10044 key.objectid = btrfs_ino(BTRFS_I(inode));
10046 key.type = BTRFS_EXTENT_DATA_KEY;
10047 datasize = btrfs_file_extent_calc_inline_size(name_len);
10048 err = btrfs_insert_empty_item(trans, root, path, &key,
10051 btrfs_free_path(path);
10054 leaf = path->nodes[0];
10055 ei = btrfs_item_ptr(leaf, path->slots[0],
10056 struct btrfs_file_extent_item);
10057 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10058 btrfs_set_file_extent_type(leaf, ei,
10059 BTRFS_FILE_EXTENT_INLINE);
10060 btrfs_set_file_extent_encryption(leaf, ei, 0);
10061 btrfs_set_file_extent_compression(leaf, ei, 0);
10062 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10063 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10065 ptr = btrfs_file_extent_inline_start(ei);
10066 write_extent_buffer(leaf, symname, ptr, name_len);
10067 btrfs_mark_buffer_dirty(leaf);
10068 btrfs_free_path(path);
10070 inode->i_op = &btrfs_symlink_inode_operations;
10071 inode_nohighmem(inode);
10072 inode_set_bytes(inode, name_len);
10073 btrfs_i_size_write(BTRFS_I(inode), name_len);
10074 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
10076 * Last step, add directory indexes for our symlink inode. This is the
10077 * last step to avoid extra cleanup of these indexes if an error happens
10081 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10082 BTRFS_I(inode), 0, index);
10086 d_instantiate_new(dentry, inode);
10089 btrfs_end_transaction(trans);
10090 if (err && inode) {
10091 inode_dec_link_count(inode);
10092 discard_new_inode(inode);
10094 btrfs_btree_balance_dirty(fs_info);
10098 static struct btrfs_trans_handle *insert_prealloc_file_extent(
10099 struct btrfs_trans_handle *trans_in,
10100 struct btrfs_inode *inode,
10101 struct btrfs_key *ins,
10104 struct btrfs_file_extent_item stack_fi;
10105 struct btrfs_replace_extent_info extent_info;
10106 struct btrfs_trans_handle *trans = trans_in;
10107 struct btrfs_path *path;
10108 u64 start = ins->objectid;
10109 u64 len = ins->offset;
10110 int qgroup_released;
10113 memset(&stack_fi, 0, sizeof(stack_fi));
10115 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
10116 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
10117 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
10118 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
10119 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
10120 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
10121 /* Encryption and other encoding is reserved and all 0 */
10123 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
10124 if (qgroup_released < 0)
10125 return ERR_PTR(qgroup_released);
10128 ret = insert_reserved_file_extent(trans, inode,
10129 file_offset, &stack_fi,
10130 true, qgroup_released);
10136 extent_info.disk_offset = start;
10137 extent_info.disk_len = len;
10138 extent_info.data_offset = 0;
10139 extent_info.data_len = len;
10140 extent_info.file_offset = file_offset;
10141 extent_info.extent_buf = (char *)&stack_fi;
10142 extent_info.is_new_extent = true;
10143 extent_info.qgroup_reserved = qgroup_released;
10144 extent_info.insertions = 0;
10146 path = btrfs_alloc_path();
10152 ret = btrfs_replace_file_extents(inode, path, file_offset,
10153 file_offset + len - 1, &extent_info,
10155 btrfs_free_path(path);
10162 * We have released qgroup data range at the beginning of the function,
10163 * and normally qgroup_released bytes will be freed when committing
10165 * But if we error out early, we have to free what we have released
10166 * or we leak qgroup data reservation.
10168 btrfs_qgroup_free_refroot(inode->root->fs_info,
10169 inode->root->root_key.objectid, qgroup_released,
10170 BTRFS_QGROUP_RSV_DATA);
10171 return ERR_PTR(ret);
10174 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10175 u64 start, u64 num_bytes, u64 min_size,
10176 loff_t actual_len, u64 *alloc_hint,
10177 struct btrfs_trans_handle *trans)
10179 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10180 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10181 struct extent_map *em;
10182 struct btrfs_root *root = BTRFS_I(inode)->root;
10183 struct btrfs_key ins;
10184 u64 cur_offset = start;
10185 u64 clear_offset = start;
10188 u64 last_alloc = (u64)-1;
10190 bool own_trans = true;
10191 u64 end = start + num_bytes - 1;
10195 while (num_bytes > 0) {
10196 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10197 cur_bytes = max(cur_bytes, min_size);
10199 * If we are severely fragmented we could end up with really
10200 * small allocations, so if the allocator is returning small
10201 * chunks lets make its job easier by only searching for those
10204 cur_bytes = min(cur_bytes, last_alloc);
10205 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10206 min_size, 0, *alloc_hint, &ins, 1, 0);
10211 * We've reserved this space, and thus converted it from
10212 * ->bytes_may_use to ->bytes_reserved. Any error that happens
10213 * from here on out we will only need to clear our reservation
10214 * for the remaining unreserved area, so advance our
10215 * clear_offset by our extent size.
10217 clear_offset += ins.offset;
10219 last_alloc = ins.offset;
10220 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
10223 * Now that we inserted the prealloc extent we can finally
10224 * decrement the number of reservations in the block group.
10225 * If we did it before, we could race with relocation and have
10226 * relocation miss the reserved extent, making it fail later.
10228 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10229 if (IS_ERR(trans)) {
10230 ret = PTR_ERR(trans);
10231 btrfs_free_reserved_extent(fs_info, ins.objectid,
10236 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10237 cur_offset + ins.offset -1, 0);
10239 em = alloc_extent_map();
10241 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10242 &BTRFS_I(inode)->runtime_flags);
10246 em->start = cur_offset;
10247 em->orig_start = cur_offset;
10248 em->len = ins.offset;
10249 em->block_start = ins.objectid;
10250 em->block_len = ins.offset;
10251 em->orig_block_len = ins.offset;
10252 em->ram_bytes = ins.offset;
10253 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10254 em->generation = trans->transid;
10257 write_lock(&em_tree->lock);
10258 ret = add_extent_mapping(em_tree, em, 1);
10259 write_unlock(&em_tree->lock);
10260 if (ret != -EEXIST)
10262 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10263 cur_offset + ins.offset - 1,
10266 free_extent_map(em);
10268 num_bytes -= ins.offset;
10269 cur_offset += ins.offset;
10270 *alloc_hint = ins.objectid + ins.offset;
10272 inode_inc_iversion(inode);
10273 inode->i_ctime = current_time(inode);
10274 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10275 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10276 (actual_len > inode->i_size) &&
10277 (cur_offset > inode->i_size)) {
10278 if (cur_offset > actual_len)
10279 i_size = actual_len;
10281 i_size = cur_offset;
10282 i_size_write(inode, i_size);
10283 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10286 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10289 btrfs_abort_transaction(trans, ret);
10291 btrfs_end_transaction(trans);
10296 btrfs_end_transaction(trans);
10300 if (clear_offset < end)
10301 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10302 end - clear_offset + 1);
10306 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10307 u64 start, u64 num_bytes, u64 min_size,
10308 loff_t actual_len, u64 *alloc_hint)
10310 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10311 min_size, actual_len, alloc_hint,
10315 int btrfs_prealloc_file_range_trans(struct inode *inode,
10316 struct btrfs_trans_handle *trans, int mode,
10317 u64 start, u64 num_bytes, u64 min_size,
10318 loff_t actual_len, u64 *alloc_hint)
10320 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10321 min_size, actual_len, alloc_hint, trans);
10324 static int btrfs_set_page_dirty(struct page *page)
10326 return __set_page_dirty_nobuffers(page);
10329 static int btrfs_permission(struct user_namespace *mnt_userns,
10330 struct inode *inode, int mask)
10332 struct btrfs_root *root = BTRFS_I(inode)->root;
10333 umode_t mode = inode->i_mode;
10335 if (mask & MAY_WRITE &&
10336 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10337 if (btrfs_root_readonly(root))
10339 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10342 return generic_permission(&init_user_ns, inode, mask);
10345 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10346 struct dentry *dentry, umode_t mode)
10348 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10349 struct btrfs_trans_handle *trans;
10350 struct btrfs_root *root = BTRFS_I(dir)->root;
10351 struct inode *inode = NULL;
10357 * 5 units required for adding orphan entry
10359 trans = btrfs_start_transaction(root, 5);
10361 return PTR_ERR(trans);
10363 ret = btrfs_get_free_objectid(root, &objectid);
10367 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10368 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10369 if (IS_ERR(inode)) {
10370 ret = PTR_ERR(inode);
10375 inode->i_fop = &btrfs_file_operations;
10376 inode->i_op = &btrfs_file_inode_operations;
10378 inode->i_mapping->a_ops = &btrfs_aops;
10380 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10384 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10387 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10392 * We set number of links to 0 in btrfs_new_inode(), and here we set
10393 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10396 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10398 set_nlink(inode, 1);
10399 d_tmpfile(dentry, inode);
10400 unlock_new_inode(inode);
10401 mark_inode_dirty(inode);
10403 btrfs_end_transaction(trans);
10405 discard_new_inode(inode);
10406 btrfs_btree_balance_dirty(fs_info);
10410 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
10412 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10413 unsigned long index = start >> PAGE_SHIFT;
10414 unsigned long end_index = end >> PAGE_SHIFT;
10418 ASSERT(end + 1 - start <= U32_MAX);
10419 len = end + 1 - start;
10420 while (index <= end_index) {
10421 page = find_get_page(inode->vfs_inode.i_mapping, index);
10422 ASSERT(page); /* Pages should be in the extent_io_tree */
10424 btrfs_page_set_writeback(fs_info, page, start, len);
10432 * Add an entry indicating a block group or device which is pinned by a
10433 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10434 * negative errno on failure.
10436 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10437 bool is_block_group)
10439 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10440 struct btrfs_swapfile_pin *sp, *entry;
10441 struct rb_node **p;
10442 struct rb_node *parent = NULL;
10444 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10449 sp->is_block_group = is_block_group;
10450 sp->bg_extent_count = 1;
10452 spin_lock(&fs_info->swapfile_pins_lock);
10453 p = &fs_info->swapfile_pins.rb_node;
10456 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10457 if (sp->ptr < entry->ptr ||
10458 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10459 p = &(*p)->rb_left;
10460 } else if (sp->ptr > entry->ptr ||
10461 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10462 p = &(*p)->rb_right;
10464 if (is_block_group)
10465 entry->bg_extent_count++;
10466 spin_unlock(&fs_info->swapfile_pins_lock);
10471 rb_link_node(&sp->node, parent, p);
10472 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10473 spin_unlock(&fs_info->swapfile_pins_lock);
10477 /* Free all of the entries pinned by this swapfile. */
10478 static void btrfs_free_swapfile_pins(struct inode *inode)
10480 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10481 struct btrfs_swapfile_pin *sp;
10482 struct rb_node *node, *next;
10484 spin_lock(&fs_info->swapfile_pins_lock);
10485 node = rb_first(&fs_info->swapfile_pins);
10487 next = rb_next(node);
10488 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10489 if (sp->inode == inode) {
10490 rb_erase(&sp->node, &fs_info->swapfile_pins);
10491 if (sp->is_block_group) {
10492 btrfs_dec_block_group_swap_extents(sp->ptr,
10493 sp->bg_extent_count);
10494 btrfs_put_block_group(sp->ptr);
10500 spin_unlock(&fs_info->swapfile_pins_lock);
10503 struct btrfs_swap_info {
10509 unsigned long nr_pages;
10513 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10514 struct btrfs_swap_info *bsi)
10516 unsigned long nr_pages;
10517 u64 first_ppage, first_ppage_reported, next_ppage;
10520 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10521 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10522 PAGE_SIZE) >> PAGE_SHIFT;
10524 if (first_ppage >= next_ppage)
10526 nr_pages = next_ppage - first_ppage;
10528 first_ppage_reported = first_ppage;
10529 if (bsi->start == 0)
10530 first_ppage_reported++;
10531 if (bsi->lowest_ppage > first_ppage_reported)
10532 bsi->lowest_ppage = first_ppage_reported;
10533 if (bsi->highest_ppage < (next_ppage - 1))
10534 bsi->highest_ppage = next_ppage - 1;
10536 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10539 bsi->nr_extents += ret;
10540 bsi->nr_pages += nr_pages;
10544 static void btrfs_swap_deactivate(struct file *file)
10546 struct inode *inode = file_inode(file);
10548 btrfs_free_swapfile_pins(inode);
10549 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10552 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10555 struct inode *inode = file_inode(file);
10556 struct btrfs_root *root = BTRFS_I(inode)->root;
10557 struct btrfs_fs_info *fs_info = root->fs_info;
10558 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10559 struct extent_state *cached_state = NULL;
10560 struct extent_map *em = NULL;
10561 struct btrfs_device *device = NULL;
10562 struct btrfs_swap_info bsi = {
10563 .lowest_ppage = (sector_t)-1ULL,
10570 * If the swap file was just created, make sure delalloc is done. If the
10571 * file changes again after this, the user is doing something stupid and
10572 * we don't really care.
10574 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10579 * The inode is locked, so these flags won't change after we check them.
10581 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10582 btrfs_warn(fs_info, "swapfile must not be compressed");
10585 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10586 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10589 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10590 btrfs_warn(fs_info, "swapfile must not be checksummed");
10595 * Balance or device remove/replace/resize can move stuff around from
10596 * under us. The exclop protection makes sure they aren't running/won't
10597 * run concurrently while we are mapping the swap extents, and
10598 * fs_info->swapfile_pins prevents them from running while the swap
10599 * file is active and moving the extents. Note that this also prevents
10600 * a concurrent device add which isn't actually necessary, but it's not
10601 * really worth the trouble to allow it.
10603 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10604 btrfs_warn(fs_info,
10605 "cannot activate swapfile while exclusive operation is running");
10610 * Prevent snapshot creation while we are activating the swap file.
10611 * We do not want to race with snapshot creation. If snapshot creation
10612 * already started before we bumped nr_swapfiles from 0 to 1 and
10613 * completes before the first write into the swap file after it is
10614 * activated, than that write would fallback to COW.
10616 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10617 btrfs_exclop_finish(fs_info);
10618 btrfs_warn(fs_info,
10619 "cannot activate swapfile because snapshot creation is in progress");
10623 * Snapshots can create extents which require COW even if NODATACOW is
10624 * set. We use this counter to prevent snapshots. We must increment it
10625 * before walking the extents because we don't want a concurrent
10626 * snapshot to run after we've already checked the extents.
10628 atomic_inc(&root->nr_swapfiles);
10630 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10632 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10634 while (start < isize) {
10635 u64 logical_block_start, physical_block_start;
10636 struct btrfs_block_group *bg;
10637 u64 len = isize - start;
10639 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10645 if (em->block_start == EXTENT_MAP_HOLE) {
10646 btrfs_warn(fs_info, "swapfile must not have holes");
10650 if (em->block_start == EXTENT_MAP_INLINE) {
10652 * It's unlikely we'll ever actually find ourselves
10653 * here, as a file small enough to fit inline won't be
10654 * big enough to store more than the swap header, but in
10655 * case something changes in the future, let's catch it
10656 * here rather than later.
10658 btrfs_warn(fs_info, "swapfile must not be inline");
10662 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10663 btrfs_warn(fs_info, "swapfile must not be compressed");
10668 logical_block_start = em->block_start + (start - em->start);
10669 len = min(len, em->len - (start - em->start));
10670 free_extent_map(em);
10673 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10679 btrfs_warn(fs_info,
10680 "swapfile must not be copy-on-write");
10685 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10691 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10692 btrfs_warn(fs_info,
10693 "swapfile must have single data profile");
10698 if (device == NULL) {
10699 device = em->map_lookup->stripes[0].dev;
10700 ret = btrfs_add_swapfile_pin(inode, device, false);
10705 } else if (device != em->map_lookup->stripes[0].dev) {
10706 btrfs_warn(fs_info, "swapfile must be on one device");
10711 physical_block_start = (em->map_lookup->stripes[0].physical +
10712 (logical_block_start - em->start));
10713 len = min(len, em->len - (logical_block_start - em->start));
10714 free_extent_map(em);
10717 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10719 btrfs_warn(fs_info,
10720 "could not find block group containing swapfile");
10725 if (!btrfs_inc_block_group_swap_extents(bg)) {
10726 btrfs_warn(fs_info,
10727 "block group for swapfile at %llu is read-only%s",
10729 atomic_read(&fs_info->scrubs_running) ?
10730 " (scrub running)" : "");
10731 btrfs_put_block_group(bg);
10736 ret = btrfs_add_swapfile_pin(inode, bg, true);
10738 btrfs_put_block_group(bg);
10745 if (bsi.block_len &&
10746 bsi.block_start + bsi.block_len == physical_block_start) {
10747 bsi.block_len += len;
10749 if (bsi.block_len) {
10750 ret = btrfs_add_swap_extent(sis, &bsi);
10755 bsi.block_start = physical_block_start;
10756 bsi.block_len = len;
10763 ret = btrfs_add_swap_extent(sis, &bsi);
10766 if (!IS_ERR_OR_NULL(em))
10767 free_extent_map(em);
10769 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10772 btrfs_swap_deactivate(file);
10774 btrfs_drew_write_unlock(&root->snapshot_lock);
10776 btrfs_exclop_finish(fs_info);
10782 sis->bdev = device->bdev;
10783 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10784 sis->max = bsi.nr_pages;
10785 sis->pages = bsi.nr_pages - 1;
10786 sis->highest_bit = bsi.nr_pages - 1;
10787 return bsi.nr_extents;
10790 static void btrfs_swap_deactivate(struct file *file)
10794 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10797 return -EOPNOTSUPP;
10802 * Update the number of bytes used in the VFS' inode. When we replace extents in
10803 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10804 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10805 * always get a correct value.
10807 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10808 const u64 add_bytes,
10809 const u64 del_bytes)
10811 if (add_bytes == del_bytes)
10814 spin_lock(&inode->lock);
10816 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10818 inode_add_bytes(&inode->vfs_inode, add_bytes);
10819 spin_unlock(&inode->lock);
10822 static const struct inode_operations btrfs_dir_inode_operations = {
10823 .getattr = btrfs_getattr,
10824 .lookup = btrfs_lookup,
10825 .create = btrfs_create,
10826 .unlink = btrfs_unlink,
10827 .link = btrfs_link,
10828 .mkdir = btrfs_mkdir,
10829 .rmdir = btrfs_rmdir,
10830 .rename = btrfs_rename2,
10831 .symlink = btrfs_symlink,
10832 .setattr = btrfs_setattr,
10833 .mknod = btrfs_mknod,
10834 .listxattr = btrfs_listxattr,
10835 .permission = btrfs_permission,
10836 .get_acl = btrfs_get_acl,
10837 .set_acl = btrfs_set_acl,
10838 .update_time = btrfs_update_time,
10839 .tmpfile = btrfs_tmpfile,
10840 .fileattr_get = btrfs_fileattr_get,
10841 .fileattr_set = btrfs_fileattr_set,
10844 static const struct file_operations btrfs_dir_file_operations = {
10845 .llseek = generic_file_llseek,
10846 .read = generic_read_dir,
10847 .iterate_shared = btrfs_real_readdir,
10848 .open = btrfs_opendir,
10849 .unlocked_ioctl = btrfs_ioctl,
10850 #ifdef CONFIG_COMPAT
10851 .compat_ioctl = btrfs_compat_ioctl,
10853 .release = btrfs_release_file,
10854 .fsync = btrfs_sync_file,
10858 * btrfs doesn't support the bmap operation because swapfiles
10859 * use bmap to make a mapping of extents in the file. They assume
10860 * these extents won't change over the life of the file and they
10861 * use the bmap result to do IO directly to the drive.
10863 * the btrfs bmap call would return logical addresses that aren't
10864 * suitable for IO and they also will change frequently as COW
10865 * operations happen. So, swapfile + btrfs == corruption.
10867 * For now we're avoiding this by dropping bmap.
10869 static const struct address_space_operations btrfs_aops = {
10870 .readpage = btrfs_readpage,
10871 .writepage = btrfs_writepage,
10872 .writepages = btrfs_writepages,
10873 .readahead = btrfs_readahead,
10874 .direct_IO = noop_direct_IO,
10875 .invalidatepage = btrfs_invalidatepage,
10876 .releasepage = btrfs_releasepage,
10877 #ifdef CONFIG_MIGRATION
10878 .migratepage = btrfs_migratepage,
10880 .set_page_dirty = btrfs_set_page_dirty,
10881 .error_remove_page = generic_error_remove_page,
10882 .swap_activate = btrfs_swap_activate,
10883 .swap_deactivate = btrfs_swap_deactivate,
10886 static const struct inode_operations btrfs_file_inode_operations = {
10887 .getattr = btrfs_getattr,
10888 .setattr = btrfs_setattr,
10889 .listxattr = btrfs_listxattr,
10890 .permission = btrfs_permission,
10891 .fiemap = btrfs_fiemap,
10892 .get_acl = btrfs_get_acl,
10893 .set_acl = btrfs_set_acl,
10894 .update_time = btrfs_update_time,
10895 .fileattr_get = btrfs_fileattr_get,
10896 .fileattr_set = btrfs_fileattr_set,
10898 static const struct inode_operations btrfs_special_inode_operations = {
10899 .getattr = btrfs_getattr,
10900 .setattr = btrfs_setattr,
10901 .permission = btrfs_permission,
10902 .listxattr = btrfs_listxattr,
10903 .get_acl = btrfs_get_acl,
10904 .set_acl = btrfs_set_acl,
10905 .update_time = btrfs_update_time,
10907 static const struct inode_operations btrfs_symlink_inode_operations = {
10908 .get_link = page_get_link,
10909 .getattr = btrfs_getattr,
10910 .setattr = btrfs_setattr,
10911 .permission = btrfs_permission,
10912 .listxattr = btrfs_listxattr,
10913 .update_time = btrfs_update_time,
10916 const struct dentry_operations btrfs_dentry_operations = {
10917 .d_delete = btrfs_dentry_delete,