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/blk-cgroup.h>
10 #include <linux/file.h>
12 #include <linux/pagemap.h>
13 #include <linux/highmem.h>
14 #include <linux/time.h>
15 #include <linux/init.h>
16 #include <linux/string.h>
17 #include <linux/backing-dev.h>
18 #include <linux/writeback.h>
19 #include <linux/compat.h>
20 #include <linux/xattr.h>
21 #include <linux/posix_acl.h>
22 #include <linux/falloc.h>
23 #include <linux/slab.h>
24 #include <linux/ratelimit.h>
25 #include <linux/btrfs.h>
26 #include <linux/blkdev.h>
27 #include <linux/posix_acl_xattr.h>
28 #include <linux/uio.h>
29 #include <linux/magic.h>
30 #include <linux/iversion.h>
31 #include <linux/swap.h>
32 #include <linux/migrate.h>
33 #include <linux/sched/mm.h>
34 #include <linux/iomap.h>
35 #include <asm/unaligned.h>
36 #include <linux/fsverity.h>
40 #include "transaction.h"
41 #include "btrfs_inode.h"
42 #include "print-tree.h"
43 #include "ordered-data.h"
47 #include "compression.h"
49 #include "free-space-cache.h"
52 #include "delalloc-space.h"
53 #include "block-group.h"
54 #include "space-info.h"
57 #include "inode-item.h"
59 struct btrfs_iget_args {
61 struct btrfs_root *root;
64 struct btrfs_dio_data {
66 struct extent_changeset *data_reserved;
69 struct btrfs_rename_ctx {
70 /* Output field. Stores the index number of the old directory entry. */
74 static const struct inode_operations btrfs_dir_inode_operations;
75 static const struct inode_operations btrfs_symlink_inode_operations;
76 static const struct inode_operations btrfs_special_inode_operations;
77 static const struct inode_operations btrfs_file_inode_operations;
78 static const struct address_space_operations btrfs_aops;
79 static const struct file_operations btrfs_dir_file_operations;
81 static struct kmem_cache *btrfs_inode_cachep;
82 struct kmem_cache *btrfs_trans_handle_cachep;
83 struct kmem_cache *btrfs_path_cachep;
84 struct kmem_cache *btrfs_free_space_cachep;
85 struct kmem_cache *btrfs_free_space_bitmap_cachep;
87 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
88 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
89 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
90 static noinline int cow_file_range(struct btrfs_inode *inode,
91 struct page *locked_page,
92 u64 start, u64 end, int *page_started,
93 unsigned long *nr_written, int unlock);
94 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
95 u64 len, u64 orig_start, u64 block_start,
96 u64 block_len, u64 orig_block_len,
97 u64 ram_bytes, int compress_type,
100 static void __endio_write_update_ordered(struct btrfs_inode *inode,
101 const u64 offset, const u64 bytes,
102 const bool uptodate);
105 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
107 * ilock_flags can have the following bit set:
109 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
110 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
112 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
114 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
116 if (ilock_flags & BTRFS_ILOCK_SHARED) {
117 if (ilock_flags & BTRFS_ILOCK_TRY) {
118 if (!inode_trylock_shared(inode))
123 inode_lock_shared(inode);
125 if (ilock_flags & BTRFS_ILOCK_TRY) {
126 if (!inode_trylock(inode))
133 if (ilock_flags & BTRFS_ILOCK_MMAP)
134 down_write(&BTRFS_I(inode)->i_mmap_lock);
139 * btrfs_inode_unlock - unock inode i_rwsem
141 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
142 * to decide whether the lock acquired is shared or exclusive.
144 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
146 if (ilock_flags & BTRFS_ILOCK_MMAP)
147 up_write(&BTRFS_I(inode)->i_mmap_lock);
148 if (ilock_flags & BTRFS_ILOCK_SHARED)
149 inode_unlock_shared(inode);
155 * Cleanup all submitted ordered extents in specified range to handle errors
156 * from the btrfs_run_delalloc_range() callback.
158 * NOTE: caller must ensure that when an error happens, it can not call
159 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
160 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
161 * to be released, which we want to happen only when finishing the ordered
162 * extent (btrfs_finish_ordered_io()).
164 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
165 struct page *locked_page,
166 u64 offset, u64 bytes)
168 unsigned long index = offset >> PAGE_SHIFT;
169 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
170 u64 page_start = page_offset(locked_page);
171 u64 page_end = page_start + PAGE_SIZE - 1;
175 while (index <= end_index) {
177 * For locked page, we will call end_extent_writepage() on it
178 * in run_delalloc_range() for the error handling. That
179 * end_extent_writepage() function will call
180 * btrfs_mark_ordered_io_finished() to clear page Ordered and
181 * run the ordered extent accounting.
183 * Here we can't just clear the Ordered bit, or
184 * btrfs_mark_ordered_io_finished() would skip the accounting
185 * for the page range, and the ordered extent will never finish.
187 if (index == (page_offset(locked_page) >> PAGE_SHIFT)) {
191 page = find_get_page(inode->vfs_inode.i_mapping, index);
197 * Here we just clear all Ordered bits for every page in the
198 * range, then __endio_write_update_ordered() will handle
199 * the ordered extent accounting for the range.
201 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
206 /* The locked page covers the full range, nothing needs to be done */
207 if (bytes + offset <= page_offset(locked_page) + PAGE_SIZE)
210 * In case this page belongs to the delalloc range being instantiated
211 * then skip it, since the first page of a range is going to be
212 * properly cleaned up by the caller of run_delalloc_range
214 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
215 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
216 offset = page_offset(locked_page) + PAGE_SIZE;
219 return __endio_write_update_ordered(inode, offset, bytes, false);
222 static int btrfs_dirty_inode(struct inode *inode);
224 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
225 struct inode *inode, struct inode *dir,
226 const struct qstr *qstr)
230 err = btrfs_init_acl(trans, inode, dir);
232 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
237 * this does all the hard work for inserting an inline extent into
238 * the btree. The caller should have done a btrfs_drop_extents so that
239 * no overlapping inline items exist in the btree
241 static int insert_inline_extent(struct btrfs_trans_handle *trans,
242 struct btrfs_path *path, bool extent_inserted,
243 struct btrfs_root *root, struct inode *inode,
244 u64 start, size_t size, size_t compressed_size,
246 struct page **compressed_pages)
248 struct extent_buffer *leaf;
249 struct page *page = NULL;
252 struct btrfs_file_extent_item *ei;
254 size_t cur_size = size;
255 unsigned long offset;
257 ASSERT((compressed_size > 0 && compressed_pages) ||
258 (compressed_size == 0 && !compressed_pages));
260 if (compressed_size && compressed_pages)
261 cur_size = compressed_size;
263 if (!extent_inserted) {
264 struct btrfs_key key;
267 key.objectid = btrfs_ino(BTRFS_I(inode));
269 key.type = BTRFS_EXTENT_DATA_KEY;
271 datasize = btrfs_file_extent_calc_inline_size(cur_size);
272 ret = btrfs_insert_empty_item(trans, root, path, &key,
277 leaf = path->nodes[0];
278 ei = btrfs_item_ptr(leaf, path->slots[0],
279 struct btrfs_file_extent_item);
280 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
281 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
282 btrfs_set_file_extent_encryption(leaf, ei, 0);
283 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
284 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
285 ptr = btrfs_file_extent_inline_start(ei);
287 if (compress_type != BTRFS_COMPRESS_NONE) {
290 while (compressed_size > 0) {
291 cpage = compressed_pages[i];
292 cur_size = min_t(unsigned long, compressed_size,
295 kaddr = kmap_atomic(cpage);
296 write_extent_buffer(leaf, kaddr, ptr, cur_size);
297 kunmap_atomic(kaddr);
301 compressed_size -= cur_size;
303 btrfs_set_file_extent_compression(leaf, ei,
306 page = find_get_page(inode->i_mapping,
307 start >> PAGE_SHIFT);
308 btrfs_set_file_extent_compression(leaf, ei, 0);
309 kaddr = kmap_atomic(page);
310 offset = offset_in_page(start);
311 write_extent_buffer(leaf, kaddr + offset, ptr, size);
312 kunmap_atomic(kaddr);
315 btrfs_mark_buffer_dirty(leaf);
316 btrfs_release_path(path);
319 * We align size to sectorsize for inline extents just for simplicity
322 size = ALIGN(size, root->fs_info->sectorsize);
323 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
328 * we're an inline extent, so nobody can
329 * extend the file past i_size without locking
330 * a page we already have locked.
332 * We must do any isize and inode updates
333 * before we unlock the pages. Otherwise we
334 * could end up racing with unlink.
336 BTRFS_I(inode)->disk_i_size = inode->i_size;
343 * conditionally insert an inline extent into the file. This
344 * does the checks required to make sure the data is small enough
345 * to fit as an inline extent.
347 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
348 u64 end, size_t compressed_size,
350 struct page **compressed_pages)
352 struct btrfs_drop_extents_args drop_args = { 0 };
353 struct btrfs_root *root = inode->root;
354 struct btrfs_fs_info *fs_info = root->fs_info;
355 struct btrfs_trans_handle *trans;
356 u64 isize = i_size_read(&inode->vfs_inode);
357 u64 actual_end = min(end + 1, isize);
358 u64 inline_len = actual_end - start;
359 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
360 u64 data_len = inline_len;
362 struct btrfs_path *path;
365 data_len = compressed_size;
368 actual_end > fs_info->sectorsize ||
369 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
371 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
373 data_len > fs_info->max_inline) {
377 path = btrfs_alloc_path();
381 trans = btrfs_join_transaction(root);
383 btrfs_free_path(path);
384 return PTR_ERR(trans);
386 trans->block_rsv = &inode->block_rsv;
388 drop_args.path = path;
389 drop_args.start = start;
390 drop_args.end = aligned_end;
391 drop_args.drop_cache = true;
392 drop_args.replace_extent = true;
394 if (compressed_size && compressed_pages)
395 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
398 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
401 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
403 btrfs_abort_transaction(trans, ret);
407 if (isize > actual_end)
408 inline_len = min_t(u64, isize, actual_end);
409 ret = insert_inline_extent(trans, path, drop_args.extent_inserted,
410 root, &inode->vfs_inode, start,
411 inline_len, compressed_size,
412 compress_type, compressed_pages);
413 if (ret && ret != -ENOSPC) {
414 btrfs_abort_transaction(trans, ret);
416 } else if (ret == -ENOSPC) {
421 btrfs_update_inode_bytes(inode, inline_len, drop_args.bytes_found);
422 ret = btrfs_update_inode(trans, root, inode);
423 if (ret && ret != -ENOSPC) {
424 btrfs_abort_transaction(trans, ret);
426 } else if (ret == -ENOSPC) {
431 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
434 * Don't forget to free the reserved space, as for inlined extent
435 * it won't count as data extent, free them directly here.
436 * And at reserve time, it's always aligned to page size, so
437 * just free one page here.
439 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
440 btrfs_free_path(path);
441 btrfs_end_transaction(trans);
445 struct async_extent {
450 unsigned long nr_pages;
452 struct list_head list;
457 struct page *locked_page;
460 unsigned int write_flags;
461 struct list_head extents;
462 struct cgroup_subsys_state *blkcg_css;
463 struct btrfs_work work;
464 struct async_cow *async_cow;
469 struct async_chunk chunks[];
472 static noinline int add_async_extent(struct async_chunk *cow,
473 u64 start, u64 ram_size,
476 unsigned long nr_pages,
479 struct async_extent *async_extent;
481 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
482 BUG_ON(!async_extent); /* -ENOMEM */
483 async_extent->start = start;
484 async_extent->ram_size = ram_size;
485 async_extent->compressed_size = compressed_size;
486 async_extent->pages = pages;
487 async_extent->nr_pages = nr_pages;
488 async_extent->compress_type = compress_type;
489 list_add_tail(&async_extent->list, &cow->extents);
494 * Check if the inode has flags compatible with compression
496 static inline bool inode_can_compress(struct btrfs_inode *inode)
498 if (inode->flags & BTRFS_INODE_NODATACOW ||
499 inode->flags & BTRFS_INODE_NODATASUM)
505 * Check if the inode needs to be submitted to compression, based on mount
506 * options, defragmentation, properties or heuristics.
508 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
511 struct btrfs_fs_info *fs_info = inode->root->fs_info;
513 if (!inode_can_compress(inode)) {
514 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
515 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
520 * Special check for subpage.
522 * We lock the full page then run each delalloc range in the page, thus
523 * for the following case, we will hit some subpage specific corner case:
526 * | |///////| |///////|
529 * In above case, both range A and range B will try to unlock the full
530 * page [0, 64K), causing the one finished later will have page
531 * unlocked already, triggering various page lock requirement BUG_ON()s.
533 * So here we add an artificial limit that subpage compression can only
534 * if the range is fully page aligned.
536 * In theory we only need to ensure the first page is fully covered, but
537 * the tailing partial page will be locked until the full compression
538 * finishes, delaying the write of other range.
540 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
541 * first to prevent any submitted async extent to unlock the full page.
542 * By this, we can ensure for subpage case that only the last async_cow
543 * will unlock the full page.
545 if (fs_info->sectorsize < PAGE_SIZE) {
546 if (!IS_ALIGNED(start, PAGE_SIZE) ||
547 !IS_ALIGNED(end + 1, PAGE_SIZE))
552 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
555 if (inode->defrag_compress)
557 /* bad compression ratios */
558 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
560 if (btrfs_test_opt(fs_info, COMPRESS) ||
561 inode->flags & BTRFS_INODE_COMPRESS ||
562 inode->prop_compress)
563 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
567 static inline void inode_should_defrag(struct btrfs_inode *inode,
568 u64 start, u64 end, u64 num_bytes, u32 small_write)
570 /* If this is a small write inside eof, kick off a defrag */
571 if (num_bytes < small_write &&
572 (start > 0 || end + 1 < inode->disk_i_size))
573 btrfs_add_inode_defrag(NULL, inode, small_write);
577 * we create compressed extents in two phases. The first
578 * phase compresses a range of pages that have already been
579 * locked (both pages and state bits are locked).
581 * This is done inside an ordered work queue, and the compression
582 * is spread across many cpus. The actual IO submission is step
583 * two, and the ordered work queue takes care of making sure that
584 * happens in the same order things were put onto the queue by
585 * writepages and friends.
587 * If this code finds it can't get good compression, it puts an
588 * entry onto the work queue to write the uncompressed bytes. This
589 * makes sure that both compressed inodes and uncompressed inodes
590 * are written in the same order that the flusher thread sent them
593 static noinline int compress_file_range(struct async_chunk *async_chunk)
595 struct inode *inode = async_chunk->inode;
596 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
597 u64 blocksize = fs_info->sectorsize;
598 u64 start = async_chunk->start;
599 u64 end = async_chunk->end;
603 struct page **pages = NULL;
604 unsigned long nr_pages;
605 unsigned long total_compressed = 0;
606 unsigned long total_in = 0;
609 int compress_type = fs_info->compress_type;
610 int compressed_extents = 0;
613 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
617 * We need to save i_size before now because it could change in between
618 * us evaluating the size and assigning it. This is because we lock and
619 * unlock the page in truncate and fallocate, and then modify the i_size
622 * The barriers are to emulate READ_ONCE, remove that once i_size_read
626 i_size = i_size_read(inode);
628 actual_end = min_t(u64, i_size, end + 1);
631 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
632 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
633 nr_pages = min_t(unsigned long, nr_pages,
634 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
637 * we don't want to send crud past the end of i_size through
638 * compression, that's just a waste of CPU time. So, if the
639 * end of the file is before the start of our current
640 * requested range of bytes, we bail out to the uncompressed
641 * cleanup code that can deal with all of this.
643 * It isn't really the fastest way to fix things, but this is a
644 * very uncommon corner.
646 if (actual_end <= start)
647 goto cleanup_and_bail_uncompressed;
649 total_compressed = actual_end - start;
652 * Skip compression for a small file range(<=blocksize) that
653 * isn't an inline extent, since it doesn't save disk space at all.
655 if (total_compressed <= blocksize &&
656 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
657 goto cleanup_and_bail_uncompressed;
660 * For subpage case, we require full page alignment for the sector
662 * Thus we must also check against @actual_end, not just @end.
664 if (blocksize < PAGE_SIZE) {
665 if (!IS_ALIGNED(start, PAGE_SIZE) ||
666 !IS_ALIGNED(round_up(actual_end, blocksize), PAGE_SIZE))
667 goto cleanup_and_bail_uncompressed;
670 total_compressed = min_t(unsigned long, total_compressed,
671 BTRFS_MAX_UNCOMPRESSED);
676 * we do compression for mount -o compress and when the
677 * inode has not been flagged as nocompress. This flag can
678 * change at any time if we discover bad compression ratios.
680 if (inode_need_compress(BTRFS_I(inode), start, end)) {
682 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
684 /* just bail out to the uncompressed code */
689 if (BTRFS_I(inode)->defrag_compress)
690 compress_type = BTRFS_I(inode)->defrag_compress;
691 else if (BTRFS_I(inode)->prop_compress)
692 compress_type = BTRFS_I(inode)->prop_compress;
695 * we need to call clear_page_dirty_for_io on each
696 * page in the range. Otherwise applications with the file
697 * mmap'd can wander in and change the page contents while
698 * we are compressing them.
700 * If the compression fails for any reason, we set the pages
701 * dirty again later on.
703 * Note that the remaining part is redirtied, the start pointer
704 * has moved, the end is the original one.
707 extent_range_clear_dirty_for_io(inode, start, end);
711 /* Compression level is applied here and only here */
712 ret = btrfs_compress_pages(
713 compress_type | (fs_info->compress_level << 4),
714 inode->i_mapping, start,
721 unsigned long offset = offset_in_page(total_compressed);
722 struct page *page = pages[nr_pages - 1];
724 /* zero the tail end of the last page, we might be
725 * sending it down to disk
728 memzero_page(page, offset, PAGE_SIZE - offset);
734 * Check cow_file_range() for why we don't even try to create inline
735 * extent for subpage case.
737 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
738 /* lets try to make an inline extent */
739 if (ret || total_in < actual_end) {
740 /* we didn't compress the entire range, try
741 * to make an uncompressed inline extent.
743 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
744 0, BTRFS_COMPRESS_NONE,
747 /* try making a compressed inline extent */
748 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
750 compress_type, pages);
753 unsigned long clear_flags = EXTENT_DELALLOC |
754 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
755 EXTENT_DO_ACCOUNTING;
756 unsigned long page_error_op;
758 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
761 * inline extent creation worked or returned error,
762 * we don't need to create any more async work items.
763 * Unlock and free up our temp pages.
765 * We use DO_ACCOUNTING here because we need the
766 * delalloc_release_metadata to be done _after_ we drop
767 * our outstanding extent for clearing delalloc for this
770 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
774 PAGE_START_WRITEBACK |
779 * Ensure we only free the compressed pages if we have
780 * them allocated, as we can still reach here with
781 * inode_need_compress() == false.
784 for (i = 0; i < nr_pages; i++) {
785 WARN_ON(pages[i]->mapping);
796 * we aren't doing an inline extent round the compressed size
797 * up to a block size boundary so the allocator does sane
800 total_compressed = ALIGN(total_compressed, blocksize);
803 * one last check to make sure the compression is really a
804 * win, compare the page count read with the blocks on disk,
805 * compression must free at least one sector size
807 total_in = round_up(total_in, fs_info->sectorsize);
808 if (total_compressed + blocksize <= total_in) {
809 compressed_extents++;
812 * The async work queues will take care of doing actual
813 * allocation on disk for these compressed pages, and
814 * will submit them to the elevator.
816 add_async_extent(async_chunk, start, total_in,
817 total_compressed, pages, nr_pages,
820 if (start + total_in < end) {
826 return compressed_extents;
831 * the compression code ran but failed to make things smaller,
832 * free any pages it allocated and our page pointer array
834 for (i = 0; i < nr_pages; i++) {
835 WARN_ON(pages[i]->mapping);
840 total_compressed = 0;
843 /* flag the file so we don't compress in the future */
844 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
845 !(BTRFS_I(inode)->prop_compress)) {
846 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
849 cleanup_and_bail_uncompressed:
851 * No compression, but we still need to write the pages in the file
852 * we've been given so far. redirty the locked page if it corresponds
853 * to our extent and set things up for the async work queue to run
854 * cow_file_range to do the normal delalloc dance.
856 if (async_chunk->locked_page &&
857 (page_offset(async_chunk->locked_page) >= start &&
858 page_offset(async_chunk->locked_page)) <= end) {
859 __set_page_dirty_nobuffers(async_chunk->locked_page);
860 /* unlocked later on in the async handlers */
864 extent_range_redirty_for_io(inode, start, end);
865 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
866 BTRFS_COMPRESS_NONE);
867 compressed_extents++;
869 return compressed_extents;
872 static void free_async_extent_pages(struct async_extent *async_extent)
876 if (!async_extent->pages)
879 for (i = 0; i < async_extent->nr_pages; i++) {
880 WARN_ON(async_extent->pages[i]->mapping);
881 put_page(async_extent->pages[i]);
883 kfree(async_extent->pages);
884 async_extent->nr_pages = 0;
885 async_extent->pages = NULL;
888 static int submit_uncompressed_range(struct btrfs_inode *inode,
889 struct async_extent *async_extent,
890 struct page *locked_page)
892 u64 start = async_extent->start;
893 u64 end = async_extent->start + async_extent->ram_size - 1;
894 unsigned long nr_written = 0;
895 int page_started = 0;
899 * Call cow_file_range() to run the delalloc range directly, since we
900 * won't go to NOCOW or async path again.
902 * Also we call cow_file_range() with @unlock_page == 0, so that we
903 * can directly submit them without interruption.
905 ret = cow_file_range(inode, locked_page, start, end, &page_started,
907 /* Inline extent inserted, page gets unlocked and everything is done */
914 unlock_page(locked_page);
918 ret = extent_write_locked_range(&inode->vfs_inode, start, end);
919 /* All pages will be unlocked, including @locked_page */
925 static int submit_one_async_extent(struct btrfs_inode *inode,
926 struct async_chunk *async_chunk,
927 struct async_extent *async_extent,
930 struct extent_io_tree *io_tree = &inode->io_tree;
931 struct btrfs_root *root = inode->root;
932 struct btrfs_fs_info *fs_info = root->fs_info;
933 struct btrfs_key ins;
934 struct page *locked_page = NULL;
935 struct extent_map *em;
937 u64 start = async_extent->start;
938 u64 end = async_extent->start + async_extent->ram_size - 1;
941 * If async_chunk->locked_page is in the async_extent range, we need to
944 if (async_chunk->locked_page) {
945 u64 locked_page_start = page_offset(async_chunk->locked_page);
946 u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
948 if (!(start >= locked_page_end || end <= locked_page_start))
949 locked_page = async_chunk->locked_page;
951 lock_extent(io_tree, start, end);
953 /* We have fall back to uncompressed write */
954 if (!async_extent->pages)
955 return submit_uncompressed_range(inode, async_extent, locked_page);
957 ret = btrfs_reserve_extent(root, async_extent->ram_size,
958 async_extent->compressed_size,
959 async_extent->compressed_size,
960 0, *alloc_hint, &ins, 1, 1);
962 free_async_extent_pages(async_extent);
964 * Here we used to try again by going back to non-compressed
965 * path for ENOSPC. But we can't reserve space even for
966 * compressed size, how could it work for uncompressed size
967 * which requires larger size? So here we directly go error
973 /* Here we're doing allocation and writeback of the compressed pages */
974 em = create_io_em(inode, start,
975 async_extent->ram_size, /* len */
976 start, /* orig_start */
977 ins.objectid, /* block_start */
978 ins.offset, /* block_len */
979 ins.offset, /* orig_block_len */
980 async_extent->ram_size, /* ram_bytes */
981 async_extent->compress_type,
982 BTRFS_ORDERED_COMPRESSED);
985 goto out_free_reserve;
989 ret = btrfs_add_ordered_extent_compress(inode, start, /* file_offset */
990 ins.objectid, /* disk_bytenr */
991 async_extent->ram_size, /* num_bytes */
992 ins.offset, /* disk_num_bytes */
993 async_extent->compress_type);
995 btrfs_drop_extent_cache(inode, start, end, 0);
996 goto out_free_reserve;
998 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1000 /* Clear dirty, set writeback and unlock the pages. */
1001 extent_clear_unlock_delalloc(inode, start, end,
1002 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
1003 PAGE_UNLOCK | PAGE_START_WRITEBACK);
1004 if (btrfs_submit_compressed_write(inode, start, /* file_offset */
1005 async_extent->ram_size, /* num_bytes */
1006 ins.objectid, /* disk_bytenr */
1007 ins.offset, /* compressed_len */
1008 async_extent->pages, /* compressed_pages */
1009 async_extent->nr_pages,
1010 async_chunk->write_flags,
1011 async_chunk->blkcg_css)) {
1012 const u64 start = async_extent->start;
1013 const u64 end = start + async_extent->ram_size - 1;
1015 btrfs_writepage_endio_finish_ordered(inode, NULL, start, end, 0);
1017 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
1018 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1019 free_async_extent_pages(async_extent);
1021 *alloc_hint = ins.objectid + ins.offset;
1022 kfree(async_extent);
1026 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1027 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1029 extent_clear_unlock_delalloc(inode, start, end,
1030 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1031 EXTENT_DELALLOC_NEW |
1032 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1033 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1034 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1035 free_async_extent_pages(async_extent);
1036 kfree(async_extent);
1041 * Phase two of compressed writeback. This is the ordered portion of the code,
1042 * which only gets called in the order the work was queued. We walk all the
1043 * async extents created by compress_file_range and send them down to the disk.
1045 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
1047 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
1048 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1049 struct async_extent *async_extent;
1053 while (!list_empty(&async_chunk->extents)) {
1057 async_extent = list_entry(async_chunk->extents.next,
1058 struct async_extent, list);
1059 list_del(&async_extent->list);
1060 extent_start = async_extent->start;
1061 ram_size = async_extent->ram_size;
1063 ret = submit_one_async_extent(inode, async_chunk, async_extent,
1065 btrfs_debug(fs_info,
1066 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1067 inode->root->root_key.objectid,
1068 btrfs_ino(inode), extent_start, ram_size, ret);
1072 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1075 struct extent_map_tree *em_tree = &inode->extent_tree;
1076 struct extent_map *em;
1079 read_lock(&em_tree->lock);
1080 em = search_extent_mapping(em_tree, start, num_bytes);
1083 * if block start isn't an actual block number then find the
1084 * first block in this inode and use that as a hint. If that
1085 * block is also bogus then just don't worry about it.
1087 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1088 free_extent_map(em);
1089 em = search_extent_mapping(em_tree, 0, 0);
1090 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1091 alloc_hint = em->block_start;
1093 free_extent_map(em);
1095 alloc_hint = em->block_start;
1096 free_extent_map(em);
1099 read_unlock(&em_tree->lock);
1105 * when extent_io.c finds a delayed allocation range in the file,
1106 * the call backs end up in this code. The basic idea is to
1107 * allocate extents on disk for the range, and create ordered data structs
1108 * in ram to track those extents.
1110 * locked_page is the page that writepage had locked already. We use
1111 * it to make sure we don't do extra locks or unlocks.
1113 * *page_started is set to one if we unlock locked_page and do everything
1114 * required to start IO on it. It may be clean and already done with
1115 * IO when we return.
1117 static noinline int cow_file_range(struct btrfs_inode *inode,
1118 struct page *locked_page,
1119 u64 start, u64 end, int *page_started,
1120 unsigned long *nr_written, int unlock)
1122 struct btrfs_root *root = inode->root;
1123 struct btrfs_fs_info *fs_info = root->fs_info;
1126 unsigned long ram_size;
1127 u64 cur_alloc_size = 0;
1129 u64 blocksize = fs_info->sectorsize;
1130 struct btrfs_key ins;
1131 struct extent_map *em;
1132 unsigned clear_bits;
1133 unsigned long page_ops;
1134 bool extent_reserved = false;
1137 if (btrfs_is_free_space_inode(inode)) {
1143 num_bytes = ALIGN(end - start + 1, blocksize);
1144 num_bytes = max(blocksize, num_bytes);
1145 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1147 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1150 * Due to the page size limit, for subpage we can only trigger the
1151 * writeback for the dirty sectors of page, that means data writeback
1152 * is doing more writeback than what we want.
1154 * This is especially unexpected for some call sites like fallocate,
1155 * where we only increase i_size after everything is done.
1156 * This means we can trigger inline extent even if we didn't want to.
1157 * So here we skip inline extent creation completely.
1159 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
1160 /* lets try to make an inline extent */
1161 ret = cow_file_range_inline(inode, start, end, 0,
1162 BTRFS_COMPRESS_NONE, NULL);
1165 * We use DO_ACCOUNTING here because we need the
1166 * delalloc_release_metadata to be run _after_ we drop
1167 * our outstanding extent for clearing delalloc for this
1170 extent_clear_unlock_delalloc(inode, start, end,
1172 EXTENT_LOCKED | EXTENT_DELALLOC |
1173 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1174 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1175 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1176 *nr_written = *nr_written +
1177 (end - start + PAGE_SIZE) / PAGE_SIZE;
1180 * locked_page is locked by the caller of
1181 * writepage_delalloc(), not locked by
1182 * __process_pages_contig().
1184 * We can't let __process_pages_contig() to unlock it,
1185 * as it doesn't have any subpage::writers recorded.
1187 * Here we manually unlock the page, since the caller
1188 * can't use page_started to determine if it's an
1189 * inline extent or a compressed extent.
1191 unlock_page(locked_page);
1193 } else if (ret < 0) {
1198 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1199 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1202 * Relocation relies on the relocated extents to have exactly the same
1203 * size as the original extents. Normally writeback for relocation data
1204 * extents follows a NOCOW path because relocation preallocates the
1205 * extents. However, due to an operation such as scrub turning a block
1206 * group to RO mode, it may fallback to COW mode, so we must make sure
1207 * an extent allocated during COW has exactly the requested size and can
1208 * not be split into smaller extents, otherwise relocation breaks and
1209 * fails during the stage where it updates the bytenr of file extent
1212 if (btrfs_is_data_reloc_root(root))
1213 min_alloc_size = num_bytes;
1215 min_alloc_size = fs_info->sectorsize;
1217 while (num_bytes > 0) {
1218 cur_alloc_size = num_bytes;
1219 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1220 min_alloc_size, 0, alloc_hint,
1224 cur_alloc_size = ins.offset;
1225 extent_reserved = true;
1227 ram_size = ins.offset;
1228 em = create_io_em(inode, start, ins.offset, /* len */
1229 start, /* orig_start */
1230 ins.objectid, /* block_start */
1231 ins.offset, /* block_len */
1232 ins.offset, /* orig_block_len */
1233 ram_size, /* ram_bytes */
1234 BTRFS_COMPRESS_NONE, /* compress_type */
1235 BTRFS_ORDERED_REGULAR /* type */);
1240 free_extent_map(em);
1242 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1243 ram_size, cur_alloc_size,
1244 BTRFS_ORDERED_REGULAR);
1246 goto out_drop_extent_cache;
1248 if (btrfs_is_data_reloc_root(root)) {
1249 ret = btrfs_reloc_clone_csums(inode, start,
1252 * Only drop cache here, and process as normal.
1254 * We must not allow extent_clear_unlock_delalloc()
1255 * at out_unlock label to free meta of this ordered
1256 * extent, as its meta should be freed by
1257 * btrfs_finish_ordered_io().
1259 * So we must continue until @start is increased to
1260 * skip current ordered extent.
1263 btrfs_drop_extent_cache(inode, start,
1264 start + ram_size - 1, 0);
1267 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1270 * We're not doing compressed IO, don't unlock the first page
1271 * (which the caller expects to stay locked), don't clear any
1272 * dirty bits and don't set any writeback bits
1274 * Do set the Ordered (Private2) bit so we know this page was
1275 * properly setup for writepage.
1277 page_ops = unlock ? PAGE_UNLOCK : 0;
1278 page_ops |= PAGE_SET_ORDERED;
1280 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1282 EXTENT_LOCKED | EXTENT_DELALLOC,
1284 if (num_bytes < cur_alloc_size)
1287 num_bytes -= cur_alloc_size;
1288 alloc_hint = ins.objectid + ins.offset;
1289 start += cur_alloc_size;
1290 extent_reserved = false;
1293 * btrfs_reloc_clone_csums() error, since start is increased
1294 * extent_clear_unlock_delalloc() at out_unlock label won't
1295 * free metadata of current ordered extent, we're OK to exit.
1303 out_drop_extent_cache:
1304 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1306 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1307 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1309 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1310 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1311 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1313 * If we reserved an extent for our delalloc range (or a subrange) and
1314 * failed to create the respective ordered extent, then it means that
1315 * when we reserved the extent we decremented the extent's size from
1316 * the data space_info's bytes_may_use counter and incremented the
1317 * space_info's bytes_reserved counter by the same amount. We must make
1318 * sure extent_clear_unlock_delalloc() does not try to decrement again
1319 * the data space_info's bytes_may_use counter, therefore we do not pass
1320 * it the flag EXTENT_CLEAR_DATA_RESV.
1322 if (extent_reserved) {
1323 extent_clear_unlock_delalloc(inode, start,
1324 start + cur_alloc_size - 1,
1328 start += cur_alloc_size;
1332 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1333 clear_bits | EXTENT_CLEAR_DATA_RESV,
1339 * work queue call back to started compression on a file and pages
1341 static noinline void async_cow_start(struct btrfs_work *work)
1343 struct async_chunk *async_chunk;
1344 int compressed_extents;
1346 async_chunk = container_of(work, struct async_chunk, work);
1348 compressed_extents = compress_file_range(async_chunk);
1349 if (compressed_extents == 0) {
1350 btrfs_add_delayed_iput(async_chunk->inode);
1351 async_chunk->inode = NULL;
1356 * work queue call back to submit previously compressed pages
1358 static noinline void async_cow_submit(struct btrfs_work *work)
1360 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1362 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1363 unsigned long nr_pages;
1365 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1369 * ->inode could be NULL if async_chunk_start has failed to compress,
1370 * in which case we don't have anything to submit, yet we need to
1371 * always adjust ->async_delalloc_pages as its paired with the init
1372 * happening in cow_file_range_async
1374 if (async_chunk->inode)
1375 submit_compressed_extents(async_chunk);
1377 /* atomic_sub_return implies a barrier */
1378 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1380 cond_wake_up_nomb(&fs_info->async_submit_wait);
1383 static noinline void async_cow_free(struct btrfs_work *work)
1385 struct async_chunk *async_chunk;
1386 struct async_cow *async_cow;
1388 async_chunk = container_of(work, struct async_chunk, work);
1389 if (async_chunk->inode)
1390 btrfs_add_delayed_iput(async_chunk->inode);
1391 if (async_chunk->blkcg_css)
1392 css_put(async_chunk->blkcg_css);
1394 async_cow = async_chunk->async_cow;
1395 if (atomic_dec_and_test(&async_cow->num_chunks))
1399 static int cow_file_range_async(struct btrfs_inode *inode,
1400 struct writeback_control *wbc,
1401 struct page *locked_page,
1402 u64 start, u64 end, int *page_started,
1403 unsigned long *nr_written)
1405 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1406 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1407 struct async_cow *ctx;
1408 struct async_chunk *async_chunk;
1409 unsigned long nr_pages;
1411 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1413 bool should_compress;
1415 const unsigned int write_flags = wbc_to_write_flags(wbc);
1417 unlock_extent(&inode->io_tree, start, end);
1419 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1420 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1422 should_compress = false;
1424 should_compress = true;
1427 nofs_flag = memalloc_nofs_save();
1428 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1429 memalloc_nofs_restore(nofs_flag);
1432 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1433 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1434 EXTENT_DO_ACCOUNTING;
1435 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1436 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1438 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1439 clear_bits, page_ops);
1443 async_chunk = ctx->chunks;
1444 atomic_set(&ctx->num_chunks, num_chunks);
1446 for (i = 0; i < num_chunks; i++) {
1447 if (should_compress)
1448 cur_end = min(end, start + SZ_512K - 1);
1453 * igrab is called higher up in the call chain, take only the
1454 * lightweight reference for the callback lifetime
1456 ihold(&inode->vfs_inode);
1457 async_chunk[i].async_cow = ctx;
1458 async_chunk[i].inode = &inode->vfs_inode;
1459 async_chunk[i].start = start;
1460 async_chunk[i].end = cur_end;
1461 async_chunk[i].write_flags = write_flags;
1462 INIT_LIST_HEAD(&async_chunk[i].extents);
1465 * The locked_page comes all the way from writepage and its
1466 * the original page we were actually given. As we spread
1467 * this large delalloc region across multiple async_chunk
1468 * structs, only the first struct needs a pointer to locked_page
1470 * This way we don't need racey decisions about who is supposed
1475 * Depending on the compressibility, the pages might or
1476 * might not go through async. We want all of them to
1477 * be accounted against wbc once. Let's do it here
1478 * before the paths diverge. wbc accounting is used
1479 * only for foreign writeback detection and doesn't
1480 * need full accuracy. Just account the whole thing
1481 * against the first page.
1483 wbc_account_cgroup_owner(wbc, locked_page,
1485 async_chunk[i].locked_page = locked_page;
1488 async_chunk[i].locked_page = NULL;
1491 if (blkcg_css != blkcg_root_css) {
1493 async_chunk[i].blkcg_css = blkcg_css;
1495 async_chunk[i].blkcg_css = NULL;
1498 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1499 async_cow_submit, async_cow_free);
1501 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1502 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1504 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1506 *nr_written += nr_pages;
1507 start = cur_end + 1;
1513 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1514 struct page *locked_page, u64 start,
1515 u64 end, int *page_started,
1516 unsigned long *nr_written)
1520 ret = cow_file_range(inode, locked_page, start, end, page_started,
1528 __set_page_dirty_nobuffers(locked_page);
1529 account_page_redirty(locked_page);
1530 extent_write_locked_range(&inode->vfs_inode, start, end);
1536 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1537 u64 bytenr, u64 num_bytes)
1539 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
1540 struct btrfs_ordered_sum *sums;
1544 ret = btrfs_lookup_csums_range(csum_root, bytenr,
1545 bytenr + num_bytes - 1, &list, 0);
1546 if (ret == 0 && list_empty(&list))
1549 while (!list_empty(&list)) {
1550 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1551 list_del(&sums->list);
1559 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1560 const u64 start, const u64 end,
1561 int *page_started, unsigned long *nr_written)
1563 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1564 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1565 const u64 range_bytes = end + 1 - start;
1566 struct extent_io_tree *io_tree = &inode->io_tree;
1567 u64 range_start = start;
1571 * If EXTENT_NORESERVE is set it means that when the buffered write was
1572 * made we had not enough available data space and therefore we did not
1573 * reserve data space for it, since we though we could do NOCOW for the
1574 * respective file range (either there is prealloc extent or the inode
1575 * has the NOCOW bit set).
1577 * However when we need to fallback to COW mode (because for example the
1578 * block group for the corresponding extent was turned to RO mode by a
1579 * scrub or relocation) we need to do the following:
1581 * 1) We increment the bytes_may_use counter of the data space info.
1582 * If COW succeeds, it allocates a new data extent and after doing
1583 * that it decrements the space info's bytes_may_use counter and
1584 * increments its bytes_reserved counter by the same amount (we do
1585 * this at btrfs_add_reserved_bytes()). So we need to increment the
1586 * bytes_may_use counter to compensate (when space is reserved at
1587 * buffered write time, the bytes_may_use counter is incremented);
1589 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1590 * that if the COW path fails for any reason, it decrements (through
1591 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1592 * data space info, which we incremented in the step above.
1594 * If we need to fallback to cow and the inode corresponds to a free
1595 * space cache inode or an inode of the data relocation tree, we must
1596 * also increment bytes_may_use of the data space_info for the same
1597 * reason. Space caches and relocated data extents always get a prealloc
1598 * extent for them, however scrub or balance may have set the block
1599 * group that contains that extent to RO mode and therefore force COW
1600 * when starting writeback.
1602 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1603 EXTENT_NORESERVE, 0);
1604 if (count > 0 || is_space_ino || is_reloc_ino) {
1606 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1607 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1609 if (is_space_ino || is_reloc_ino)
1610 bytes = range_bytes;
1612 spin_lock(&sinfo->lock);
1613 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1614 spin_unlock(&sinfo->lock);
1617 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1621 return cow_file_range(inode, locked_page, start, end, page_started,
1626 * when nowcow writeback call back. This checks for snapshots or COW copies
1627 * of the extents that exist in the file, and COWs the file as required.
1629 * If no cow copies or snapshots exist, we write directly to the existing
1632 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1633 struct page *locked_page,
1634 const u64 start, const u64 end,
1636 unsigned long *nr_written)
1638 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1639 struct btrfs_root *root = inode->root;
1640 struct btrfs_path *path;
1641 u64 cow_start = (u64)-1;
1642 u64 cur_offset = start;
1644 bool check_prev = true;
1645 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1646 u64 ino = btrfs_ino(inode);
1648 u64 disk_bytenr = 0;
1649 const bool force = inode->flags & BTRFS_INODE_NODATACOW;
1651 path = btrfs_alloc_path();
1653 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1654 EXTENT_LOCKED | EXTENT_DELALLOC |
1655 EXTENT_DO_ACCOUNTING |
1656 EXTENT_DEFRAG, PAGE_UNLOCK |
1657 PAGE_START_WRITEBACK |
1658 PAGE_END_WRITEBACK);
1663 struct btrfs_key found_key;
1664 struct btrfs_file_extent_item *fi;
1665 struct extent_buffer *leaf;
1675 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1681 * If there is no extent for our range when doing the initial
1682 * search, then go back to the previous slot as it will be the
1683 * one containing the search offset
1685 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1686 leaf = path->nodes[0];
1687 btrfs_item_key_to_cpu(leaf, &found_key,
1688 path->slots[0] - 1);
1689 if (found_key.objectid == ino &&
1690 found_key.type == BTRFS_EXTENT_DATA_KEY)
1695 /* Go to next leaf if we have exhausted the current one */
1696 leaf = path->nodes[0];
1697 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1698 ret = btrfs_next_leaf(root, path);
1700 if (cow_start != (u64)-1)
1701 cur_offset = cow_start;
1706 leaf = path->nodes[0];
1709 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1711 /* Didn't find anything for our INO */
1712 if (found_key.objectid > ino)
1715 * Keep searching until we find an EXTENT_ITEM or there are no
1716 * more extents for this inode
1718 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1719 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1724 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1725 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1726 found_key.offset > end)
1730 * If the found extent starts after requested offset, then
1731 * adjust extent_end to be right before this extent begins
1733 if (found_key.offset > cur_offset) {
1734 extent_end = found_key.offset;
1740 * Found extent which begins before our range and potentially
1743 fi = btrfs_item_ptr(leaf, path->slots[0],
1744 struct btrfs_file_extent_item);
1745 extent_type = btrfs_file_extent_type(leaf, fi);
1747 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1748 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1749 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1750 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1751 extent_offset = btrfs_file_extent_offset(leaf, fi);
1752 extent_end = found_key.offset +
1753 btrfs_file_extent_num_bytes(leaf, fi);
1755 btrfs_file_extent_disk_num_bytes(leaf, fi);
1757 * If the extent we got ends before our current offset,
1758 * skip to the next extent.
1760 if (extent_end <= cur_offset) {
1765 if (disk_bytenr == 0)
1767 /* Skip compressed/encrypted/encoded extents */
1768 if (btrfs_file_extent_compression(leaf, fi) ||
1769 btrfs_file_extent_encryption(leaf, fi) ||
1770 btrfs_file_extent_other_encoding(leaf, fi))
1773 * If extent is created before the last volume's snapshot
1774 * this implies the extent is shared, hence we can't do
1775 * nocow. This is the same check as in
1776 * btrfs_cross_ref_exist but without calling
1777 * btrfs_search_slot.
1779 if (!freespace_inode &&
1780 btrfs_file_extent_generation(leaf, fi) <=
1781 btrfs_root_last_snapshot(&root->root_item))
1783 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1787 * The following checks can be expensive, as they need to
1788 * take other locks and do btree or rbtree searches, so
1789 * release the path to avoid blocking other tasks for too
1792 btrfs_release_path(path);
1794 ret = btrfs_cross_ref_exist(root, ino,
1796 extent_offset, disk_bytenr, false);
1799 * ret could be -EIO if the above fails to read
1803 if (cow_start != (u64)-1)
1804 cur_offset = cow_start;
1808 WARN_ON_ONCE(freespace_inode);
1811 disk_bytenr += extent_offset;
1812 disk_bytenr += cur_offset - found_key.offset;
1813 num_bytes = min(end + 1, extent_end) - cur_offset;
1815 * If there are pending snapshots for this root, we
1816 * fall into common COW way
1818 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1821 * force cow if csum exists in the range.
1822 * this ensure that csum for a given extent are
1823 * either valid or do not exist.
1825 ret = csum_exist_in_range(fs_info, disk_bytenr,
1829 * ret could be -EIO if the above fails to read
1833 if (cow_start != (u64)-1)
1834 cur_offset = cow_start;
1837 WARN_ON_ONCE(freespace_inode);
1840 /* If the extent's block group is RO, we must COW */
1841 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1844 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1845 extent_end = found_key.offset + ram_bytes;
1846 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1847 /* Skip extents outside of our requested range */
1848 if (extent_end <= start) {
1853 /* If this triggers then we have a memory corruption */
1858 * If nocow is false then record the beginning of the range
1859 * that needs to be COWed
1862 if (cow_start == (u64)-1)
1863 cow_start = cur_offset;
1864 cur_offset = extent_end;
1865 if (cur_offset > end)
1867 if (!path->nodes[0])
1874 * COW range from cow_start to found_key.offset - 1. As the key
1875 * will contain the beginning of the first extent that can be
1876 * NOCOW, following one which needs to be COW'ed
1878 if (cow_start != (u64)-1) {
1879 ret = fallback_to_cow(inode, locked_page,
1880 cow_start, found_key.offset - 1,
1881 page_started, nr_written);
1884 cow_start = (u64)-1;
1887 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1888 u64 orig_start = found_key.offset - extent_offset;
1889 struct extent_map *em;
1891 em = create_io_em(inode, cur_offset, num_bytes,
1893 disk_bytenr, /* block_start */
1894 num_bytes, /* block_len */
1895 disk_num_bytes, /* orig_block_len */
1896 ram_bytes, BTRFS_COMPRESS_NONE,
1897 BTRFS_ORDERED_PREALLOC);
1902 free_extent_map(em);
1903 ret = btrfs_add_ordered_extent(inode, cur_offset,
1904 disk_bytenr, num_bytes,
1906 BTRFS_ORDERED_PREALLOC);
1908 btrfs_drop_extent_cache(inode, cur_offset,
1909 cur_offset + num_bytes - 1,
1914 ret = btrfs_add_ordered_extent(inode, cur_offset,
1915 disk_bytenr, num_bytes,
1917 BTRFS_ORDERED_NOCOW);
1923 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1926 if (btrfs_is_data_reloc_root(root))
1928 * Error handled later, as we must prevent
1929 * extent_clear_unlock_delalloc() in error handler
1930 * from freeing metadata of created ordered extent.
1932 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1935 extent_clear_unlock_delalloc(inode, cur_offset,
1936 cur_offset + num_bytes - 1,
1937 locked_page, EXTENT_LOCKED |
1939 EXTENT_CLEAR_DATA_RESV,
1940 PAGE_UNLOCK | PAGE_SET_ORDERED);
1942 cur_offset = extent_end;
1945 * btrfs_reloc_clone_csums() error, now we're OK to call error
1946 * handler, as metadata for created ordered extent will only
1947 * be freed by btrfs_finish_ordered_io().
1951 if (cur_offset > end)
1954 btrfs_release_path(path);
1956 if (cur_offset <= end && cow_start == (u64)-1)
1957 cow_start = cur_offset;
1959 if (cow_start != (u64)-1) {
1961 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1962 page_started, nr_written);
1969 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1971 if (ret && cur_offset < end)
1972 extent_clear_unlock_delalloc(inode, cur_offset, end,
1973 locked_page, EXTENT_LOCKED |
1974 EXTENT_DELALLOC | EXTENT_DEFRAG |
1975 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1976 PAGE_START_WRITEBACK |
1977 PAGE_END_WRITEBACK);
1978 btrfs_free_path(path);
1982 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
1984 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
1985 if (inode->defrag_bytes &&
1986 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
1995 * Function to process delayed allocation (create CoW) for ranges which are
1996 * being touched for the first time.
1998 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1999 u64 start, u64 end, int *page_started, unsigned long *nr_written,
2000 struct writeback_control *wbc)
2003 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2006 * The range must cover part of the @locked_page, or the returned
2007 * @page_started can confuse the caller.
2009 ASSERT(!(end <= page_offset(locked_page) ||
2010 start >= page_offset(locked_page) + PAGE_SIZE));
2012 if (should_nocow(inode, start, end)) {
2014 * Normally on a zoned device we're only doing COW writes, but
2015 * in case of relocation on a zoned filesystem we have taken
2016 * precaution, that we're only writing sequentially. It's safe
2017 * to use run_delalloc_nocow() here, like for regular
2018 * preallocated inodes.
2021 (zoned && btrfs_is_data_reloc_root(inode->root)));
2022 ret = run_delalloc_nocow(inode, locked_page, start, end,
2023 page_started, nr_written);
2024 } else if (!inode_can_compress(inode) ||
2025 !inode_need_compress(inode, start, end)) {
2027 ret = run_delalloc_zoned(inode, locked_page, start, end,
2028 page_started, nr_written);
2030 ret = cow_file_range(inode, locked_page, start, end,
2031 page_started, nr_written, 1);
2033 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
2034 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
2035 page_started, nr_written);
2039 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2044 void btrfs_split_delalloc_extent(struct inode *inode,
2045 struct extent_state *orig, u64 split)
2049 /* not delalloc, ignore it */
2050 if (!(orig->state & EXTENT_DELALLOC))
2053 size = orig->end - orig->start + 1;
2054 if (size > BTRFS_MAX_EXTENT_SIZE) {
2059 * See the explanation in btrfs_merge_delalloc_extent, the same
2060 * applies here, just in reverse.
2062 new_size = orig->end - split + 1;
2063 num_extents = count_max_extents(new_size);
2064 new_size = split - orig->start;
2065 num_extents += count_max_extents(new_size);
2066 if (count_max_extents(size) >= num_extents)
2070 spin_lock(&BTRFS_I(inode)->lock);
2071 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
2072 spin_unlock(&BTRFS_I(inode)->lock);
2076 * Handle merged delayed allocation extents so we can keep track of new extents
2077 * that are just merged onto old extents, such as when we are doing sequential
2078 * writes, so we can properly account for the metadata space we'll need.
2080 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
2081 struct extent_state *other)
2083 u64 new_size, old_size;
2086 /* not delalloc, ignore it */
2087 if (!(other->state & EXTENT_DELALLOC))
2090 if (new->start > other->start)
2091 new_size = new->end - other->start + 1;
2093 new_size = other->end - new->start + 1;
2095 /* we're not bigger than the max, unreserve the space and go */
2096 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
2097 spin_lock(&BTRFS_I(inode)->lock);
2098 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2099 spin_unlock(&BTRFS_I(inode)->lock);
2104 * We have to add up either side to figure out how many extents were
2105 * accounted for before we merged into one big extent. If the number of
2106 * extents we accounted for is <= the amount we need for the new range
2107 * then we can return, otherwise drop. Think of it like this
2111 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2112 * need 2 outstanding extents, on one side we have 1 and the other side
2113 * we have 1 so they are == and we can return. But in this case
2115 * [MAX_SIZE+4k][MAX_SIZE+4k]
2117 * Each range on their own accounts for 2 extents, but merged together
2118 * they are only 3 extents worth of accounting, so we need to drop in
2121 old_size = other->end - other->start + 1;
2122 num_extents = count_max_extents(old_size);
2123 old_size = new->end - new->start + 1;
2124 num_extents += count_max_extents(old_size);
2125 if (count_max_extents(new_size) >= num_extents)
2128 spin_lock(&BTRFS_I(inode)->lock);
2129 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2130 spin_unlock(&BTRFS_I(inode)->lock);
2133 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2134 struct inode *inode)
2136 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2138 spin_lock(&root->delalloc_lock);
2139 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2140 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2141 &root->delalloc_inodes);
2142 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2143 &BTRFS_I(inode)->runtime_flags);
2144 root->nr_delalloc_inodes++;
2145 if (root->nr_delalloc_inodes == 1) {
2146 spin_lock(&fs_info->delalloc_root_lock);
2147 BUG_ON(!list_empty(&root->delalloc_root));
2148 list_add_tail(&root->delalloc_root,
2149 &fs_info->delalloc_roots);
2150 spin_unlock(&fs_info->delalloc_root_lock);
2153 spin_unlock(&root->delalloc_lock);
2157 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2158 struct btrfs_inode *inode)
2160 struct btrfs_fs_info *fs_info = root->fs_info;
2162 if (!list_empty(&inode->delalloc_inodes)) {
2163 list_del_init(&inode->delalloc_inodes);
2164 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2165 &inode->runtime_flags);
2166 root->nr_delalloc_inodes--;
2167 if (!root->nr_delalloc_inodes) {
2168 ASSERT(list_empty(&root->delalloc_inodes));
2169 spin_lock(&fs_info->delalloc_root_lock);
2170 BUG_ON(list_empty(&root->delalloc_root));
2171 list_del_init(&root->delalloc_root);
2172 spin_unlock(&fs_info->delalloc_root_lock);
2177 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2178 struct btrfs_inode *inode)
2180 spin_lock(&root->delalloc_lock);
2181 __btrfs_del_delalloc_inode(root, inode);
2182 spin_unlock(&root->delalloc_lock);
2186 * Properly track delayed allocation bytes in the inode and to maintain the
2187 * list of inodes that have pending delalloc work to be done.
2189 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2192 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2194 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2197 * set_bit and clear bit hooks normally require _irqsave/restore
2198 * but in this case, we are only testing for the DELALLOC
2199 * bit, which is only set or cleared with irqs on
2201 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2202 struct btrfs_root *root = BTRFS_I(inode)->root;
2203 u64 len = state->end + 1 - state->start;
2204 u32 num_extents = count_max_extents(len);
2205 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2207 spin_lock(&BTRFS_I(inode)->lock);
2208 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2209 spin_unlock(&BTRFS_I(inode)->lock);
2211 /* For sanity tests */
2212 if (btrfs_is_testing(fs_info))
2215 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2216 fs_info->delalloc_batch);
2217 spin_lock(&BTRFS_I(inode)->lock);
2218 BTRFS_I(inode)->delalloc_bytes += len;
2219 if (*bits & EXTENT_DEFRAG)
2220 BTRFS_I(inode)->defrag_bytes += len;
2221 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2222 &BTRFS_I(inode)->runtime_flags))
2223 btrfs_add_delalloc_inodes(root, inode);
2224 spin_unlock(&BTRFS_I(inode)->lock);
2227 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2228 (*bits & EXTENT_DELALLOC_NEW)) {
2229 spin_lock(&BTRFS_I(inode)->lock);
2230 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2232 spin_unlock(&BTRFS_I(inode)->lock);
2237 * Once a range is no longer delalloc this function ensures that proper
2238 * accounting happens.
2240 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2241 struct extent_state *state, unsigned *bits)
2243 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2244 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2245 u64 len = state->end + 1 - state->start;
2246 u32 num_extents = count_max_extents(len);
2248 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2249 spin_lock(&inode->lock);
2250 inode->defrag_bytes -= len;
2251 spin_unlock(&inode->lock);
2255 * set_bit and clear bit hooks normally require _irqsave/restore
2256 * but in this case, we are only testing for the DELALLOC
2257 * bit, which is only set or cleared with irqs on
2259 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2260 struct btrfs_root *root = inode->root;
2261 bool do_list = !btrfs_is_free_space_inode(inode);
2263 spin_lock(&inode->lock);
2264 btrfs_mod_outstanding_extents(inode, -num_extents);
2265 spin_unlock(&inode->lock);
2268 * We don't reserve metadata space for space cache inodes so we
2269 * don't need to call delalloc_release_metadata if there is an
2272 if (*bits & EXTENT_CLEAR_META_RESV &&
2273 root != fs_info->tree_root)
2274 btrfs_delalloc_release_metadata(inode, len, false);
2276 /* For sanity tests. */
2277 if (btrfs_is_testing(fs_info))
2280 if (!btrfs_is_data_reloc_root(root) &&
2281 do_list && !(state->state & EXTENT_NORESERVE) &&
2282 (*bits & EXTENT_CLEAR_DATA_RESV))
2283 btrfs_free_reserved_data_space_noquota(fs_info, len);
2285 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2286 fs_info->delalloc_batch);
2287 spin_lock(&inode->lock);
2288 inode->delalloc_bytes -= len;
2289 if (do_list && inode->delalloc_bytes == 0 &&
2290 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2291 &inode->runtime_flags))
2292 btrfs_del_delalloc_inode(root, inode);
2293 spin_unlock(&inode->lock);
2296 if ((state->state & EXTENT_DELALLOC_NEW) &&
2297 (*bits & EXTENT_DELALLOC_NEW)) {
2298 spin_lock(&inode->lock);
2299 ASSERT(inode->new_delalloc_bytes >= len);
2300 inode->new_delalloc_bytes -= len;
2301 if (*bits & EXTENT_ADD_INODE_BYTES)
2302 inode_add_bytes(&inode->vfs_inode, len);
2303 spin_unlock(&inode->lock);
2308 * in order to insert checksums into the metadata in large chunks,
2309 * we wait until bio submission time. All the pages in the bio are
2310 * checksummed and sums are attached onto the ordered extent record.
2312 * At IO completion time the cums attached on the ordered extent record
2313 * are inserted into the btree
2315 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2316 u64 dio_file_offset)
2318 return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2322 * Split an extent_map at [start, start + len]
2324 * This function is intended to be used only for extract_ordered_extent().
2326 static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2329 struct extent_map_tree *em_tree = &inode->extent_tree;
2330 struct extent_map *em;
2331 struct extent_map *split_pre = NULL;
2332 struct extent_map *split_mid = NULL;
2333 struct extent_map *split_post = NULL;
2335 unsigned long flags;
2338 if (pre == 0 && post == 0)
2341 split_pre = alloc_extent_map();
2343 split_mid = alloc_extent_map();
2345 split_post = alloc_extent_map();
2346 if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2351 ASSERT(pre + post < len);
2353 lock_extent(&inode->io_tree, start, start + len - 1);
2354 write_lock(&em_tree->lock);
2355 em = lookup_extent_mapping(em_tree, start, len);
2361 ASSERT(em->len == len);
2362 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2363 ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2364 ASSERT(test_bit(EXTENT_FLAG_PINNED, &em->flags));
2365 ASSERT(!test_bit(EXTENT_FLAG_LOGGING, &em->flags));
2366 ASSERT(!list_empty(&em->list));
2369 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2371 /* First, replace the em with a new extent_map starting from * em->start */
2372 split_pre->start = em->start;
2373 split_pre->len = (pre ? pre : em->len - post);
2374 split_pre->orig_start = split_pre->start;
2375 split_pre->block_start = em->block_start;
2376 split_pre->block_len = split_pre->len;
2377 split_pre->orig_block_len = split_pre->block_len;
2378 split_pre->ram_bytes = split_pre->len;
2379 split_pre->flags = flags;
2380 split_pre->compress_type = em->compress_type;
2381 split_pre->generation = em->generation;
2383 replace_extent_mapping(em_tree, em, split_pre, 1);
2386 * Now we only have an extent_map at:
2387 * [em->start, em->start + pre] if pre != 0
2388 * [em->start, em->start + em->len - post] if pre == 0
2392 /* Insert the middle extent_map */
2393 split_mid->start = em->start + pre;
2394 split_mid->len = em->len - pre - post;
2395 split_mid->orig_start = split_mid->start;
2396 split_mid->block_start = em->block_start + pre;
2397 split_mid->block_len = split_mid->len;
2398 split_mid->orig_block_len = split_mid->block_len;
2399 split_mid->ram_bytes = split_mid->len;
2400 split_mid->flags = flags;
2401 split_mid->compress_type = em->compress_type;
2402 split_mid->generation = em->generation;
2403 add_extent_mapping(em_tree, split_mid, 1);
2407 split_post->start = em->start + em->len - post;
2408 split_post->len = post;
2409 split_post->orig_start = split_post->start;
2410 split_post->block_start = em->block_start + em->len - post;
2411 split_post->block_len = split_post->len;
2412 split_post->orig_block_len = split_post->block_len;
2413 split_post->ram_bytes = split_post->len;
2414 split_post->flags = flags;
2415 split_post->compress_type = em->compress_type;
2416 split_post->generation = em->generation;
2417 add_extent_mapping(em_tree, split_post, 1);
2421 free_extent_map(em);
2422 /* Once for the tree */
2423 free_extent_map(em);
2426 write_unlock(&em_tree->lock);
2427 unlock_extent(&inode->io_tree, start, start + len - 1);
2429 free_extent_map(split_pre);
2430 free_extent_map(split_mid);
2431 free_extent_map(split_post);
2436 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2437 struct bio *bio, loff_t file_offset)
2439 struct btrfs_ordered_extent *ordered;
2440 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2442 u64 len = bio->bi_iter.bi_size;
2443 u64 end = start + len;
2448 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2449 if (WARN_ON_ONCE(!ordered))
2450 return BLK_STS_IOERR;
2452 /* No need to split */
2453 if (ordered->disk_num_bytes == len)
2456 /* We cannot split once end_bio'd ordered extent */
2457 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2462 /* We cannot split a compressed ordered extent */
2463 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2468 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2469 /* bio must be in one ordered extent */
2470 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2475 /* Checksum list should be empty */
2476 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2481 file_len = ordered->num_bytes;
2482 pre = start - ordered->disk_bytenr;
2483 post = ordered_end - end;
2485 ret = btrfs_split_ordered_extent(ordered, pre, post);
2488 ret = split_zoned_em(inode, file_offset, file_len, pre, post);
2491 btrfs_put_ordered_extent(ordered);
2493 return errno_to_blk_status(ret);
2497 * extent_io.c submission hook. This does the right thing for csum calculation
2498 * on write, or reading the csums from the tree before a read.
2500 * Rules about async/sync submit,
2501 * a) read: sync submit
2503 * b) write without checksum: sync submit
2505 * c) write with checksum:
2506 * c-1) if bio is issued by fsync: sync submit
2507 * (sync_writers != 0)
2509 * c-2) if root is reloc root: sync submit
2510 * (only in case of buffered IO)
2512 * c-3) otherwise: async submit
2514 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2515 int mirror_num, unsigned long bio_flags)
2518 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2519 struct btrfs_root *root = BTRFS_I(inode)->root;
2520 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2521 blk_status_t ret = 0;
2523 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2525 skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2526 test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2528 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2529 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2531 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2532 struct page *page = bio_first_bvec_all(bio)->bv_page;
2533 loff_t file_offset = page_offset(page);
2535 ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2540 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2541 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2545 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2546 ret = btrfs_submit_compressed_read(inode, bio,
2552 * Lookup bio sums does extra checks around whether we
2553 * need to csum or not, which is why we ignore skip_sum
2556 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2561 } else if (async && !skip_sum) {
2562 /* csum items have already been cloned */
2563 if (btrfs_is_data_reloc_root(root))
2565 /* we're doing a write, do the async checksumming */
2566 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2567 0, btrfs_submit_bio_start);
2569 } else if (!skip_sum) {
2570 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2576 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2580 bio->bi_status = ret;
2587 * given a list of ordered sums record them in the inode. This happens
2588 * at IO completion time based on sums calculated at bio submission time.
2590 static int add_pending_csums(struct btrfs_trans_handle *trans,
2591 struct list_head *list)
2593 struct btrfs_ordered_sum *sum;
2594 struct btrfs_root *csum_root = NULL;
2597 list_for_each_entry(sum, list, list) {
2598 trans->adding_csums = true;
2600 csum_root = btrfs_csum_root(trans->fs_info,
2602 ret = btrfs_csum_file_blocks(trans, csum_root, sum);
2603 trans->adding_csums = false;
2610 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2613 struct extent_state **cached_state)
2615 u64 search_start = start;
2616 const u64 end = start + len - 1;
2618 while (search_start < end) {
2619 const u64 search_len = end - search_start + 1;
2620 struct extent_map *em;
2624 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2628 if (em->block_start != EXTENT_MAP_HOLE)
2632 if (em->start < search_start)
2633 em_len -= search_start - em->start;
2634 if (em_len > search_len)
2635 em_len = search_len;
2637 ret = set_extent_bit(&inode->io_tree, search_start,
2638 search_start + em_len - 1,
2639 EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2642 search_start = extent_map_end(em);
2643 free_extent_map(em);
2650 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2651 unsigned int extra_bits,
2652 struct extent_state **cached_state)
2654 WARN_ON(PAGE_ALIGNED(end));
2656 if (start >= i_size_read(&inode->vfs_inode) &&
2657 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2659 * There can't be any extents following eof in this case so just
2660 * set the delalloc new bit for the range directly.
2662 extra_bits |= EXTENT_DELALLOC_NEW;
2666 ret = btrfs_find_new_delalloc_bytes(inode, start,
2673 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2677 /* see btrfs_writepage_start_hook for details on why this is required */
2678 struct btrfs_writepage_fixup {
2680 struct inode *inode;
2681 struct btrfs_work work;
2684 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2686 struct btrfs_writepage_fixup *fixup;
2687 struct btrfs_ordered_extent *ordered;
2688 struct extent_state *cached_state = NULL;
2689 struct extent_changeset *data_reserved = NULL;
2691 struct btrfs_inode *inode;
2695 bool free_delalloc_space = true;
2697 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2699 inode = BTRFS_I(fixup->inode);
2700 page_start = page_offset(page);
2701 page_end = page_offset(page) + PAGE_SIZE - 1;
2704 * This is similar to page_mkwrite, we need to reserve the space before
2705 * we take the page lock.
2707 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2713 * Before we queued this fixup, we took a reference on the page.
2714 * page->mapping may go NULL, but it shouldn't be moved to a different
2717 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2719 * Unfortunately this is a little tricky, either
2721 * 1) We got here and our page had already been dealt with and
2722 * we reserved our space, thus ret == 0, so we need to just
2723 * drop our space reservation and bail. This can happen the
2724 * first time we come into the fixup worker, or could happen
2725 * while waiting for the ordered extent.
2726 * 2) Our page was already dealt with, but we happened to get an
2727 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2728 * this case we obviously don't have anything to release, but
2729 * because the page was already dealt with we don't want to
2730 * mark the page with an error, so make sure we're resetting
2731 * ret to 0. This is why we have this check _before_ the ret
2732 * check, because we do not want to have a surprise ENOSPC
2733 * when the page was already properly dealt with.
2736 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2737 btrfs_delalloc_release_space(inode, data_reserved,
2738 page_start, PAGE_SIZE,
2746 * We can't mess with the page state unless it is locked, so now that
2747 * it is locked bail if we failed to make our space reservation.
2752 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2754 /* already ordered? We're done */
2755 if (PageOrdered(page))
2758 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2760 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2763 btrfs_start_ordered_extent(ordered, 1);
2764 btrfs_put_ordered_extent(ordered);
2768 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2774 * Everything went as planned, we're now the owner of a dirty page with
2775 * delayed allocation bits set and space reserved for our COW
2778 * The page was dirty when we started, nothing should have cleaned it.
2780 BUG_ON(!PageDirty(page));
2781 free_delalloc_space = false;
2783 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2784 if (free_delalloc_space)
2785 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2787 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2792 * We hit ENOSPC or other errors. Update the mapping and page
2793 * to reflect the errors and clean the page.
2795 mapping_set_error(page->mapping, ret);
2796 end_extent_writepage(page, ret, page_start, page_end);
2797 clear_page_dirty_for_io(page);
2800 btrfs_page_clear_checked(inode->root->fs_info, page, page_start, PAGE_SIZE);
2804 extent_changeset_free(data_reserved);
2806 * As a precaution, do a delayed iput in case it would be the last iput
2807 * that could need flushing space. Recursing back to fixup worker would
2810 btrfs_add_delayed_iput(&inode->vfs_inode);
2814 * There are a few paths in the higher layers of the kernel that directly
2815 * set the page dirty bit without asking the filesystem if it is a
2816 * good idea. This causes problems because we want to make sure COW
2817 * properly happens and the data=ordered rules are followed.
2819 * In our case any range that doesn't have the ORDERED bit set
2820 * hasn't been properly setup for IO. We kick off an async process
2821 * to fix it up. The async helper will wait for ordered extents, set
2822 * the delalloc bit and make it safe to write the page.
2824 int btrfs_writepage_cow_fixup(struct page *page)
2826 struct inode *inode = page->mapping->host;
2827 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2828 struct btrfs_writepage_fixup *fixup;
2830 /* This page has ordered extent covering it already */
2831 if (PageOrdered(page))
2835 * PageChecked is set below when we create a fixup worker for this page,
2836 * don't try to create another one if we're already PageChecked()
2838 * The extent_io writepage code will redirty the page if we send back
2841 if (PageChecked(page))
2844 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2849 * We are already holding a reference to this inode from
2850 * write_cache_pages. We need to hold it because the space reservation
2851 * takes place outside of the page lock, and we can't trust
2852 * page->mapping outside of the page lock.
2855 btrfs_page_set_checked(fs_info, page, page_offset(page), PAGE_SIZE);
2857 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2859 fixup->inode = inode;
2860 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2865 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2866 struct btrfs_inode *inode, u64 file_pos,
2867 struct btrfs_file_extent_item *stack_fi,
2868 const bool update_inode_bytes,
2869 u64 qgroup_reserved)
2871 struct btrfs_root *root = inode->root;
2872 const u64 sectorsize = root->fs_info->sectorsize;
2873 struct btrfs_path *path;
2874 struct extent_buffer *leaf;
2875 struct btrfs_key ins;
2876 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2877 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2878 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2879 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2880 struct btrfs_drop_extents_args drop_args = { 0 };
2883 path = btrfs_alloc_path();
2888 * we may be replacing one extent in the tree with another.
2889 * The new extent is pinned in the extent map, and we don't want
2890 * to drop it from the cache until it is completely in the btree.
2892 * So, tell btrfs_drop_extents to leave this extent in the cache.
2893 * the caller is expected to unpin it and allow it to be merged
2896 drop_args.path = path;
2897 drop_args.start = file_pos;
2898 drop_args.end = file_pos + num_bytes;
2899 drop_args.replace_extent = true;
2900 drop_args.extent_item_size = sizeof(*stack_fi);
2901 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2905 if (!drop_args.extent_inserted) {
2906 ins.objectid = btrfs_ino(inode);
2907 ins.offset = file_pos;
2908 ins.type = BTRFS_EXTENT_DATA_KEY;
2910 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2915 leaf = path->nodes[0];
2916 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2917 write_extent_buffer(leaf, stack_fi,
2918 btrfs_item_ptr_offset(leaf, path->slots[0]),
2919 sizeof(struct btrfs_file_extent_item));
2921 btrfs_mark_buffer_dirty(leaf);
2922 btrfs_release_path(path);
2925 * If we dropped an inline extent here, we know the range where it is
2926 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2927 * number of bytes only for that range containing the inline extent.
2928 * The remaining of the range will be processed when clearning the
2929 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2931 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2932 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2934 inline_size = drop_args.bytes_found - inline_size;
2935 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2936 drop_args.bytes_found -= inline_size;
2937 num_bytes -= sectorsize;
2940 if (update_inode_bytes)
2941 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2943 ins.objectid = disk_bytenr;
2944 ins.offset = disk_num_bytes;
2945 ins.type = BTRFS_EXTENT_ITEM_KEY;
2947 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2951 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2952 file_pos, qgroup_reserved, &ins);
2954 btrfs_free_path(path);
2959 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2962 struct btrfs_block_group *cache;
2964 cache = btrfs_lookup_block_group(fs_info, start);
2967 spin_lock(&cache->lock);
2968 cache->delalloc_bytes -= len;
2969 spin_unlock(&cache->lock);
2971 btrfs_put_block_group(cache);
2974 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2975 struct btrfs_ordered_extent *oe)
2977 struct btrfs_file_extent_item stack_fi;
2979 bool update_inode_bytes;
2981 memset(&stack_fi, 0, sizeof(stack_fi));
2982 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2983 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2984 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2985 oe->disk_num_bytes);
2986 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2987 logical_len = oe->truncated_len;
2989 logical_len = oe->num_bytes;
2990 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2991 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2992 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2993 /* Encryption and other encoding is reserved and all 0 */
2996 * For delalloc, when completing an ordered extent we update the inode's
2997 * bytes when clearing the range in the inode's io tree, so pass false
2998 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
2999 * except if the ordered extent was truncated.
3001 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3002 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3004 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3005 oe->file_offset, &stack_fi,
3006 update_inode_bytes, oe->qgroup_rsv);
3010 * As ordered data IO finishes, this gets called so we can finish
3011 * an ordered extent if the range of bytes in the file it covers are
3014 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3016 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3017 struct btrfs_root *root = inode->root;
3018 struct btrfs_fs_info *fs_info = root->fs_info;
3019 struct btrfs_trans_handle *trans = NULL;
3020 struct extent_io_tree *io_tree = &inode->io_tree;
3021 struct extent_state *cached_state = NULL;
3023 int compress_type = 0;
3025 u64 logical_len = ordered_extent->num_bytes;
3026 bool freespace_inode;
3027 bool truncated = false;
3028 bool clear_reserved_extent = true;
3029 unsigned int clear_bits = EXTENT_DEFRAG;
3031 start = ordered_extent->file_offset;
3032 end = start + ordered_extent->num_bytes - 1;
3034 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3035 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3036 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
3037 clear_bits |= EXTENT_DELALLOC_NEW;
3039 freespace_inode = btrfs_is_free_space_inode(inode);
3041 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3046 /* A valid bdev implies a write on a sequential zone */
3047 if (ordered_extent->bdev) {
3048 btrfs_rewrite_logical_zoned(ordered_extent);
3049 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3050 ordered_extent->disk_num_bytes);
3053 btrfs_free_io_failure_record(inode, start, end);
3055 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3057 logical_len = ordered_extent->truncated_len;
3058 /* Truncated the entire extent, don't bother adding */
3063 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3064 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3066 btrfs_inode_safe_disk_i_size_write(inode, 0);
3067 if (freespace_inode)
3068 trans = btrfs_join_transaction_spacecache(root);
3070 trans = btrfs_join_transaction(root);
3071 if (IS_ERR(trans)) {
3072 ret = PTR_ERR(trans);
3076 trans->block_rsv = &inode->block_rsv;
3077 ret = btrfs_update_inode_fallback(trans, root, inode);
3078 if (ret) /* -ENOMEM or corruption */
3079 btrfs_abort_transaction(trans, ret);
3083 clear_bits |= EXTENT_LOCKED;
3084 lock_extent_bits(io_tree, start, end, &cached_state);
3086 if (freespace_inode)
3087 trans = btrfs_join_transaction_spacecache(root);
3089 trans = btrfs_join_transaction(root);
3090 if (IS_ERR(trans)) {
3091 ret = PTR_ERR(trans);
3096 trans->block_rsv = &inode->block_rsv;
3098 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3099 compress_type = ordered_extent->compress_type;
3100 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3101 BUG_ON(compress_type);
3102 ret = btrfs_mark_extent_written(trans, inode,
3103 ordered_extent->file_offset,
3104 ordered_extent->file_offset +
3107 BUG_ON(root == fs_info->tree_root);
3108 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3110 clear_reserved_extent = false;
3111 btrfs_release_delalloc_bytes(fs_info,
3112 ordered_extent->disk_bytenr,
3113 ordered_extent->disk_num_bytes);
3116 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3117 ordered_extent->num_bytes, trans->transid);
3119 btrfs_abort_transaction(trans, ret);
3123 ret = add_pending_csums(trans, &ordered_extent->list);
3125 btrfs_abort_transaction(trans, ret);
3130 * If this is a new delalloc range, clear its new delalloc flag to
3131 * update the inode's number of bytes. This needs to be done first
3132 * before updating the inode item.
3134 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3135 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3136 clear_extent_bit(&inode->io_tree, start, end,
3137 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3138 0, 0, &cached_state);
3140 btrfs_inode_safe_disk_i_size_write(inode, 0);
3141 ret = btrfs_update_inode_fallback(trans, root, inode);
3142 if (ret) { /* -ENOMEM or corruption */
3143 btrfs_abort_transaction(trans, ret);
3148 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3149 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
3153 btrfs_end_transaction(trans);
3155 if (ret || truncated) {
3156 u64 unwritten_start = start;
3159 * If we failed to finish this ordered extent for any reason we
3160 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3161 * extent, and mark the inode with the error if it wasn't
3162 * already set. Any error during writeback would have already
3163 * set the mapping error, so we need to set it if we're the ones
3164 * marking this ordered extent as failed.
3166 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3167 &ordered_extent->flags))
3168 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3171 unwritten_start += logical_len;
3172 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3174 /* Drop the cache for the part of the extent we didn't write. */
3175 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3178 * If the ordered extent had an IOERR or something else went
3179 * wrong we need to return the space for this ordered extent
3180 * back to the allocator. We only free the extent in the
3181 * truncated case if we didn't write out the extent at all.
3183 * If we made it past insert_reserved_file_extent before we
3184 * errored out then we don't need to do this as the accounting
3185 * has already been done.
3187 if ((ret || !logical_len) &&
3188 clear_reserved_extent &&
3189 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3190 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3192 * Discard the range before returning it back to the
3195 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3196 btrfs_discard_extent(fs_info,
3197 ordered_extent->disk_bytenr,
3198 ordered_extent->disk_num_bytes,
3200 btrfs_free_reserved_extent(fs_info,
3201 ordered_extent->disk_bytenr,
3202 ordered_extent->disk_num_bytes, 1);
3207 * This needs to be done to make sure anybody waiting knows we are done
3208 * updating everything for this ordered extent.
3210 btrfs_remove_ordered_extent(inode, ordered_extent);
3213 btrfs_put_ordered_extent(ordered_extent);
3214 /* once for the tree */
3215 btrfs_put_ordered_extent(ordered_extent);
3220 static void finish_ordered_fn(struct btrfs_work *work)
3222 struct btrfs_ordered_extent *ordered_extent;
3223 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3224 btrfs_finish_ordered_io(ordered_extent);
3227 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3228 struct page *page, u64 start,
3229 u64 end, bool uptodate)
3231 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3233 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start,
3234 finish_ordered_fn, uptodate);
3238 * check_data_csum - verify checksum of one sector of uncompressed data
3240 * @io_bio: btrfs_io_bio which contains the csum
3241 * @bio_offset: offset to the beginning of the bio (in bytes)
3242 * @page: page where is the data to be verified
3243 * @pgoff: offset inside the page
3244 * @start: logical offset in the file
3246 * The length of such check is always one sector size.
3248 static int check_data_csum(struct inode *inode, struct btrfs_bio *bbio,
3249 u32 bio_offset, struct page *page, u32 pgoff,
3252 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3253 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3255 u32 len = fs_info->sectorsize;
3256 const u32 csum_size = fs_info->csum_size;
3257 unsigned int offset_sectors;
3259 u8 csum[BTRFS_CSUM_SIZE];
3261 ASSERT(pgoff + len <= PAGE_SIZE);
3263 offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3264 csum_expected = ((u8 *)bbio->csum) + offset_sectors * csum_size;
3266 kaddr = kmap_atomic(page);
3267 shash->tfm = fs_info->csum_shash;
3269 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3271 if (memcmp(csum, csum_expected, csum_size))
3274 kunmap_atomic(kaddr);
3277 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3280 btrfs_dev_stat_inc_and_print(bbio->device,
3281 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3282 memset(kaddr + pgoff, 1, len);
3283 flush_dcache_page(page);
3284 kunmap_atomic(kaddr);
3289 * When reads are done, we need to check csums to verify the data is correct.
3290 * if there's a match, we allow the bio to finish. If not, the code in
3291 * extent_io.c will try to find good copies for us.
3293 * @bio_offset: offset to the beginning of the bio (in bytes)
3294 * @start: file offset of the range start
3295 * @end: file offset of the range end (inclusive)
3297 * Return a bitmap where bit set means a csum mismatch, and bit not set means
3300 unsigned int btrfs_verify_data_csum(struct btrfs_bio *bbio,
3301 u32 bio_offset, struct page *page,
3304 struct inode *inode = page->mapping->host;
3305 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3306 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3307 struct btrfs_root *root = BTRFS_I(inode)->root;
3308 const u32 sectorsize = root->fs_info->sectorsize;
3310 unsigned int result = 0;
3312 if (btrfs_page_test_checked(fs_info, page, start, end + 1 - start)) {
3313 btrfs_page_clear_checked(fs_info, page, start, end + 1 - start);
3318 * This only happens for NODATASUM or compressed read.
3319 * Normally this should be covered by above check for compressed read
3320 * or the next check for NODATASUM. Just do a quicker exit here.
3322 if (bbio->csum == NULL)
3325 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3328 if (unlikely(test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state)))
3331 ASSERT(page_offset(page) <= start &&
3332 end <= page_offset(page) + PAGE_SIZE - 1);
3333 for (pg_off = offset_in_page(start);
3334 pg_off < offset_in_page(end);
3335 pg_off += sectorsize, bio_offset += sectorsize) {
3336 u64 file_offset = pg_off + page_offset(page);
3339 if (btrfs_is_data_reloc_root(root) &&
3340 test_range_bit(io_tree, file_offset,
3341 file_offset + sectorsize - 1,
3342 EXTENT_NODATASUM, 1, NULL)) {
3343 /* Skip the range without csum for data reloc inode */
3344 clear_extent_bits(io_tree, file_offset,
3345 file_offset + sectorsize - 1,
3349 ret = check_data_csum(inode, bbio, bio_offset, page, pg_off,
3350 page_offset(page) + pg_off);
3352 const int nr_bit = (pg_off - offset_in_page(start)) >>
3353 root->fs_info->sectorsize_bits;
3355 result |= (1U << nr_bit);
3362 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3364 * @inode: The inode we want to perform iput on
3366 * This function uses the generic vfs_inode::i_count to track whether we should
3367 * just decrement it (in case it's > 1) or if this is the last iput then link
3368 * the inode to the delayed iput machinery. Delayed iputs are processed at
3369 * transaction commit time/superblock commit/cleaner kthread.
3371 void btrfs_add_delayed_iput(struct inode *inode)
3373 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3374 struct btrfs_inode *binode = BTRFS_I(inode);
3376 if (atomic_add_unless(&inode->i_count, -1, 1))
3379 atomic_inc(&fs_info->nr_delayed_iputs);
3380 spin_lock(&fs_info->delayed_iput_lock);
3381 ASSERT(list_empty(&binode->delayed_iput));
3382 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3383 spin_unlock(&fs_info->delayed_iput_lock);
3384 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3385 wake_up_process(fs_info->cleaner_kthread);
3388 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3389 struct btrfs_inode *inode)
3391 list_del_init(&inode->delayed_iput);
3392 spin_unlock(&fs_info->delayed_iput_lock);
3393 iput(&inode->vfs_inode);
3394 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3395 wake_up(&fs_info->delayed_iputs_wait);
3396 spin_lock(&fs_info->delayed_iput_lock);
3399 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3400 struct btrfs_inode *inode)
3402 if (!list_empty(&inode->delayed_iput)) {
3403 spin_lock(&fs_info->delayed_iput_lock);
3404 if (!list_empty(&inode->delayed_iput))
3405 run_delayed_iput_locked(fs_info, inode);
3406 spin_unlock(&fs_info->delayed_iput_lock);
3410 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3413 spin_lock(&fs_info->delayed_iput_lock);
3414 while (!list_empty(&fs_info->delayed_iputs)) {
3415 struct btrfs_inode *inode;
3417 inode = list_first_entry(&fs_info->delayed_iputs,
3418 struct btrfs_inode, delayed_iput);
3419 run_delayed_iput_locked(fs_info, inode);
3420 cond_resched_lock(&fs_info->delayed_iput_lock);
3422 spin_unlock(&fs_info->delayed_iput_lock);
3426 * Wait for flushing all delayed iputs
3428 * @fs_info: the filesystem
3430 * This will wait on any delayed iputs that are currently running with KILLABLE
3431 * set. Once they are all done running we will return, unless we are killed in
3432 * which case we return EINTR. This helps in user operations like fallocate etc
3433 * that might get blocked on the iputs.
3435 * Return EINTR if we were killed, 0 if nothing's pending
3437 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3439 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3440 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3447 * This creates an orphan entry for the given inode in case something goes wrong
3448 * in the middle of an unlink.
3450 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3451 struct btrfs_inode *inode)
3455 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3456 if (ret && ret != -EEXIST) {
3457 btrfs_abort_transaction(trans, ret);
3465 * We have done the delete so we can go ahead and remove the orphan item for
3466 * this particular inode.
3468 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3469 struct btrfs_inode *inode)
3471 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3475 * this cleans up any orphans that may be left on the list from the last use
3478 int btrfs_orphan_cleanup(struct btrfs_root *root)
3480 struct btrfs_fs_info *fs_info = root->fs_info;
3481 struct btrfs_path *path;
3482 struct extent_buffer *leaf;
3483 struct btrfs_key key, found_key;
3484 struct btrfs_trans_handle *trans;
3485 struct inode *inode;
3486 u64 last_objectid = 0;
3487 int ret = 0, nr_unlink = 0;
3489 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3492 path = btrfs_alloc_path();
3497 path->reada = READA_BACK;
3499 key.objectid = BTRFS_ORPHAN_OBJECTID;
3500 key.type = BTRFS_ORPHAN_ITEM_KEY;
3501 key.offset = (u64)-1;
3504 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3509 * if ret == 0 means we found what we were searching for, which
3510 * is weird, but possible, so only screw with path if we didn't
3511 * find the key and see if we have stuff that matches
3515 if (path->slots[0] == 0)
3520 /* pull out the item */
3521 leaf = path->nodes[0];
3522 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3524 /* make sure the item matches what we want */
3525 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3527 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3530 /* release the path since we're done with it */
3531 btrfs_release_path(path);
3534 * this is where we are basically btrfs_lookup, without the
3535 * crossing root thing. we store the inode number in the
3536 * offset of the orphan item.
3539 if (found_key.offset == last_objectid) {
3541 "Error removing orphan entry, stopping orphan cleanup");
3546 last_objectid = found_key.offset;
3548 found_key.objectid = found_key.offset;
3549 found_key.type = BTRFS_INODE_ITEM_KEY;
3550 found_key.offset = 0;
3551 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3552 ret = PTR_ERR_OR_ZERO(inode);
3553 if (ret && ret != -ENOENT)
3556 if (ret == -ENOENT && root == fs_info->tree_root) {
3557 struct btrfs_root *dead_root;
3558 int is_dead_root = 0;
3561 * This is an orphan in the tree root. Currently these
3562 * could come from 2 sources:
3563 * a) a root (snapshot/subvolume) deletion in progress
3564 * b) a free space cache inode
3565 * We need to distinguish those two, as the orphan item
3566 * for a root must not get deleted before the deletion
3567 * of the snapshot/subvolume's tree completes.
3569 * btrfs_find_orphan_roots() ran before us, which has
3570 * found all deleted roots and loaded them into
3571 * fs_info->fs_roots_radix. So here we can find if an
3572 * orphan item corresponds to a deleted root by looking
3573 * up the root from that radix tree.
3576 spin_lock(&fs_info->fs_roots_radix_lock);
3577 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3578 (unsigned long)found_key.objectid);
3579 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3581 spin_unlock(&fs_info->fs_roots_radix_lock);
3584 /* prevent this orphan from being found again */
3585 key.offset = found_key.objectid - 1;
3592 * If we have an inode with links, there are a couple of
3595 * 1. We were halfway through creating fsverity metadata for the
3596 * file. In that case, the orphan item represents incomplete
3597 * fsverity metadata which must be cleaned up with
3598 * btrfs_drop_verity_items and deleting the orphan item.
3600 * 2. Old kernels (before v3.12) used to create an
3601 * orphan item for truncate indicating that there were possibly
3602 * extent items past i_size that needed to be deleted. In v3.12,
3603 * truncate was changed to update i_size in sync with the extent
3604 * items, but the (useless) orphan item was still created. Since
3605 * v4.18, we don't create the orphan item for truncate at all.
3607 * So, this item could mean that we need to do a truncate, but
3608 * only if this filesystem was last used on a pre-v3.12 kernel
3609 * and was not cleanly unmounted. The odds of that are quite
3610 * slim, and it's a pain to do the truncate now, so just delete
3613 * It's also possible that this orphan item was supposed to be
3614 * deleted but wasn't. The inode number may have been reused,
3615 * but either way, we can delete the orphan item.
3617 if (ret == -ENOENT || inode->i_nlink) {
3619 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3624 trans = btrfs_start_transaction(root, 1);
3625 if (IS_ERR(trans)) {
3626 ret = PTR_ERR(trans);
3629 btrfs_debug(fs_info, "auto deleting %Lu",
3630 found_key.objectid);
3631 ret = btrfs_del_orphan_item(trans, root,
3632 found_key.objectid);
3633 btrfs_end_transaction(trans);
3641 /* this will do delete_inode and everything for us */
3644 /* release the path since we're done with it */
3645 btrfs_release_path(path);
3647 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3648 trans = btrfs_join_transaction(root);
3650 btrfs_end_transaction(trans);
3654 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3658 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3659 btrfs_free_path(path);
3664 * very simple check to peek ahead in the leaf looking for xattrs. If we
3665 * don't find any xattrs, we know there can't be any acls.
3667 * slot is the slot the inode is in, objectid is the objectid of the inode
3669 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3670 int slot, u64 objectid,
3671 int *first_xattr_slot)
3673 u32 nritems = btrfs_header_nritems(leaf);
3674 struct btrfs_key found_key;
3675 static u64 xattr_access = 0;
3676 static u64 xattr_default = 0;
3679 if (!xattr_access) {
3680 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3681 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3682 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3683 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3687 *first_xattr_slot = -1;
3688 while (slot < nritems) {
3689 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3691 /* we found a different objectid, there must not be acls */
3692 if (found_key.objectid != objectid)
3695 /* we found an xattr, assume we've got an acl */
3696 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3697 if (*first_xattr_slot == -1)
3698 *first_xattr_slot = slot;
3699 if (found_key.offset == xattr_access ||
3700 found_key.offset == xattr_default)
3705 * we found a key greater than an xattr key, there can't
3706 * be any acls later on
3708 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3715 * it goes inode, inode backrefs, xattrs, extents,
3716 * so if there are a ton of hard links to an inode there can
3717 * be a lot of backrefs. Don't waste time searching too hard,
3718 * this is just an optimization
3723 /* we hit the end of the leaf before we found an xattr or
3724 * something larger than an xattr. We have to assume the inode
3727 if (*first_xattr_slot == -1)
3728 *first_xattr_slot = slot;
3733 * read an inode from the btree into the in-memory inode
3735 static int btrfs_read_locked_inode(struct inode *inode,
3736 struct btrfs_path *in_path)
3738 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3739 struct btrfs_path *path = in_path;
3740 struct extent_buffer *leaf;
3741 struct btrfs_inode_item *inode_item;
3742 struct btrfs_root *root = BTRFS_I(inode)->root;
3743 struct btrfs_key location;
3748 bool filled = false;
3749 int first_xattr_slot;
3751 ret = btrfs_fill_inode(inode, &rdev);
3756 path = btrfs_alloc_path();
3761 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3763 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3765 if (path != in_path)
3766 btrfs_free_path(path);
3770 leaf = path->nodes[0];
3775 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3776 struct btrfs_inode_item);
3777 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3778 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3779 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3780 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3781 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3782 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3783 round_up(i_size_read(inode), fs_info->sectorsize));
3785 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3786 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3788 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3789 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3791 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3792 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3794 BTRFS_I(inode)->i_otime.tv_sec =
3795 btrfs_timespec_sec(leaf, &inode_item->otime);
3796 BTRFS_I(inode)->i_otime.tv_nsec =
3797 btrfs_timespec_nsec(leaf, &inode_item->otime);
3799 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3800 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3801 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3803 inode_set_iversion_queried(inode,
3804 btrfs_inode_sequence(leaf, inode_item));
3805 inode->i_generation = BTRFS_I(inode)->generation;
3807 rdev = btrfs_inode_rdev(leaf, inode_item);
3809 BTRFS_I(inode)->index_cnt = (u64)-1;
3810 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
3811 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
3815 * If we were modified in the current generation and evicted from memory
3816 * and then re-read we need to do a full sync since we don't have any
3817 * idea about which extents were modified before we were evicted from
3820 * This is required for both inode re-read from disk and delayed inode
3821 * in delayed_nodes_tree.
3823 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3824 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3825 &BTRFS_I(inode)->runtime_flags);
3828 * We don't persist the id of the transaction where an unlink operation
3829 * against the inode was last made. So here we assume the inode might
3830 * have been evicted, and therefore the exact value of last_unlink_trans
3831 * lost, and set it to last_trans to avoid metadata inconsistencies
3832 * between the inode and its parent if the inode is fsync'ed and the log
3833 * replayed. For example, in the scenario:
3836 * ln mydir/foo mydir/bar
3839 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3840 * xfs_io -c fsync mydir/foo
3842 * mount fs, triggers fsync log replay
3844 * We must make sure that when we fsync our inode foo we also log its
3845 * parent inode, otherwise after log replay the parent still has the
3846 * dentry with the "bar" name but our inode foo has a link count of 1
3847 * and doesn't have an inode ref with the name "bar" anymore.
3849 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3850 * but it guarantees correctness at the expense of occasional full
3851 * transaction commits on fsync if our inode is a directory, or if our
3852 * inode is not a directory, logging its parent unnecessarily.
3854 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3857 * Same logic as for last_unlink_trans. We don't persist the generation
3858 * of the last transaction where this inode was used for a reflink
3859 * operation, so after eviction and reloading the inode we must be
3860 * pessimistic and assume the last transaction that modified the inode.
3862 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3865 if (inode->i_nlink != 1 ||
3866 path->slots[0] >= btrfs_header_nritems(leaf))
3869 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3870 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3873 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3874 if (location.type == BTRFS_INODE_REF_KEY) {
3875 struct btrfs_inode_ref *ref;
3877 ref = (struct btrfs_inode_ref *)ptr;
3878 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3879 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3880 struct btrfs_inode_extref *extref;
3882 extref = (struct btrfs_inode_extref *)ptr;
3883 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3888 * try to precache a NULL acl entry for files that don't have
3889 * any xattrs or acls
3891 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3892 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3893 if (first_xattr_slot != -1) {
3894 path->slots[0] = first_xattr_slot;
3895 ret = btrfs_load_inode_props(inode, path);
3898 "error loading props for ino %llu (root %llu): %d",
3899 btrfs_ino(BTRFS_I(inode)),
3900 root->root_key.objectid, ret);
3902 if (path != in_path)
3903 btrfs_free_path(path);
3906 cache_no_acl(inode);
3908 switch (inode->i_mode & S_IFMT) {
3910 inode->i_mapping->a_ops = &btrfs_aops;
3911 inode->i_fop = &btrfs_file_operations;
3912 inode->i_op = &btrfs_file_inode_operations;
3915 inode->i_fop = &btrfs_dir_file_operations;
3916 inode->i_op = &btrfs_dir_inode_operations;
3919 inode->i_op = &btrfs_symlink_inode_operations;
3920 inode_nohighmem(inode);
3921 inode->i_mapping->a_ops = &btrfs_aops;
3924 inode->i_op = &btrfs_special_inode_operations;
3925 init_special_inode(inode, inode->i_mode, rdev);
3929 btrfs_sync_inode_flags_to_i_flags(inode);
3934 * given a leaf and an inode, copy the inode fields into the leaf
3936 static void fill_inode_item(struct btrfs_trans_handle *trans,
3937 struct extent_buffer *leaf,
3938 struct btrfs_inode_item *item,
3939 struct inode *inode)
3941 struct btrfs_map_token token;
3944 btrfs_init_map_token(&token, leaf);
3946 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3947 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3948 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3949 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3950 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3952 btrfs_set_token_timespec_sec(&token, &item->atime,
3953 inode->i_atime.tv_sec);
3954 btrfs_set_token_timespec_nsec(&token, &item->atime,
3955 inode->i_atime.tv_nsec);
3957 btrfs_set_token_timespec_sec(&token, &item->mtime,
3958 inode->i_mtime.tv_sec);
3959 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3960 inode->i_mtime.tv_nsec);
3962 btrfs_set_token_timespec_sec(&token, &item->ctime,
3963 inode->i_ctime.tv_sec);
3964 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3965 inode->i_ctime.tv_nsec);
3967 btrfs_set_token_timespec_sec(&token, &item->otime,
3968 BTRFS_I(inode)->i_otime.tv_sec);
3969 btrfs_set_token_timespec_nsec(&token, &item->otime,
3970 BTRFS_I(inode)->i_otime.tv_nsec);
3972 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3973 btrfs_set_token_inode_generation(&token, item,
3974 BTRFS_I(inode)->generation);
3975 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3976 btrfs_set_token_inode_transid(&token, item, trans->transid);
3977 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3978 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
3979 BTRFS_I(inode)->ro_flags);
3980 btrfs_set_token_inode_flags(&token, item, flags);
3981 btrfs_set_token_inode_block_group(&token, item, 0);
3985 * copy everything in the in-memory inode into the btree.
3987 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3988 struct btrfs_root *root,
3989 struct btrfs_inode *inode)
3991 struct btrfs_inode_item *inode_item;
3992 struct btrfs_path *path;
3993 struct extent_buffer *leaf;
3996 path = btrfs_alloc_path();
4000 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4007 leaf = path->nodes[0];
4008 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4009 struct btrfs_inode_item);
4011 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4012 btrfs_mark_buffer_dirty(leaf);
4013 btrfs_set_inode_last_trans(trans, inode);
4016 btrfs_free_path(path);
4021 * copy everything in the in-memory inode into the btree.
4023 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4024 struct btrfs_root *root,
4025 struct btrfs_inode *inode)
4027 struct btrfs_fs_info *fs_info = root->fs_info;
4031 * If the inode is a free space inode, we can deadlock during commit
4032 * if we put it into the delayed code.
4034 * The data relocation inode should also be directly updated
4037 if (!btrfs_is_free_space_inode(inode)
4038 && !btrfs_is_data_reloc_root(root)
4039 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4040 btrfs_update_root_times(trans, root);
4042 ret = btrfs_delayed_update_inode(trans, root, inode);
4044 btrfs_set_inode_last_trans(trans, inode);
4048 return btrfs_update_inode_item(trans, root, inode);
4051 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4052 struct btrfs_root *root, struct btrfs_inode *inode)
4056 ret = btrfs_update_inode(trans, root, inode);
4058 return btrfs_update_inode_item(trans, root, inode);
4063 * unlink helper that gets used here in inode.c and in the tree logging
4064 * recovery code. It remove a link in a directory with a given name, and
4065 * also drops the back refs in the inode to the directory
4067 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4068 struct btrfs_inode *dir,
4069 struct btrfs_inode *inode,
4070 const char *name, int name_len,
4071 struct btrfs_rename_ctx *rename_ctx)
4073 struct btrfs_root *root = dir->root;
4074 struct btrfs_fs_info *fs_info = root->fs_info;
4075 struct btrfs_path *path;
4077 struct btrfs_dir_item *di;
4079 u64 ino = btrfs_ino(inode);
4080 u64 dir_ino = btrfs_ino(dir);
4082 path = btrfs_alloc_path();
4088 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4089 name, name_len, -1);
4090 if (IS_ERR_OR_NULL(di)) {
4091 ret = di ? PTR_ERR(di) : -ENOENT;
4094 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4097 btrfs_release_path(path);
4100 * If we don't have dir index, we have to get it by looking up
4101 * the inode ref, since we get the inode ref, remove it directly,
4102 * it is unnecessary to do delayed deletion.
4104 * But if we have dir index, needn't search inode ref to get it.
4105 * Since the inode ref is close to the inode item, it is better
4106 * that we delay to delete it, and just do this deletion when
4107 * we update the inode item.
4109 if (inode->dir_index) {
4110 ret = btrfs_delayed_delete_inode_ref(inode);
4112 index = inode->dir_index;
4117 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4121 "failed to delete reference to %.*s, inode %llu parent %llu",
4122 name_len, name, ino, dir_ino);
4123 btrfs_abort_transaction(trans, ret);
4128 rename_ctx->index = index;
4130 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4132 btrfs_abort_transaction(trans, ret);
4137 * If we are in a rename context, we don't need to update anything in the
4138 * log. That will be done later during the rename by btrfs_log_new_name().
4139 * Besides that, doing it here would only cause extra unncessary btree
4140 * operations on the log tree, increasing latency for applications.
4143 btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4145 btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4150 * If we have a pending delayed iput we could end up with the final iput
4151 * being run in btrfs-cleaner context. If we have enough of these built
4152 * up we can end up burning a lot of time in btrfs-cleaner without any
4153 * way to throttle the unlinks. Since we're currently holding a ref on
4154 * the inode we can run the delayed iput here without any issues as the
4155 * final iput won't be done until after we drop the ref we're currently
4158 btrfs_run_delayed_iput(fs_info, inode);
4160 btrfs_free_path(path);
4164 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4165 inode_inc_iversion(&inode->vfs_inode);
4166 inode_inc_iversion(&dir->vfs_inode);
4167 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4168 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4169 ret = btrfs_update_inode(trans, root, dir);
4174 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4175 struct btrfs_inode *dir, struct btrfs_inode *inode,
4176 const char *name, int name_len)
4179 ret = __btrfs_unlink_inode(trans, dir, inode, name, name_len, NULL);
4181 drop_nlink(&inode->vfs_inode);
4182 ret = btrfs_update_inode(trans, inode->root, inode);
4188 * helper to start transaction for unlink and rmdir.
4190 * unlink and rmdir are special in btrfs, they do not always free space, so
4191 * if we cannot make our reservations the normal way try and see if there is
4192 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4193 * allow the unlink to occur.
4195 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4197 struct btrfs_root *root = BTRFS_I(dir)->root;
4200 * 1 for the possible orphan item
4201 * 1 for the dir item
4202 * 1 for the dir index
4203 * 1 for the inode ref
4206 return btrfs_start_transaction_fallback_global_rsv(root, 5);
4209 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4211 struct btrfs_trans_handle *trans;
4212 struct inode *inode = d_inode(dentry);
4215 trans = __unlink_start_trans(dir);
4217 return PTR_ERR(trans);
4219 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4222 ret = btrfs_unlink_inode(trans, BTRFS_I(dir),
4223 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4224 dentry->d_name.len);
4228 if (inode->i_nlink == 0) {
4229 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4235 btrfs_end_transaction(trans);
4236 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4240 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4241 struct inode *dir, struct dentry *dentry)
4243 struct btrfs_root *root = BTRFS_I(dir)->root;
4244 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4245 struct btrfs_path *path;
4246 struct extent_buffer *leaf;
4247 struct btrfs_dir_item *di;
4248 struct btrfs_key key;
4249 const char *name = dentry->d_name.name;
4250 int name_len = dentry->d_name.len;
4254 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4256 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4257 objectid = inode->root->root_key.objectid;
4258 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4259 objectid = inode->location.objectid;
4265 path = btrfs_alloc_path();
4269 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4270 name, name_len, -1);
4271 if (IS_ERR_OR_NULL(di)) {
4272 ret = di ? PTR_ERR(di) : -ENOENT;
4276 leaf = path->nodes[0];
4277 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4278 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4279 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4281 btrfs_abort_transaction(trans, ret);
4284 btrfs_release_path(path);
4287 * This is a placeholder inode for a subvolume we didn't have a
4288 * reference to at the time of the snapshot creation. In the meantime
4289 * we could have renamed the real subvol link into our snapshot, so
4290 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4291 * Instead simply lookup the dir_index_item for this entry so we can
4292 * remove it. Otherwise we know we have a ref to the root and we can
4293 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4295 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4296 di = btrfs_search_dir_index_item(root, path, dir_ino,
4298 if (IS_ERR_OR_NULL(di)) {
4303 btrfs_abort_transaction(trans, ret);
4307 leaf = path->nodes[0];
4308 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4310 btrfs_release_path(path);
4312 ret = btrfs_del_root_ref(trans, objectid,
4313 root->root_key.objectid, dir_ino,
4314 &index, name, name_len);
4316 btrfs_abort_transaction(trans, ret);
4321 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4323 btrfs_abort_transaction(trans, ret);
4327 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4328 inode_inc_iversion(dir);
4329 dir->i_mtime = dir->i_ctime = current_time(dir);
4330 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4332 btrfs_abort_transaction(trans, ret);
4334 btrfs_free_path(path);
4339 * Helper to check if the subvolume references other subvolumes or if it's
4342 static noinline int may_destroy_subvol(struct btrfs_root *root)
4344 struct btrfs_fs_info *fs_info = root->fs_info;
4345 struct btrfs_path *path;
4346 struct btrfs_dir_item *di;
4347 struct btrfs_key key;
4351 path = btrfs_alloc_path();
4355 /* Make sure this root isn't set as the default subvol */
4356 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4357 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4358 dir_id, "default", 7, 0);
4359 if (di && !IS_ERR(di)) {
4360 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4361 if (key.objectid == root->root_key.objectid) {
4364 "deleting default subvolume %llu is not allowed",
4368 btrfs_release_path(path);
4371 key.objectid = root->root_key.objectid;
4372 key.type = BTRFS_ROOT_REF_KEY;
4373 key.offset = (u64)-1;
4375 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4381 if (path->slots[0] > 0) {
4383 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4384 if (key.objectid == root->root_key.objectid &&
4385 key.type == BTRFS_ROOT_REF_KEY)
4389 btrfs_free_path(path);
4393 /* Delete all dentries for inodes belonging to the root */
4394 static void btrfs_prune_dentries(struct btrfs_root *root)
4396 struct btrfs_fs_info *fs_info = root->fs_info;
4397 struct rb_node *node;
4398 struct rb_node *prev;
4399 struct btrfs_inode *entry;
4400 struct inode *inode;
4403 if (!BTRFS_FS_ERROR(fs_info))
4404 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4406 spin_lock(&root->inode_lock);
4408 node = root->inode_tree.rb_node;
4412 entry = rb_entry(node, struct btrfs_inode, rb_node);
4414 if (objectid < btrfs_ino(entry))
4415 node = node->rb_left;
4416 else if (objectid > btrfs_ino(entry))
4417 node = node->rb_right;
4423 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4424 if (objectid <= btrfs_ino(entry)) {
4428 prev = rb_next(prev);
4432 entry = rb_entry(node, struct btrfs_inode, rb_node);
4433 objectid = btrfs_ino(entry) + 1;
4434 inode = igrab(&entry->vfs_inode);
4436 spin_unlock(&root->inode_lock);
4437 if (atomic_read(&inode->i_count) > 1)
4438 d_prune_aliases(inode);
4440 * btrfs_drop_inode will have it removed from the inode
4441 * cache when its usage count hits zero.
4445 spin_lock(&root->inode_lock);
4449 if (cond_resched_lock(&root->inode_lock))
4452 node = rb_next(node);
4454 spin_unlock(&root->inode_lock);
4457 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4459 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4460 struct btrfs_root *root = BTRFS_I(dir)->root;
4461 struct inode *inode = d_inode(dentry);
4462 struct btrfs_root *dest = BTRFS_I(inode)->root;
4463 struct btrfs_trans_handle *trans;
4464 struct btrfs_block_rsv block_rsv;
4469 * Don't allow to delete a subvolume with send in progress. This is
4470 * inside the inode lock so the error handling that has to drop the bit
4471 * again is not run concurrently.
4473 spin_lock(&dest->root_item_lock);
4474 if (dest->send_in_progress) {
4475 spin_unlock(&dest->root_item_lock);
4477 "attempt to delete subvolume %llu during send",
4478 dest->root_key.objectid);
4481 root_flags = btrfs_root_flags(&dest->root_item);
4482 btrfs_set_root_flags(&dest->root_item,
4483 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4484 spin_unlock(&dest->root_item_lock);
4486 down_write(&fs_info->subvol_sem);
4488 ret = may_destroy_subvol(dest);
4492 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4494 * One for dir inode,
4495 * two for dir entries,
4496 * two for root ref/backref.
4498 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4502 trans = btrfs_start_transaction(root, 0);
4503 if (IS_ERR(trans)) {
4504 ret = PTR_ERR(trans);
4507 trans->block_rsv = &block_rsv;
4508 trans->bytes_reserved = block_rsv.size;
4510 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4512 ret = btrfs_unlink_subvol(trans, dir, dentry);
4514 btrfs_abort_transaction(trans, ret);
4518 ret = btrfs_record_root_in_trans(trans, dest);
4520 btrfs_abort_transaction(trans, ret);
4524 memset(&dest->root_item.drop_progress, 0,
4525 sizeof(dest->root_item.drop_progress));
4526 btrfs_set_root_drop_level(&dest->root_item, 0);
4527 btrfs_set_root_refs(&dest->root_item, 0);
4529 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4530 ret = btrfs_insert_orphan_item(trans,
4532 dest->root_key.objectid);
4534 btrfs_abort_transaction(trans, ret);
4539 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4540 BTRFS_UUID_KEY_SUBVOL,
4541 dest->root_key.objectid);
4542 if (ret && ret != -ENOENT) {
4543 btrfs_abort_transaction(trans, ret);
4546 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4547 ret = btrfs_uuid_tree_remove(trans,
4548 dest->root_item.received_uuid,
4549 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4550 dest->root_key.objectid);
4551 if (ret && ret != -ENOENT) {
4552 btrfs_abort_transaction(trans, ret);
4557 free_anon_bdev(dest->anon_dev);
4560 trans->block_rsv = NULL;
4561 trans->bytes_reserved = 0;
4562 ret = btrfs_end_transaction(trans);
4563 inode->i_flags |= S_DEAD;
4565 btrfs_subvolume_release_metadata(root, &block_rsv);
4567 up_write(&fs_info->subvol_sem);
4569 spin_lock(&dest->root_item_lock);
4570 root_flags = btrfs_root_flags(&dest->root_item);
4571 btrfs_set_root_flags(&dest->root_item,
4572 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4573 spin_unlock(&dest->root_item_lock);
4575 d_invalidate(dentry);
4576 btrfs_prune_dentries(dest);
4577 ASSERT(dest->send_in_progress == 0);
4583 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4585 struct inode *inode = d_inode(dentry);
4586 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4588 struct btrfs_trans_handle *trans;
4589 u64 last_unlink_trans;
4591 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4593 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4594 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4596 "extent tree v2 doesn't support snapshot deletion yet");
4599 return btrfs_delete_subvolume(dir, dentry);
4602 trans = __unlink_start_trans(dir);
4604 return PTR_ERR(trans);
4606 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4607 err = btrfs_unlink_subvol(trans, dir, dentry);
4611 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4615 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4617 /* now the directory is empty */
4618 err = btrfs_unlink_inode(trans, BTRFS_I(dir),
4619 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4620 dentry->d_name.len);
4622 btrfs_i_size_write(BTRFS_I(inode), 0);
4624 * Propagate the last_unlink_trans value of the deleted dir to
4625 * its parent directory. This is to prevent an unrecoverable
4626 * log tree in the case we do something like this:
4628 * 2) create snapshot under dir foo
4629 * 3) delete the snapshot
4632 * 6) fsync foo or some file inside foo
4634 if (last_unlink_trans >= trans->transid)
4635 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4638 btrfs_end_transaction(trans);
4639 btrfs_btree_balance_dirty(fs_info);
4645 * btrfs_truncate_block - read, zero a chunk and write a block
4646 * @inode - inode that we're zeroing
4647 * @from - the offset to start zeroing
4648 * @len - the length to zero, 0 to zero the entire range respective to the
4650 * @front - zero up to the offset instead of from the offset on
4652 * This will find the block for the "from" offset and cow the block and zero the
4653 * part we want to zero. This is used with truncate and hole punching.
4655 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4658 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4659 struct address_space *mapping = inode->vfs_inode.i_mapping;
4660 struct extent_io_tree *io_tree = &inode->io_tree;
4661 struct btrfs_ordered_extent *ordered;
4662 struct extent_state *cached_state = NULL;
4663 struct extent_changeset *data_reserved = NULL;
4664 bool only_release_metadata = false;
4665 u32 blocksize = fs_info->sectorsize;
4666 pgoff_t index = from >> PAGE_SHIFT;
4667 unsigned offset = from & (blocksize - 1);
4669 gfp_t mask = btrfs_alloc_write_mask(mapping);
4670 size_t write_bytes = blocksize;
4675 if (IS_ALIGNED(offset, blocksize) &&
4676 (!len || IS_ALIGNED(len, blocksize)))
4679 block_start = round_down(from, blocksize);
4680 block_end = block_start + blocksize - 1;
4682 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4685 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
4686 /* For nocow case, no need to reserve data space */
4687 only_release_metadata = true;
4692 ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
4694 if (!only_release_metadata)
4695 btrfs_free_reserved_data_space(inode, data_reserved,
4696 block_start, blocksize);
4700 page = find_or_create_page(mapping, index, mask);
4702 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4704 btrfs_delalloc_release_extents(inode, blocksize);
4708 ret = set_page_extent_mapped(page);
4712 if (!PageUptodate(page)) {
4713 ret = btrfs_readpage(NULL, page);
4715 if (page->mapping != mapping) {
4720 if (!PageUptodate(page)) {
4725 wait_on_page_writeback(page);
4727 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4729 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4731 unlock_extent_cached(io_tree, block_start, block_end,
4735 btrfs_start_ordered_extent(ordered, 1);
4736 btrfs_put_ordered_extent(ordered);
4740 clear_extent_bit(&inode->io_tree, block_start, block_end,
4741 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4742 0, 0, &cached_state);
4744 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4747 unlock_extent_cached(io_tree, block_start, block_end,
4752 if (offset != blocksize) {
4754 len = blocksize - offset;
4756 memzero_page(page, (block_start - page_offset(page)),
4759 memzero_page(page, (block_start - page_offset(page)) + offset,
4761 flush_dcache_page(page);
4763 btrfs_page_clear_checked(fs_info, page, block_start,
4764 block_end + 1 - block_start);
4765 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
4766 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4768 if (only_release_metadata)
4769 set_extent_bit(&inode->io_tree, block_start, block_end,
4770 EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
4774 if (only_release_metadata)
4775 btrfs_delalloc_release_metadata(inode, blocksize, true);
4777 btrfs_delalloc_release_space(inode, data_reserved,
4778 block_start, blocksize, true);
4780 btrfs_delalloc_release_extents(inode, blocksize);
4784 if (only_release_metadata)
4785 btrfs_check_nocow_unlock(inode);
4786 extent_changeset_free(data_reserved);
4790 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4791 u64 offset, u64 len)
4793 struct btrfs_fs_info *fs_info = root->fs_info;
4794 struct btrfs_trans_handle *trans;
4795 struct btrfs_drop_extents_args drop_args = { 0 };
4799 * If NO_HOLES is enabled, we don't need to do anything.
4800 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
4801 * or btrfs_update_inode() will be called, which guarantee that the next
4802 * fsync will know this inode was changed and needs to be logged.
4804 if (btrfs_fs_incompat(fs_info, NO_HOLES))
4808 * 1 - for the one we're dropping
4809 * 1 - for the one we're adding
4810 * 1 - for updating the inode.
4812 trans = btrfs_start_transaction(root, 3);
4814 return PTR_ERR(trans);
4816 drop_args.start = offset;
4817 drop_args.end = offset + len;
4818 drop_args.drop_cache = true;
4820 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4822 btrfs_abort_transaction(trans, ret);
4823 btrfs_end_transaction(trans);
4827 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
4828 offset, 0, 0, len, 0, len, 0, 0, 0);
4830 btrfs_abort_transaction(trans, ret);
4832 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
4833 btrfs_update_inode(trans, root, inode);
4835 btrfs_end_transaction(trans);
4840 * This function puts in dummy file extents for the area we're creating a hole
4841 * for. So if we are truncating this file to a larger size we need to insert
4842 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4843 * the range between oldsize and size
4845 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
4847 struct btrfs_root *root = inode->root;
4848 struct btrfs_fs_info *fs_info = root->fs_info;
4849 struct extent_io_tree *io_tree = &inode->io_tree;
4850 struct extent_map *em = NULL;
4851 struct extent_state *cached_state = NULL;
4852 struct extent_map_tree *em_tree = &inode->extent_tree;
4853 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4854 u64 block_end = ALIGN(size, fs_info->sectorsize);
4861 * If our size started in the middle of a block we need to zero out the
4862 * rest of the block before we expand the i_size, otherwise we could
4863 * expose stale data.
4865 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4869 if (size <= hole_start)
4872 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
4874 cur_offset = hole_start;
4876 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4877 block_end - cur_offset);
4883 last_byte = min(extent_map_end(em), block_end);
4884 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4885 hole_size = last_byte - cur_offset;
4887 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4888 struct extent_map *hole_em;
4890 err = maybe_insert_hole(root, inode, cur_offset,
4895 err = btrfs_inode_set_file_extent_range(inode,
4896 cur_offset, hole_size);
4900 btrfs_drop_extent_cache(inode, cur_offset,
4901 cur_offset + hole_size - 1, 0);
4902 hole_em = alloc_extent_map();
4904 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4905 &inode->runtime_flags);
4908 hole_em->start = cur_offset;
4909 hole_em->len = hole_size;
4910 hole_em->orig_start = cur_offset;
4912 hole_em->block_start = EXTENT_MAP_HOLE;
4913 hole_em->block_len = 0;
4914 hole_em->orig_block_len = 0;
4915 hole_em->ram_bytes = hole_size;
4916 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4917 hole_em->generation = fs_info->generation;
4920 write_lock(&em_tree->lock);
4921 err = add_extent_mapping(em_tree, hole_em, 1);
4922 write_unlock(&em_tree->lock);
4925 btrfs_drop_extent_cache(inode, cur_offset,
4929 free_extent_map(hole_em);
4931 err = btrfs_inode_set_file_extent_range(inode,
4932 cur_offset, hole_size);
4937 free_extent_map(em);
4939 cur_offset = last_byte;
4940 if (cur_offset >= block_end)
4943 free_extent_map(em);
4944 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4948 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4950 struct btrfs_root *root = BTRFS_I(inode)->root;
4951 struct btrfs_trans_handle *trans;
4952 loff_t oldsize = i_size_read(inode);
4953 loff_t newsize = attr->ia_size;
4954 int mask = attr->ia_valid;
4958 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4959 * special case where we need to update the times despite not having
4960 * these flags set. For all other operations the VFS set these flags
4961 * explicitly if it wants a timestamp update.
4963 if (newsize != oldsize) {
4964 inode_inc_iversion(inode);
4965 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4966 inode->i_ctime = inode->i_mtime =
4967 current_time(inode);
4970 if (newsize > oldsize) {
4972 * Don't do an expanding truncate while snapshotting is ongoing.
4973 * This is to ensure the snapshot captures a fully consistent
4974 * state of this file - if the snapshot captures this expanding
4975 * truncation, it must capture all writes that happened before
4978 btrfs_drew_write_lock(&root->snapshot_lock);
4979 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
4981 btrfs_drew_write_unlock(&root->snapshot_lock);
4985 trans = btrfs_start_transaction(root, 1);
4986 if (IS_ERR(trans)) {
4987 btrfs_drew_write_unlock(&root->snapshot_lock);
4988 return PTR_ERR(trans);
4991 i_size_write(inode, newsize);
4992 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
4993 pagecache_isize_extended(inode, oldsize, newsize);
4994 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
4995 btrfs_drew_write_unlock(&root->snapshot_lock);
4996 btrfs_end_transaction(trans);
4998 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5000 if (btrfs_is_zoned(fs_info)) {
5001 ret = btrfs_wait_ordered_range(inode,
5002 ALIGN(newsize, fs_info->sectorsize),
5009 * We're truncating a file that used to have good data down to
5010 * zero. Make sure any new writes to the file get on disk
5014 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5015 &BTRFS_I(inode)->runtime_flags);
5017 truncate_setsize(inode, newsize);
5019 inode_dio_wait(inode);
5021 ret = btrfs_truncate(inode, newsize == oldsize);
5022 if (ret && inode->i_nlink) {
5026 * Truncate failed, so fix up the in-memory size. We
5027 * adjusted disk_i_size down as we removed extents, so
5028 * wait for disk_i_size to be stable and then update the
5029 * in-memory size to match.
5031 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5034 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5041 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5044 struct inode *inode = d_inode(dentry);
5045 struct btrfs_root *root = BTRFS_I(inode)->root;
5048 if (btrfs_root_readonly(root))
5051 err = setattr_prepare(mnt_userns, dentry, attr);
5055 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5056 err = btrfs_setsize(inode, attr);
5061 if (attr->ia_valid) {
5062 setattr_copy(mnt_userns, inode, attr);
5063 inode_inc_iversion(inode);
5064 err = btrfs_dirty_inode(inode);
5066 if (!err && attr->ia_valid & ATTR_MODE)
5067 err = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5074 * While truncating the inode pages during eviction, we get the VFS calling
5075 * btrfs_invalidatepage() against each page of the inode. This is slow because
5076 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5077 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5078 * extent_state structures over and over, wasting lots of time.
5080 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5081 * those expensive operations on a per page basis and do only the ordered io
5082 * finishing, while we release here the extent_map and extent_state structures,
5083 * without the excessive merging and splitting.
5085 static void evict_inode_truncate_pages(struct inode *inode)
5087 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5088 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5089 struct rb_node *node;
5091 ASSERT(inode->i_state & I_FREEING);
5092 truncate_inode_pages_final(&inode->i_data);
5094 write_lock(&map_tree->lock);
5095 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5096 struct extent_map *em;
5098 node = rb_first_cached(&map_tree->map);
5099 em = rb_entry(node, struct extent_map, rb_node);
5100 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5101 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5102 remove_extent_mapping(map_tree, em);
5103 free_extent_map(em);
5104 if (need_resched()) {
5105 write_unlock(&map_tree->lock);
5107 write_lock(&map_tree->lock);
5110 write_unlock(&map_tree->lock);
5113 * Keep looping until we have no more ranges in the io tree.
5114 * We can have ongoing bios started by readahead that have
5115 * their endio callback (extent_io.c:end_bio_extent_readpage)
5116 * still in progress (unlocked the pages in the bio but did not yet
5117 * unlocked the ranges in the io tree). Therefore this means some
5118 * ranges can still be locked and eviction started because before
5119 * submitting those bios, which are executed by a separate task (work
5120 * queue kthread), inode references (inode->i_count) were not taken
5121 * (which would be dropped in the end io callback of each bio).
5122 * Therefore here we effectively end up waiting for those bios and
5123 * anyone else holding locked ranges without having bumped the inode's
5124 * reference count - if we don't do it, when they access the inode's
5125 * io_tree to unlock a range it may be too late, leading to an
5126 * use-after-free issue.
5128 spin_lock(&io_tree->lock);
5129 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5130 struct extent_state *state;
5131 struct extent_state *cached_state = NULL;
5134 unsigned state_flags;
5136 node = rb_first(&io_tree->state);
5137 state = rb_entry(node, struct extent_state, rb_node);
5138 start = state->start;
5140 state_flags = state->state;
5141 spin_unlock(&io_tree->lock);
5143 lock_extent_bits(io_tree, start, end, &cached_state);
5146 * If still has DELALLOC flag, the extent didn't reach disk,
5147 * and its reserved space won't be freed by delayed_ref.
5148 * So we need to free its reserved space here.
5149 * (Refer to comment in btrfs_invalidatepage, case 2)
5151 * Note, end is the bytenr of last byte, so we need + 1 here.
5153 if (state_flags & EXTENT_DELALLOC)
5154 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5157 clear_extent_bit(io_tree, start, end,
5158 EXTENT_LOCKED | EXTENT_DELALLOC |
5159 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5163 spin_lock(&io_tree->lock);
5165 spin_unlock(&io_tree->lock);
5168 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5169 struct btrfs_block_rsv *rsv)
5171 struct btrfs_fs_info *fs_info = root->fs_info;
5172 struct btrfs_trans_handle *trans;
5173 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5177 * Eviction should be taking place at some place safe because of our
5178 * delayed iputs. However the normal flushing code will run delayed
5179 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5181 * We reserve the delayed_refs_extra here again because we can't use
5182 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5183 * above. We reserve our extra bit here because we generate a ton of
5184 * delayed refs activity by truncating.
5186 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5187 * if we fail to make this reservation we can re-try without the
5188 * delayed_refs_extra so we can make some forward progress.
5190 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5191 BTRFS_RESERVE_FLUSH_EVICT);
5193 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5194 BTRFS_RESERVE_FLUSH_EVICT);
5197 "could not allocate space for delete; will truncate on mount");
5198 return ERR_PTR(-ENOSPC);
5200 delayed_refs_extra = 0;
5203 trans = btrfs_join_transaction(root);
5207 if (delayed_refs_extra) {
5208 trans->block_rsv = &fs_info->trans_block_rsv;
5209 trans->bytes_reserved = delayed_refs_extra;
5210 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5211 delayed_refs_extra, 1);
5216 void btrfs_evict_inode(struct inode *inode)
5218 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5219 struct btrfs_trans_handle *trans;
5220 struct btrfs_root *root = BTRFS_I(inode)->root;
5221 struct btrfs_block_rsv *rsv;
5224 trace_btrfs_inode_evict(inode);
5227 fsverity_cleanup_inode(inode);
5232 evict_inode_truncate_pages(inode);
5234 if (inode->i_nlink &&
5235 ((btrfs_root_refs(&root->root_item) != 0 &&
5236 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5237 btrfs_is_free_space_inode(BTRFS_I(inode))))
5240 if (is_bad_inode(inode))
5243 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5245 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5248 if (inode->i_nlink > 0) {
5249 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5250 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5255 * This makes sure the inode item in tree is uptodate and the space for
5256 * the inode update is released.
5258 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5263 * This drops any pending insert or delete operations we have for this
5264 * inode. We could have a delayed dir index deletion queued up, but
5265 * we're removing the inode completely so that'll be taken care of in
5268 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5270 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5273 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5276 btrfs_i_size_write(BTRFS_I(inode), 0);
5279 struct btrfs_truncate_control control = {
5280 .inode = BTRFS_I(inode),
5281 .ino = btrfs_ino(BTRFS_I(inode)),
5286 trans = evict_refill_and_join(root, rsv);
5290 trans->block_rsv = rsv;
5292 ret = btrfs_truncate_inode_items(trans, root, &control);
5293 trans->block_rsv = &fs_info->trans_block_rsv;
5294 btrfs_end_transaction(trans);
5295 btrfs_btree_balance_dirty(fs_info);
5296 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5303 * Errors here aren't a big deal, it just means we leave orphan items in
5304 * the tree. They will be cleaned up on the next mount. If the inode
5305 * number gets reused, cleanup deletes the orphan item without doing
5306 * anything, and unlink reuses the existing orphan item.
5308 * If it turns out that we are dropping too many of these, we might want
5309 * to add a mechanism for retrying these after a commit.
5311 trans = evict_refill_and_join(root, rsv);
5312 if (!IS_ERR(trans)) {
5313 trans->block_rsv = rsv;
5314 btrfs_orphan_del(trans, BTRFS_I(inode));
5315 trans->block_rsv = &fs_info->trans_block_rsv;
5316 btrfs_end_transaction(trans);
5320 btrfs_free_block_rsv(fs_info, rsv);
5323 * If we didn't successfully delete, the orphan item will still be in
5324 * the tree and we'll retry on the next mount. Again, we might also want
5325 * to retry these periodically in the future.
5327 btrfs_remove_delayed_node(BTRFS_I(inode));
5328 fsverity_cleanup_inode(inode);
5333 * Return the key found in the dir entry in the location pointer, fill @type
5334 * with BTRFS_FT_*, and return 0.
5336 * If no dir entries were found, returns -ENOENT.
5337 * If found a corrupted location in dir entry, returns -EUCLEAN.
5339 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5340 struct btrfs_key *location, u8 *type)
5342 const char *name = dentry->d_name.name;
5343 int namelen = dentry->d_name.len;
5344 struct btrfs_dir_item *di;
5345 struct btrfs_path *path;
5346 struct btrfs_root *root = BTRFS_I(dir)->root;
5349 path = btrfs_alloc_path();
5353 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5355 if (IS_ERR_OR_NULL(di)) {
5356 ret = di ? PTR_ERR(di) : -ENOENT;
5360 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5361 if (location->type != BTRFS_INODE_ITEM_KEY &&
5362 location->type != BTRFS_ROOT_ITEM_KEY) {
5364 btrfs_warn(root->fs_info,
5365 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5366 __func__, name, btrfs_ino(BTRFS_I(dir)),
5367 location->objectid, location->type, location->offset);
5370 *type = btrfs_dir_type(path->nodes[0], di);
5372 btrfs_free_path(path);
5377 * when we hit a tree root in a directory, the btrfs part of the inode
5378 * needs to be changed to reflect the root directory of the tree root. This
5379 * is kind of like crossing a mount point.
5381 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5383 struct dentry *dentry,
5384 struct btrfs_key *location,
5385 struct btrfs_root **sub_root)
5387 struct btrfs_path *path;
5388 struct btrfs_root *new_root;
5389 struct btrfs_root_ref *ref;
5390 struct extent_buffer *leaf;
5391 struct btrfs_key key;
5395 path = btrfs_alloc_path();
5402 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5403 key.type = BTRFS_ROOT_REF_KEY;
5404 key.offset = location->objectid;
5406 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5413 leaf = path->nodes[0];
5414 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5415 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5416 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5419 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5420 (unsigned long)(ref + 1),
5421 dentry->d_name.len);
5425 btrfs_release_path(path);
5427 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5428 if (IS_ERR(new_root)) {
5429 err = PTR_ERR(new_root);
5433 *sub_root = new_root;
5434 location->objectid = btrfs_root_dirid(&new_root->root_item);
5435 location->type = BTRFS_INODE_ITEM_KEY;
5436 location->offset = 0;
5439 btrfs_free_path(path);
5443 static void inode_tree_add(struct inode *inode)
5445 struct btrfs_root *root = BTRFS_I(inode)->root;
5446 struct btrfs_inode *entry;
5448 struct rb_node *parent;
5449 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5450 u64 ino = btrfs_ino(BTRFS_I(inode));
5452 if (inode_unhashed(inode))
5455 spin_lock(&root->inode_lock);
5456 p = &root->inode_tree.rb_node;
5459 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5461 if (ino < btrfs_ino(entry))
5462 p = &parent->rb_left;
5463 else if (ino > btrfs_ino(entry))
5464 p = &parent->rb_right;
5466 WARN_ON(!(entry->vfs_inode.i_state &
5467 (I_WILL_FREE | I_FREEING)));
5468 rb_replace_node(parent, new, &root->inode_tree);
5469 RB_CLEAR_NODE(parent);
5470 spin_unlock(&root->inode_lock);
5474 rb_link_node(new, parent, p);
5475 rb_insert_color(new, &root->inode_tree);
5476 spin_unlock(&root->inode_lock);
5479 static void inode_tree_del(struct btrfs_inode *inode)
5481 struct btrfs_root *root = inode->root;
5484 spin_lock(&root->inode_lock);
5485 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5486 rb_erase(&inode->rb_node, &root->inode_tree);
5487 RB_CLEAR_NODE(&inode->rb_node);
5488 empty = RB_EMPTY_ROOT(&root->inode_tree);
5490 spin_unlock(&root->inode_lock);
5492 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5493 spin_lock(&root->inode_lock);
5494 empty = RB_EMPTY_ROOT(&root->inode_tree);
5495 spin_unlock(&root->inode_lock);
5497 btrfs_add_dead_root(root);
5502 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5504 struct btrfs_iget_args *args = p;
5506 inode->i_ino = args->ino;
5507 BTRFS_I(inode)->location.objectid = args->ino;
5508 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5509 BTRFS_I(inode)->location.offset = 0;
5510 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5511 BUG_ON(args->root && !BTRFS_I(inode)->root);
5515 static int btrfs_find_actor(struct inode *inode, void *opaque)
5517 struct btrfs_iget_args *args = opaque;
5519 return args->ino == BTRFS_I(inode)->location.objectid &&
5520 args->root == BTRFS_I(inode)->root;
5523 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5524 struct btrfs_root *root)
5526 struct inode *inode;
5527 struct btrfs_iget_args args;
5528 unsigned long hashval = btrfs_inode_hash(ino, root);
5533 inode = iget5_locked(s, hashval, btrfs_find_actor,
5534 btrfs_init_locked_inode,
5540 * Get an inode object given its inode number and corresponding root.
5541 * Path can be preallocated to prevent recursing back to iget through
5542 * allocator. NULL is also valid but may require an additional allocation
5545 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5546 struct btrfs_root *root, struct btrfs_path *path)
5548 struct inode *inode;
5550 inode = btrfs_iget_locked(s, ino, root);
5552 return ERR_PTR(-ENOMEM);
5554 if (inode->i_state & I_NEW) {
5557 ret = btrfs_read_locked_inode(inode, path);
5559 inode_tree_add(inode);
5560 unlock_new_inode(inode);
5564 * ret > 0 can come from btrfs_search_slot called by
5565 * btrfs_read_locked_inode, this means the inode item
5570 inode = ERR_PTR(ret);
5577 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5579 return btrfs_iget_path(s, ino, root, NULL);
5582 static struct inode *new_simple_dir(struct super_block *s,
5583 struct btrfs_key *key,
5584 struct btrfs_root *root)
5586 struct inode *inode = new_inode(s);
5589 return ERR_PTR(-ENOMEM);
5591 BTRFS_I(inode)->root = btrfs_grab_root(root);
5592 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5593 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5595 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5597 * We only need lookup, the rest is read-only and there's no inode
5598 * associated with the dentry
5600 inode->i_op = &simple_dir_inode_operations;
5601 inode->i_opflags &= ~IOP_XATTR;
5602 inode->i_fop = &simple_dir_operations;
5603 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5604 inode->i_mtime = current_time(inode);
5605 inode->i_atime = inode->i_mtime;
5606 inode->i_ctime = inode->i_mtime;
5607 BTRFS_I(inode)->i_otime = inode->i_mtime;
5612 static inline u8 btrfs_inode_type(struct inode *inode)
5615 * Compile-time asserts that generic FT_* types still match
5618 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5619 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5620 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5621 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5622 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5623 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5624 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5625 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5627 return fs_umode_to_ftype(inode->i_mode);
5630 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5632 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5633 struct inode *inode;
5634 struct btrfs_root *root = BTRFS_I(dir)->root;
5635 struct btrfs_root *sub_root = root;
5636 struct btrfs_key location;
5640 if (dentry->d_name.len > BTRFS_NAME_LEN)
5641 return ERR_PTR(-ENAMETOOLONG);
5643 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5645 return ERR_PTR(ret);
5647 if (location.type == BTRFS_INODE_ITEM_KEY) {
5648 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5652 /* Do extra check against inode mode with di_type */
5653 if (btrfs_inode_type(inode) != di_type) {
5655 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5656 inode->i_mode, btrfs_inode_type(inode),
5659 return ERR_PTR(-EUCLEAN);
5664 ret = fixup_tree_root_location(fs_info, dir, dentry,
5665 &location, &sub_root);
5668 inode = ERR_PTR(ret);
5670 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5672 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5674 if (root != sub_root)
5675 btrfs_put_root(sub_root);
5677 if (!IS_ERR(inode) && root != sub_root) {
5678 down_read(&fs_info->cleanup_work_sem);
5679 if (!sb_rdonly(inode->i_sb))
5680 ret = btrfs_orphan_cleanup(sub_root);
5681 up_read(&fs_info->cleanup_work_sem);
5684 inode = ERR_PTR(ret);
5691 static int btrfs_dentry_delete(const struct dentry *dentry)
5693 struct btrfs_root *root;
5694 struct inode *inode = d_inode(dentry);
5696 if (!inode && !IS_ROOT(dentry))
5697 inode = d_inode(dentry->d_parent);
5700 root = BTRFS_I(inode)->root;
5701 if (btrfs_root_refs(&root->root_item) == 0)
5704 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5710 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5713 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5715 if (inode == ERR_PTR(-ENOENT))
5717 return d_splice_alias(inode, dentry);
5721 * All this infrastructure exists because dir_emit can fault, and we are holding
5722 * the tree lock when doing readdir. For now just allocate a buffer and copy
5723 * our information into that, and then dir_emit from the buffer. This is
5724 * similar to what NFS does, only we don't keep the buffer around in pagecache
5725 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5726 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5729 static int btrfs_opendir(struct inode *inode, struct file *file)
5731 struct btrfs_file_private *private;
5733 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5736 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5737 if (!private->filldir_buf) {
5741 file->private_data = private;
5752 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5755 struct dir_entry *entry = addr;
5756 char *name = (char *)(entry + 1);
5758 ctx->pos = get_unaligned(&entry->offset);
5759 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5760 get_unaligned(&entry->ino),
5761 get_unaligned(&entry->type)))
5763 addr += sizeof(struct dir_entry) +
5764 get_unaligned(&entry->name_len);
5770 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5772 struct inode *inode = file_inode(file);
5773 struct btrfs_root *root = BTRFS_I(inode)->root;
5774 struct btrfs_file_private *private = file->private_data;
5775 struct btrfs_dir_item *di;
5776 struct btrfs_key key;
5777 struct btrfs_key found_key;
5778 struct btrfs_path *path;
5780 struct list_head ins_list;
5781 struct list_head del_list;
5783 struct extent_buffer *leaf;
5790 struct btrfs_key location;
5792 if (!dir_emit_dots(file, ctx))
5795 path = btrfs_alloc_path();
5799 addr = private->filldir_buf;
5800 path->reada = READA_FORWARD;
5802 INIT_LIST_HEAD(&ins_list);
5803 INIT_LIST_HEAD(&del_list);
5804 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5807 key.type = BTRFS_DIR_INDEX_KEY;
5808 key.offset = ctx->pos;
5809 key.objectid = btrfs_ino(BTRFS_I(inode));
5811 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5816 struct dir_entry *entry;
5818 leaf = path->nodes[0];
5819 slot = path->slots[0];
5820 if (slot >= btrfs_header_nritems(leaf)) {
5821 ret = btrfs_next_leaf(root, path);
5829 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5831 if (found_key.objectid != key.objectid)
5833 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5835 if (found_key.offset < ctx->pos)
5837 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5839 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5840 name_len = btrfs_dir_name_len(leaf, di);
5841 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5843 btrfs_release_path(path);
5844 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5847 addr = private->filldir_buf;
5854 put_unaligned(name_len, &entry->name_len);
5855 name_ptr = (char *)(entry + 1);
5856 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5858 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5860 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5861 put_unaligned(location.objectid, &entry->ino);
5862 put_unaligned(found_key.offset, &entry->offset);
5864 addr += sizeof(struct dir_entry) + name_len;
5865 total_len += sizeof(struct dir_entry) + name_len;
5869 btrfs_release_path(path);
5871 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5875 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5880 * Stop new entries from being returned after we return the last
5883 * New directory entries are assigned a strictly increasing
5884 * offset. This means that new entries created during readdir
5885 * are *guaranteed* to be seen in the future by that readdir.
5886 * This has broken buggy programs which operate on names as
5887 * they're returned by readdir. Until we re-use freed offsets
5888 * we have this hack to stop new entries from being returned
5889 * under the assumption that they'll never reach this huge
5892 * This is being careful not to overflow 32bit loff_t unless the
5893 * last entry requires it because doing so has broken 32bit apps
5896 if (ctx->pos >= INT_MAX)
5897 ctx->pos = LLONG_MAX;
5904 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5905 btrfs_free_path(path);
5910 * This is somewhat expensive, updating the tree every time the
5911 * inode changes. But, it is most likely to find the inode in cache.
5912 * FIXME, needs more benchmarking...there are no reasons other than performance
5913 * to keep or drop this code.
5915 static int btrfs_dirty_inode(struct inode *inode)
5917 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5918 struct btrfs_root *root = BTRFS_I(inode)->root;
5919 struct btrfs_trans_handle *trans;
5922 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5925 trans = btrfs_join_transaction(root);
5927 return PTR_ERR(trans);
5929 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5930 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
5931 /* whoops, lets try again with the full transaction */
5932 btrfs_end_transaction(trans);
5933 trans = btrfs_start_transaction(root, 1);
5935 return PTR_ERR(trans);
5937 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5939 btrfs_end_transaction(trans);
5940 if (BTRFS_I(inode)->delayed_node)
5941 btrfs_balance_delayed_items(fs_info);
5947 * This is a copy of file_update_time. We need this so we can return error on
5948 * ENOSPC for updating the inode in the case of file write and mmap writes.
5950 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5953 struct btrfs_root *root = BTRFS_I(inode)->root;
5954 bool dirty = flags & ~S_VERSION;
5956 if (btrfs_root_readonly(root))
5959 if (flags & S_VERSION)
5960 dirty |= inode_maybe_inc_iversion(inode, dirty);
5961 if (flags & S_CTIME)
5962 inode->i_ctime = *now;
5963 if (flags & S_MTIME)
5964 inode->i_mtime = *now;
5965 if (flags & S_ATIME)
5966 inode->i_atime = *now;
5967 return dirty ? btrfs_dirty_inode(inode) : 0;
5971 * find the highest existing sequence number in a directory
5972 * and then set the in-memory index_cnt variable to reflect
5973 * free sequence numbers
5975 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5977 struct btrfs_root *root = inode->root;
5978 struct btrfs_key key, found_key;
5979 struct btrfs_path *path;
5980 struct extent_buffer *leaf;
5983 key.objectid = btrfs_ino(inode);
5984 key.type = BTRFS_DIR_INDEX_KEY;
5985 key.offset = (u64)-1;
5987 path = btrfs_alloc_path();
5991 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5994 /* FIXME: we should be able to handle this */
5999 if (path->slots[0] == 0) {
6000 inode->index_cnt = BTRFS_DIR_START_INDEX;
6006 leaf = path->nodes[0];
6007 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6009 if (found_key.objectid != btrfs_ino(inode) ||
6010 found_key.type != BTRFS_DIR_INDEX_KEY) {
6011 inode->index_cnt = BTRFS_DIR_START_INDEX;
6015 inode->index_cnt = found_key.offset + 1;
6017 btrfs_free_path(path);
6022 * helper to find a free sequence number in a given directory. This current
6023 * code is very simple, later versions will do smarter things in the btree
6025 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6029 if (dir->index_cnt == (u64)-1) {
6030 ret = btrfs_inode_delayed_dir_index_count(dir);
6032 ret = btrfs_set_inode_index_count(dir);
6038 *index = dir->index_cnt;
6044 static int btrfs_insert_inode_locked(struct inode *inode)
6046 struct btrfs_iget_args args;
6048 args.ino = BTRFS_I(inode)->location.objectid;
6049 args.root = BTRFS_I(inode)->root;
6051 return insert_inode_locked4(inode,
6052 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6053 btrfs_find_actor, &args);
6057 * Inherit flags from the parent inode.
6059 * Currently only the compression flags and the cow flags are inherited.
6061 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6068 flags = BTRFS_I(dir)->flags;
6070 if (flags & BTRFS_INODE_NOCOMPRESS) {
6071 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6072 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6073 } else if (flags & BTRFS_INODE_COMPRESS) {
6074 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6075 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6078 if (flags & BTRFS_INODE_NODATACOW) {
6079 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6080 if (S_ISREG(inode->i_mode))
6081 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6084 btrfs_sync_inode_flags_to_i_flags(inode);
6087 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6088 struct btrfs_root *root,
6089 struct user_namespace *mnt_userns,
6091 const char *name, int name_len,
6092 u64 ref_objectid, u64 objectid,
6093 umode_t mode, u64 *index)
6095 struct btrfs_fs_info *fs_info = root->fs_info;
6096 struct inode *inode;
6097 struct btrfs_inode_item *inode_item;
6098 struct btrfs_key *location;
6099 struct btrfs_path *path;
6100 struct btrfs_inode_ref *ref;
6101 struct btrfs_key key[2];
6103 struct btrfs_item_batch batch;
6105 unsigned int nofs_flag;
6108 path = btrfs_alloc_path();
6110 return ERR_PTR(-ENOMEM);
6112 nofs_flag = memalloc_nofs_save();
6113 inode = new_inode(fs_info->sb);
6114 memalloc_nofs_restore(nofs_flag);
6116 btrfs_free_path(path);
6117 return ERR_PTR(-ENOMEM);
6121 * O_TMPFILE, set link count to 0, so that after this point,
6122 * we fill in an inode item with the correct link count.
6125 set_nlink(inode, 0);
6128 * we have to initialize this early, so we can reclaim the inode
6129 * number if we fail afterwards in this function.
6131 inode->i_ino = objectid;
6134 trace_btrfs_inode_request(dir);
6136 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6138 btrfs_free_path(path);
6140 return ERR_PTR(ret);
6146 * index_cnt is ignored for everything but a dir,
6147 * btrfs_set_inode_index_count has an explanation for the magic
6150 BTRFS_I(inode)->index_cnt = 2;
6151 BTRFS_I(inode)->dir_index = *index;
6152 BTRFS_I(inode)->root = btrfs_grab_root(root);
6153 BTRFS_I(inode)->generation = trans->transid;
6154 inode->i_generation = BTRFS_I(inode)->generation;
6157 * We could have gotten an inode number from somebody who was fsynced
6158 * and then removed in this same transaction, so let's just set full
6159 * sync since it will be a full sync anyway and this will blow away the
6160 * old info in the log.
6162 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6164 key[0].objectid = objectid;
6165 key[0].type = BTRFS_INODE_ITEM_KEY;
6168 sizes[0] = sizeof(struct btrfs_inode_item);
6172 * Start new inodes with an inode_ref. This is slightly more
6173 * efficient for small numbers of hard links since they will
6174 * be packed into one item. Extended refs will kick in if we
6175 * add more hard links than can fit in the ref item.
6177 key[1].objectid = objectid;
6178 key[1].type = BTRFS_INODE_REF_KEY;
6179 key[1].offset = ref_objectid;
6181 sizes[1] = name_len + sizeof(*ref);
6184 location = &BTRFS_I(inode)->location;
6185 location->objectid = objectid;
6186 location->offset = 0;
6187 location->type = BTRFS_INODE_ITEM_KEY;
6189 ret = btrfs_insert_inode_locked(inode);
6195 batch.keys = &key[0];
6196 batch.data_sizes = &sizes[0];
6197 batch.total_data_size = sizes[0] + (name ? sizes[1] : 0);
6198 batch.nr = name ? 2 : 1;
6199 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6203 inode_init_owner(mnt_userns, inode, dir, mode);
6204 inode_set_bytes(inode, 0);
6206 inode->i_mtime = current_time(inode);
6207 inode->i_atime = inode->i_mtime;
6208 inode->i_ctime = inode->i_mtime;
6209 BTRFS_I(inode)->i_otime = inode->i_mtime;
6211 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6212 struct btrfs_inode_item);
6213 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6214 sizeof(*inode_item));
6215 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6218 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6219 struct btrfs_inode_ref);
6220 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6221 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6222 ptr = (unsigned long)(ref + 1);
6223 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6226 btrfs_mark_buffer_dirty(path->nodes[0]);
6227 btrfs_free_path(path);
6229 btrfs_inherit_iflags(inode, dir);
6231 if (S_ISREG(mode)) {
6232 if (btrfs_test_opt(fs_info, NODATASUM))
6233 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6234 if (btrfs_test_opt(fs_info, NODATACOW))
6235 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6236 BTRFS_INODE_NODATASUM;
6239 inode_tree_add(inode);
6241 trace_btrfs_inode_new(inode);
6242 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6244 btrfs_update_root_times(trans, root);
6246 ret = btrfs_inode_inherit_props(trans, inode, dir);
6249 "error inheriting props for ino %llu (root %llu): %d",
6250 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6255 discard_new_inode(inode);
6258 BTRFS_I(dir)->index_cnt--;
6259 btrfs_free_path(path);
6260 return ERR_PTR(ret);
6264 * utility function to add 'inode' into 'parent_inode' with
6265 * a give name and a given sequence number.
6266 * if 'add_backref' is true, also insert a backref from the
6267 * inode to the parent directory.
6269 int btrfs_add_link(struct btrfs_trans_handle *trans,
6270 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6271 const char *name, int name_len, int add_backref, u64 index)
6274 struct btrfs_key key;
6275 struct btrfs_root *root = parent_inode->root;
6276 u64 ino = btrfs_ino(inode);
6277 u64 parent_ino = btrfs_ino(parent_inode);
6279 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6280 memcpy(&key, &inode->root->root_key, sizeof(key));
6283 key.type = BTRFS_INODE_ITEM_KEY;
6287 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6288 ret = btrfs_add_root_ref(trans, key.objectid,
6289 root->root_key.objectid, parent_ino,
6290 index, name, name_len);
6291 } else if (add_backref) {
6292 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6296 /* Nothing to clean up yet */
6300 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6301 btrfs_inode_type(&inode->vfs_inode), index);
6302 if (ret == -EEXIST || ret == -EOVERFLOW)
6305 btrfs_abort_transaction(trans, ret);
6309 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6311 inode_inc_iversion(&parent_inode->vfs_inode);
6313 * If we are replaying a log tree, we do not want to update the mtime
6314 * and ctime of the parent directory with the current time, since the
6315 * log replay procedure is responsible for setting them to their correct
6316 * values (the ones it had when the fsync was done).
6318 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6319 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6321 parent_inode->vfs_inode.i_mtime = now;
6322 parent_inode->vfs_inode.i_ctime = now;
6324 ret = btrfs_update_inode(trans, root, parent_inode);
6326 btrfs_abort_transaction(trans, ret);
6330 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6333 err = btrfs_del_root_ref(trans, key.objectid,
6334 root->root_key.objectid, parent_ino,
6335 &local_index, name, name_len);
6337 btrfs_abort_transaction(trans, err);
6338 } else if (add_backref) {
6342 err = btrfs_del_inode_ref(trans, root, name, name_len,
6343 ino, parent_ino, &local_index);
6345 btrfs_abort_transaction(trans, err);
6348 /* Return the original error code */
6352 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6353 struct btrfs_inode *dir, struct dentry *dentry,
6354 struct btrfs_inode *inode, int backref, u64 index)
6356 int err = btrfs_add_link(trans, dir, inode,
6357 dentry->d_name.name, dentry->d_name.len,
6364 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6365 struct dentry *dentry, umode_t mode, dev_t rdev)
6367 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6368 struct btrfs_trans_handle *trans;
6369 struct btrfs_root *root = BTRFS_I(dir)->root;
6370 struct inode *inode = NULL;
6376 * 2 for inode item and ref
6378 * 1 for xattr if selinux is on
6380 trans = btrfs_start_transaction(root, 5);
6382 return PTR_ERR(trans);
6384 err = btrfs_get_free_objectid(root, &objectid);
6388 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6389 dentry->d_name.name, dentry->d_name.len,
6390 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
6391 if (IS_ERR(inode)) {
6392 err = PTR_ERR(inode);
6398 * If the active LSM wants to access the inode during
6399 * d_instantiate it needs these. Smack checks to see
6400 * if the filesystem supports xattrs by looking at the
6403 inode->i_op = &btrfs_special_inode_operations;
6404 init_special_inode(inode, inode->i_mode, rdev);
6406 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6410 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6415 btrfs_update_inode(trans, root, BTRFS_I(inode));
6416 d_instantiate_new(dentry, inode);
6419 btrfs_end_transaction(trans);
6420 btrfs_btree_balance_dirty(fs_info);
6422 inode_dec_link_count(inode);
6423 discard_new_inode(inode);
6428 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6429 struct dentry *dentry, umode_t mode, bool excl)
6431 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6432 struct btrfs_trans_handle *trans;
6433 struct btrfs_root *root = BTRFS_I(dir)->root;
6434 struct inode *inode = NULL;
6440 * 2 for inode item and ref
6442 * 1 for xattr if selinux is on
6444 trans = btrfs_start_transaction(root, 5);
6446 return PTR_ERR(trans);
6448 err = btrfs_get_free_objectid(root, &objectid);
6452 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6453 dentry->d_name.name, dentry->d_name.len,
6454 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
6455 if (IS_ERR(inode)) {
6456 err = PTR_ERR(inode);
6461 * If the active LSM wants to access the inode during
6462 * d_instantiate it needs these. Smack checks to see
6463 * if the filesystem supports xattrs by looking at the
6466 inode->i_fop = &btrfs_file_operations;
6467 inode->i_op = &btrfs_file_inode_operations;
6468 inode->i_mapping->a_ops = &btrfs_aops;
6470 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6474 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6478 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6483 d_instantiate_new(dentry, inode);
6486 btrfs_end_transaction(trans);
6488 inode_dec_link_count(inode);
6489 discard_new_inode(inode);
6491 btrfs_btree_balance_dirty(fs_info);
6495 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6496 struct dentry *dentry)
6498 struct btrfs_trans_handle *trans = NULL;
6499 struct btrfs_root *root = BTRFS_I(dir)->root;
6500 struct inode *inode = d_inode(old_dentry);
6501 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6506 /* do not allow sys_link's with other subvols of the same device */
6507 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6510 if (inode->i_nlink >= BTRFS_LINK_MAX)
6513 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6518 * 2 items for inode and inode ref
6519 * 2 items for dir items
6520 * 1 item for parent inode
6521 * 1 item for orphan item deletion if O_TMPFILE
6523 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6524 if (IS_ERR(trans)) {
6525 err = PTR_ERR(trans);
6530 /* There are several dir indexes for this inode, clear the cache. */
6531 BTRFS_I(inode)->dir_index = 0ULL;
6533 inode_inc_iversion(inode);
6534 inode->i_ctime = current_time(inode);
6536 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6538 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6544 struct dentry *parent = dentry->d_parent;
6546 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6549 if (inode->i_nlink == 1) {
6551 * If new hard link count is 1, it's a file created
6552 * with open(2) O_TMPFILE flag.
6554 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6558 d_instantiate(dentry, inode);
6559 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6564 btrfs_end_transaction(trans);
6566 inode_dec_link_count(inode);
6569 btrfs_btree_balance_dirty(fs_info);
6573 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6574 struct dentry *dentry, umode_t mode)
6576 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6577 struct inode *inode = NULL;
6578 struct btrfs_trans_handle *trans;
6579 struct btrfs_root *root = BTRFS_I(dir)->root;
6585 * 2 items for inode and ref
6586 * 2 items for dir items
6587 * 1 for xattr if selinux is on
6589 trans = btrfs_start_transaction(root, 5);
6591 return PTR_ERR(trans);
6593 err = btrfs_get_free_objectid(root, &objectid);
6597 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6598 dentry->d_name.name, dentry->d_name.len,
6599 btrfs_ino(BTRFS_I(dir)), objectid,
6600 S_IFDIR | mode, &index);
6601 if (IS_ERR(inode)) {
6602 err = PTR_ERR(inode);
6607 /* these must be set before we unlock the inode */
6608 inode->i_op = &btrfs_dir_inode_operations;
6609 inode->i_fop = &btrfs_dir_file_operations;
6611 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6615 btrfs_i_size_write(BTRFS_I(inode), 0);
6616 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6620 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6621 dentry->d_name.name,
6622 dentry->d_name.len, 0, index);
6626 d_instantiate_new(dentry, inode);
6629 btrfs_end_transaction(trans);
6631 inode_dec_link_count(inode);
6632 discard_new_inode(inode);
6634 btrfs_btree_balance_dirty(fs_info);
6638 static noinline int uncompress_inline(struct btrfs_path *path,
6640 size_t pg_offset, u64 extent_offset,
6641 struct btrfs_file_extent_item *item)
6644 struct extent_buffer *leaf = path->nodes[0];
6647 unsigned long inline_size;
6651 WARN_ON(pg_offset != 0);
6652 compress_type = btrfs_file_extent_compression(leaf, item);
6653 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6654 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6655 tmp = kmalloc(inline_size, GFP_NOFS);
6658 ptr = btrfs_file_extent_inline_start(item);
6660 read_extent_buffer(leaf, tmp, ptr, inline_size);
6662 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6663 ret = btrfs_decompress(compress_type, tmp, page,
6664 extent_offset, inline_size, max_size);
6667 * decompression code contains a memset to fill in any space between the end
6668 * of the uncompressed data and the end of max_size in case the decompressed
6669 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6670 * the end of an inline extent and the beginning of the next block, so we
6671 * cover that region here.
6674 if (max_size + pg_offset < PAGE_SIZE)
6675 memzero_page(page, pg_offset + max_size,
6676 PAGE_SIZE - max_size - pg_offset);
6682 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6683 * @inode: file to search in
6684 * @page: page to read extent data into if the extent is inline
6685 * @pg_offset: offset into @page to copy to
6686 * @start: file offset
6687 * @len: length of range starting at @start
6689 * This returns the first &struct extent_map which overlaps with the given
6690 * range, reading it from the B-tree and caching it if necessary. Note that
6691 * there may be more extents which overlap the given range after the returned
6694 * If @page is not NULL and the extent is inline, this also reads the extent
6695 * data directly into the page and marks the extent up to date in the io_tree.
6697 * Return: ERR_PTR on error, non-NULL extent_map on success.
6699 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6700 struct page *page, size_t pg_offset,
6703 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6705 u64 extent_start = 0;
6707 u64 objectid = btrfs_ino(inode);
6708 int extent_type = -1;
6709 struct btrfs_path *path = NULL;
6710 struct btrfs_root *root = inode->root;
6711 struct btrfs_file_extent_item *item;
6712 struct extent_buffer *leaf;
6713 struct btrfs_key found_key;
6714 struct extent_map *em = NULL;
6715 struct extent_map_tree *em_tree = &inode->extent_tree;
6716 struct extent_io_tree *io_tree = &inode->io_tree;
6718 read_lock(&em_tree->lock);
6719 em = lookup_extent_mapping(em_tree, start, len);
6720 read_unlock(&em_tree->lock);
6723 if (em->start > start || em->start + em->len <= start)
6724 free_extent_map(em);
6725 else if (em->block_start == EXTENT_MAP_INLINE && page)
6726 free_extent_map(em);
6730 em = alloc_extent_map();
6735 em->start = EXTENT_MAP_HOLE;
6736 em->orig_start = EXTENT_MAP_HOLE;
6738 em->block_len = (u64)-1;
6740 path = btrfs_alloc_path();
6746 /* Chances are we'll be called again, so go ahead and do readahead */
6747 path->reada = READA_FORWARD;
6750 * The same explanation in load_free_space_cache applies here as well,
6751 * we only read when we're loading the free space cache, and at that
6752 * point the commit_root has everything we need.
6754 if (btrfs_is_free_space_inode(inode)) {
6755 path->search_commit_root = 1;
6756 path->skip_locking = 1;
6759 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6762 } else if (ret > 0) {
6763 if (path->slots[0] == 0)
6769 leaf = path->nodes[0];
6770 item = btrfs_item_ptr(leaf, path->slots[0],
6771 struct btrfs_file_extent_item);
6772 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6773 if (found_key.objectid != objectid ||
6774 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6776 * If we backup past the first extent we want to move forward
6777 * and see if there is an extent in front of us, otherwise we'll
6778 * say there is a hole for our whole search range which can
6785 extent_type = btrfs_file_extent_type(leaf, item);
6786 extent_start = found_key.offset;
6787 extent_end = btrfs_file_extent_end(path);
6788 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6789 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6790 /* Only regular file could have regular/prealloc extent */
6791 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6794 "regular/prealloc extent found for non-regular inode %llu",
6798 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6800 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6801 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6806 if (start >= extent_end) {
6808 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6809 ret = btrfs_next_leaf(root, path);
6815 leaf = path->nodes[0];
6817 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6818 if (found_key.objectid != objectid ||
6819 found_key.type != BTRFS_EXTENT_DATA_KEY)
6821 if (start + len <= found_key.offset)
6823 if (start > found_key.offset)
6826 /* New extent overlaps with existing one */
6828 em->orig_start = start;
6829 em->len = found_key.offset - start;
6830 em->block_start = EXTENT_MAP_HOLE;
6834 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6836 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6837 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6839 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6843 size_t extent_offset;
6849 size = btrfs_file_extent_ram_bytes(leaf, item);
6850 extent_offset = page_offset(page) + pg_offset - extent_start;
6851 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6852 size - extent_offset);
6853 em->start = extent_start + extent_offset;
6854 em->len = ALIGN(copy_size, fs_info->sectorsize);
6855 em->orig_block_len = em->len;
6856 em->orig_start = em->start;
6857 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6859 if (!PageUptodate(page)) {
6860 if (btrfs_file_extent_compression(leaf, item) !=
6861 BTRFS_COMPRESS_NONE) {
6862 ret = uncompress_inline(path, page, pg_offset,
6863 extent_offset, item);
6867 map = kmap_local_page(page);
6868 read_extent_buffer(leaf, map + pg_offset, ptr,
6870 if (pg_offset + copy_size < PAGE_SIZE) {
6871 memset(map + pg_offset + copy_size, 0,
6872 PAGE_SIZE - pg_offset -
6877 flush_dcache_page(page);
6879 set_extent_uptodate(io_tree, em->start,
6880 extent_map_end(em) - 1, NULL, GFP_NOFS);
6885 em->orig_start = start;
6887 em->block_start = EXTENT_MAP_HOLE;
6890 btrfs_release_path(path);
6891 if (em->start > start || extent_map_end(em) <= start) {
6893 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6894 em->start, em->len, start, len);
6899 write_lock(&em_tree->lock);
6900 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6901 write_unlock(&em_tree->lock);
6903 btrfs_free_path(path);
6905 trace_btrfs_get_extent(root, inode, em);
6908 free_extent_map(em);
6909 return ERR_PTR(ret);
6914 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6917 struct extent_map *em;
6918 struct extent_map *hole_em = NULL;
6919 u64 delalloc_start = start;
6925 em = btrfs_get_extent(inode, NULL, 0, start, len);
6929 * If our em maps to:
6931 * - a pre-alloc extent,
6932 * there might actually be delalloc bytes behind it.
6934 if (em->block_start != EXTENT_MAP_HOLE &&
6935 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6940 /* check to see if we've wrapped (len == -1 or similar) */
6949 /* ok, we didn't find anything, lets look for delalloc */
6950 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6951 end, len, EXTENT_DELALLOC, 1);
6952 delalloc_end = delalloc_start + delalloc_len;
6953 if (delalloc_end < delalloc_start)
6954 delalloc_end = (u64)-1;
6957 * We didn't find anything useful, return the original results from
6960 if (delalloc_start > end || delalloc_end <= start) {
6967 * Adjust the delalloc_start to make sure it doesn't go backwards from
6968 * the start they passed in
6970 delalloc_start = max(start, delalloc_start);
6971 delalloc_len = delalloc_end - delalloc_start;
6973 if (delalloc_len > 0) {
6976 const u64 hole_end = extent_map_end(hole_em);
6978 em = alloc_extent_map();
6986 * When btrfs_get_extent can't find anything it returns one
6989 * Make sure what it found really fits our range, and adjust to
6990 * make sure it is based on the start from the caller
6992 if (hole_end <= start || hole_em->start > end) {
6993 free_extent_map(hole_em);
6996 hole_start = max(hole_em->start, start);
6997 hole_len = hole_end - hole_start;
7000 if (hole_em && delalloc_start > hole_start) {
7002 * Our hole starts before our delalloc, so we have to
7003 * return just the parts of the hole that go until the
7006 em->len = min(hole_len, delalloc_start - hole_start);
7007 em->start = hole_start;
7008 em->orig_start = hole_start;
7010 * Don't adjust block start at all, it is fixed at
7013 em->block_start = hole_em->block_start;
7014 em->block_len = hole_len;
7015 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7016 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7019 * Hole is out of passed range or it starts after
7022 em->start = delalloc_start;
7023 em->len = delalloc_len;
7024 em->orig_start = delalloc_start;
7025 em->block_start = EXTENT_MAP_DELALLOC;
7026 em->block_len = delalloc_len;
7033 free_extent_map(hole_em);
7035 free_extent_map(em);
7036 return ERR_PTR(err);
7041 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7044 const u64 orig_start,
7045 const u64 block_start,
7046 const u64 block_len,
7047 const u64 orig_block_len,
7048 const u64 ram_bytes,
7051 struct extent_map *em = NULL;
7054 if (type != BTRFS_ORDERED_NOCOW) {
7055 em = create_io_em(inode, start, len, orig_start, block_start,
7056 block_len, orig_block_len, ram_bytes,
7057 BTRFS_COMPRESS_NONE, /* compress_type */
7062 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7066 free_extent_map(em);
7067 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7076 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7079 struct btrfs_root *root = inode->root;
7080 struct btrfs_fs_info *fs_info = root->fs_info;
7081 struct extent_map *em;
7082 struct btrfs_key ins;
7086 alloc_hint = get_extent_allocation_hint(inode, start, len);
7087 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7088 0, alloc_hint, &ins, 1, 1);
7090 return ERR_PTR(ret);
7092 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7093 ins.objectid, ins.offset, ins.offset,
7094 ins.offset, BTRFS_ORDERED_REGULAR);
7095 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7097 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7103 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7105 struct btrfs_block_group *block_group;
7106 bool readonly = false;
7108 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7109 if (!block_group || block_group->ro)
7112 btrfs_put_block_group(block_group);
7117 * Check if we can do nocow write into the range [@offset, @offset + @len)
7119 * @offset: File offset
7120 * @len: The length to write, will be updated to the nocow writeable
7122 * @orig_start: (optional) Return the original file offset of the file extent
7123 * @orig_len: (optional) Return the original on-disk length of the file extent
7124 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7125 * @strict: if true, omit optimizations that might force us into unnecessary
7126 * cow. e.g., don't trust generation number.
7129 * >0 and update @len if we can do nocow write
7130 * 0 if we can't do nocow write
7131 * <0 if error happened
7133 * NOTE: This only checks the file extents, caller is responsible to wait for
7134 * any ordered extents.
7136 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7137 u64 *orig_start, u64 *orig_block_len,
7138 u64 *ram_bytes, bool strict)
7140 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7141 struct btrfs_path *path;
7143 struct extent_buffer *leaf;
7144 struct btrfs_root *root = BTRFS_I(inode)->root;
7145 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7146 struct btrfs_file_extent_item *fi;
7147 struct btrfs_key key;
7154 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7156 path = btrfs_alloc_path();
7160 ret = btrfs_lookup_file_extent(NULL, root, path,
7161 btrfs_ino(BTRFS_I(inode)), offset, 0);
7165 slot = path->slots[0];
7168 /* can't find the item, must cow */
7175 leaf = path->nodes[0];
7176 btrfs_item_key_to_cpu(leaf, &key, slot);
7177 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7178 key.type != BTRFS_EXTENT_DATA_KEY) {
7179 /* not our file or wrong item type, must cow */
7183 if (key.offset > offset) {
7184 /* Wrong offset, must cow */
7188 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7189 found_type = btrfs_file_extent_type(leaf, fi);
7190 if (found_type != BTRFS_FILE_EXTENT_REG &&
7191 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7192 /* not a regular extent, must cow */
7196 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7199 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7200 if (extent_end <= offset)
7203 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7204 if (disk_bytenr == 0)
7207 if (btrfs_file_extent_compression(leaf, fi) ||
7208 btrfs_file_extent_encryption(leaf, fi) ||
7209 btrfs_file_extent_other_encoding(leaf, fi))
7213 * Do the same check as in btrfs_cross_ref_exist but without the
7214 * unnecessary search.
7217 (btrfs_file_extent_generation(leaf, fi) <=
7218 btrfs_root_last_snapshot(&root->root_item)))
7221 backref_offset = btrfs_file_extent_offset(leaf, fi);
7224 *orig_start = key.offset - backref_offset;
7225 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7226 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7229 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7232 num_bytes = min(offset + *len, extent_end) - offset;
7233 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7236 range_end = round_up(offset + num_bytes,
7237 root->fs_info->sectorsize) - 1;
7238 ret = test_range_bit(io_tree, offset, range_end,
7239 EXTENT_DELALLOC, 0, NULL);
7246 btrfs_release_path(path);
7249 * look for other files referencing this extent, if we
7250 * find any we must cow
7253 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7254 key.offset - backref_offset, disk_bytenr,
7262 * adjust disk_bytenr and num_bytes to cover just the bytes
7263 * in this extent we are about to write. If there
7264 * are any csums in that range we have to cow in order
7265 * to keep the csums correct
7267 disk_bytenr += backref_offset;
7268 disk_bytenr += offset - key.offset;
7269 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7272 * all of the above have passed, it is safe to overwrite this extent
7278 btrfs_free_path(path);
7282 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7283 struct extent_state **cached_state, bool writing)
7285 struct btrfs_ordered_extent *ordered;
7289 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7292 * We're concerned with the entire range that we're going to be
7293 * doing DIO to, so we need to make sure there's no ordered
7294 * extents in this range.
7296 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7297 lockend - lockstart + 1);
7300 * We need to make sure there are no buffered pages in this
7301 * range either, we could have raced between the invalidate in
7302 * generic_file_direct_write and locking the extent. The
7303 * invalidate needs to happen so that reads after a write do not
7307 (!writing || !filemap_range_has_page(inode->i_mapping,
7308 lockstart, lockend)))
7311 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7316 * If we are doing a DIO read and the ordered extent we
7317 * found is for a buffered write, we can not wait for it
7318 * to complete and retry, because if we do so we can
7319 * deadlock with concurrent buffered writes on page
7320 * locks. This happens only if our DIO read covers more
7321 * than one extent map, if at this point has already
7322 * created an ordered extent for a previous extent map
7323 * and locked its range in the inode's io tree, and a
7324 * concurrent write against that previous extent map's
7325 * range and this range started (we unlock the ranges
7326 * in the io tree only when the bios complete and
7327 * buffered writes always lock pages before attempting
7328 * to lock range in the io tree).
7331 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7332 btrfs_start_ordered_extent(ordered, 1);
7335 btrfs_put_ordered_extent(ordered);
7338 * We could trigger writeback for this range (and wait
7339 * for it to complete) and then invalidate the pages for
7340 * this range (through invalidate_inode_pages2_range()),
7341 * but that can lead us to a deadlock with a concurrent
7342 * call to readahead (a buffered read or a defrag call
7343 * triggered a readahead) on a page lock due to an
7344 * ordered dio extent we created before but did not have
7345 * yet a corresponding bio submitted (whence it can not
7346 * complete), which makes readahead wait for that
7347 * ordered extent to complete while holding a lock on
7362 /* The callers of this must take lock_extent() */
7363 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7364 u64 len, u64 orig_start, u64 block_start,
7365 u64 block_len, u64 orig_block_len,
7366 u64 ram_bytes, int compress_type,
7369 struct extent_map_tree *em_tree;
7370 struct extent_map *em;
7373 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7374 type == BTRFS_ORDERED_COMPRESSED ||
7375 type == BTRFS_ORDERED_NOCOW ||
7376 type == BTRFS_ORDERED_REGULAR);
7378 em_tree = &inode->extent_tree;
7379 em = alloc_extent_map();
7381 return ERR_PTR(-ENOMEM);
7384 em->orig_start = orig_start;
7386 em->block_len = block_len;
7387 em->block_start = block_start;
7388 em->orig_block_len = orig_block_len;
7389 em->ram_bytes = ram_bytes;
7390 em->generation = -1;
7391 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7392 if (type == BTRFS_ORDERED_PREALLOC) {
7393 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7394 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7395 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7396 em->compress_type = compress_type;
7400 btrfs_drop_extent_cache(inode, em->start,
7401 em->start + em->len - 1, 0);
7402 write_lock(&em_tree->lock);
7403 ret = add_extent_mapping(em_tree, em, 1);
7404 write_unlock(&em_tree->lock);
7406 * The caller has taken lock_extent(), who could race with us
7409 } while (ret == -EEXIST);
7412 free_extent_map(em);
7413 return ERR_PTR(ret);
7416 /* em got 2 refs now, callers needs to do free_extent_map once. */
7421 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7422 struct inode *inode,
7423 struct btrfs_dio_data *dio_data,
7426 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7427 struct extent_map *em = *map;
7429 u64 block_start, orig_start, orig_block_len, ram_bytes;
7430 bool can_nocow = false;
7431 bool space_reserved = false;
7435 * We don't allocate a new extent in the following cases
7437 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7439 * 2) The extent is marked as PREALLOC. We're good to go here and can
7440 * just use the extent.
7443 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7444 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7445 em->block_start != EXTENT_MAP_HOLE)) {
7446 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7447 type = BTRFS_ORDERED_PREALLOC;
7449 type = BTRFS_ORDERED_NOCOW;
7450 len = min(len, em->len - (start - em->start));
7451 block_start = em->block_start + (start - em->start);
7453 if (can_nocow_extent(inode, start, &len, &orig_start,
7454 &orig_block_len, &ram_bytes, false) == 1 &&
7455 btrfs_inc_nocow_writers(fs_info, block_start))
7460 struct extent_map *em2;
7462 /* We can NOCOW, so only need to reserve metadata space. */
7463 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
7465 /* Our caller expects us to free the input extent map. */
7466 free_extent_map(em);
7468 btrfs_dec_nocow_writers(fs_info, block_start);
7471 space_reserved = true;
7473 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7474 orig_start, block_start,
7475 len, orig_block_len,
7477 btrfs_dec_nocow_writers(fs_info, block_start);
7478 if (type == BTRFS_ORDERED_PREALLOC) {
7479 free_extent_map(em);
7488 const u64 prev_len = len;
7490 /* Our caller expects us to free the input extent map. */
7491 free_extent_map(em);
7494 /* We have to COW, so need to reserve metadata and data space. */
7495 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7496 &dio_data->data_reserved,
7500 space_reserved = true;
7502 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7508 len = min(len, em->len - (start - em->start));
7510 btrfs_delalloc_release_space(BTRFS_I(inode),
7511 dio_data->data_reserved,
7512 start + len, prev_len - len,
7517 * We have created our ordered extent, so we can now release our reservation
7518 * for an outstanding extent.
7520 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7523 * Need to update the i_size under the extent lock so buffered
7524 * readers will get the updated i_size when we unlock.
7526 if (start + len > i_size_read(inode))
7527 i_size_write(inode, start + len);
7529 if (ret && space_reserved) {
7530 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7532 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7534 btrfs_delalloc_release_space(BTRFS_I(inode),
7535 dio_data->data_reserved,
7537 extent_changeset_free(dio_data->data_reserved);
7538 dio_data->data_reserved = NULL;
7544 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7545 loff_t length, unsigned int flags, struct iomap *iomap,
7546 struct iomap *srcmap)
7548 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7549 struct extent_map *em;
7550 struct extent_state *cached_state = NULL;
7551 struct btrfs_dio_data *dio_data = NULL;
7552 u64 lockstart, lockend;
7553 const bool write = !!(flags & IOMAP_WRITE);
7556 bool unlock_extents = false;
7559 len = min_t(u64, len, fs_info->sectorsize);
7562 lockend = start + len - 1;
7565 * The generic stuff only does filemap_write_and_wait_range, which
7566 * isn't enough if we've written compressed pages to this area, so we
7567 * need to flush the dirty pages again to make absolutely sure that any
7568 * outstanding dirty pages are on disk.
7570 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7571 &BTRFS_I(inode)->runtime_flags)) {
7572 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7573 start + length - 1);
7578 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7582 iomap->private = dio_data;
7586 * If this errors out it's because we couldn't invalidate pagecache for
7587 * this range and we need to fallback to buffered.
7589 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7594 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7601 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7602 * io. INLINE is special, and we could probably kludge it in here, but
7603 * it's still buffered so for safety lets just fall back to the generic
7606 * For COMPRESSED we _have_ to read the entire extent in so we can
7607 * decompress it, so there will be buffering required no matter what we
7608 * do, so go ahead and fallback to buffered.
7610 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7611 * to buffered IO. Don't blame me, this is the price we pay for using
7614 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7615 em->block_start == EXTENT_MAP_INLINE) {
7616 free_extent_map(em);
7621 len = min(len, em->len - (start - em->start));
7624 * If we have a NOWAIT request and the range contains multiple extents
7625 * (or a mix of extents and holes), then we return -EAGAIN to make the
7626 * caller fallback to a context where it can do a blocking (without
7627 * NOWAIT) request. This way we avoid doing partial IO and returning
7628 * success to the caller, which is not optimal for writes and for reads
7629 * it can result in unexpected behaviour for an application.
7631 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7632 * iomap_dio_rw(), we can end up returning less data then what the caller
7633 * asked for, resulting in an unexpected, and incorrect, short read.
7634 * That is, the caller asked to read N bytes and we return less than that,
7635 * which is wrong unless we are crossing EOF. This happens if we get a
7636 * page fault error when trying to fault in pages for the buffer that is
7637 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7638 * have previously submitted bios for other extents in the range, in
7639 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7640 * those bios have completed by the time we get the page fault error,
7641 * which we return back to our caller - we should only return EIOCBQUEUED
7642 * after we have submitted bios for all the extents in the range.
7644 if ((flags & IOMAP_NOWAIT) && len < length) {
7645 free_extent_map(em);
7651 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7655 unlock_extents = true;
7656 /* Recalc len in case the new em is smaller than requested */
7657 len = min(len, em->len - (start - em->start));
7660 * We need to unlock only the end area that we aren't using.
7661 * The rest is going to be unlocked by the endio routine.
7663 lockstart = start + len;
7664 if (lockstart < lockend)
7665 unlock_extents = true;
7669 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7670 lockstart, lockend, &cached_state);
7672 free_extent_state(cached_state);
7675 * Translate extent map information to iomap.
7676 * We trim the extents (and move the addr) even though iomap code does
7677 * that, since we have locked only the parts we are performing I/O in.
7679 if ((em->block_start == EXTENT_MAP_HOLE) ||
7680 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7681 iomap->addr = IOMAP_NULL_ADDR;
7682 iomap->type = IOMAP_HOLE;
7684 iomap->addr = em->block_start + (start - em->start);
7685 iomap->type = IOMAP_MAPPED;
7687 iomap->offset = start;
7688 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7689 iomap->length = len;
7691 if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
7692 iomap->flags |= IOMAP_F_ZONE_APPEND;
7694 free_extent_map(em);
7699 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7707 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7708 ssize_t written, unsigned int flags, struct iomap *iomap)
7711 struct btrfs_dio_data *dio_data = iomap->private;
7712 size_t submitted = dio_data->submitted;
7713 const bool write = !!(flags & IOMAP_WRITE);
7715 if (!write && (iomap->type == IOMAP_HOLE)) {
7716 /* If reading from a hole, unlock and return */
7717 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7721 if (submitted < length) {
7723 length -= submitted;
7725 __endio_write_update_ordered(BTRFS_I(inode), pos,
7728 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7734 extent_changeset_free(dio_data->data_reserved);
7737 iomap->private = NULL;
7742 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7745 * This implies a barrier so that stores to dio_bio->bi_status before
7746 * this and loads of dio_bio->bi_status after this are fully ordered.
7748 if (!refcount_dec_and_test(&dip->refs))
7751 if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
7752 __endio_write_update_ordered(BTRFS_I(dip->inode),
7755 !dip->dio_bio->bi_status);
7757 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7759 dip->file_offset + dip->bytes - 1);
7762 bio_endio(dip->dio_bio);
7766 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7768 unsigned long bio_flags)
7770 struct btrfs_dio_private *dip = bio->bi_private;
7771 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7774 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7776 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7780 refcount_inc(&dip->refs);
7781 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7783 refcount_dec(&dip->refs);
7787 static blk_status_t btrfs_check_read_dio_bio(struct btrfs_dio_private *dip,
7788 struct btrfs_bio *bbio,
7789 const bool uptodate)
7791 struct inode *inode = dip->inode;
7792 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7793 const u32 sectorsize = fs_info->sectorsize;
7794 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7795 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7796 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7797 struct bio_vec bvec;
7798 struct bvec_iter iter;
7799 const u64 orig_file_offset = dip->file_offset;
7800 u64 start = orig_file_offset;
7802 blk_status_t err = BLK_STS_OK;
7804 __bio_for_each_segment(bvec, &bbio->bio, iter, bbio->iter) {
7805 unsigned int i, nr_sectors, pgoff;
7807 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7808 pgoff = bvec.bv_offset;
7809 for (i = 0; i < nr_sectors; i++) {
7810 ASSERT(pgoff < PAGE_SIZE);
7812 (!csum || !check_data_csum(inode, bbio,
7813 bio_offset, bvec.bv_page,
7815 clean_io_failure(fs_info, failure_tree, io_tree,
7816 start, bvec.bv_page,
7817 btrfs_ino(BTRFS_I(inode)),
7822 ASSERT((start - orig_file_offset) < UINT_MAX);
7823 ret = btrfs_repair_one_sector(inode,
7825 start - orig_file_offset,
7826 bvec.bv_page, pgoff,
7827 start, bbio->mirror_num,
7828 submit_dio_repair_bio);
7830 err = errno_to_blk_status(ret);
7832 start += sectorsize;
7833 ASSERT(bio_offset + sectorsize > bio_offset);
7834 bio_offset += sectorsize;
7835 pgoff += sectorsize;
7841 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7842 const u64 offset, const u64 bytes,
7843 const bool uptodate)
7845 btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes,
7846 finish_ordered_fn, uptodate);
7849 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7851 u64 dio_file_offset)
7853 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, 1);
7856 static void btrfs_end_dio_bio(struct bio *bio)
7858 struct btrfs_dio_private *dip = bio->bi_private;
7859 blk_status_t err = bio->bi_status;
7862 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7863 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7864 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7865 bio->bi_opf, bio->bi_iter.bi_sector,
7866 bio->bi_iter.bi_size, err);
7868 if (bio_op(bio) == REQ_OP_READ)
7869 err = btrfs_check_read_dio_bio(dip, btrfs_bio(bio), !err);
7872 dip->dio_bio->bi_status = err;
7874 btrfs_record_physical_zoned(dip->inode, dip->file_offset, bio);
7877 btrfs_dio_private_put(dip);
7880 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7881 struct inode *inode, u64 file_offset, int async_submit)
7883 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7884 struct btrfs_dio_private *dip = bio->bi_private;
7885 bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
7888 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7890 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7893 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7898 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7901 if (write && async_submit) {
7902 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
7903 btrfs_submit_bio_start_direct_io);
7907 * If we aren't doing async submit, calculate the csum of the
7910 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
7916 csum_offset = file_offset - dip->file_offset;
7917 csum_offset >>= fs_info->sectorsize_bits;
7918 csum_offset *= fs_info->csum_size;
7919 btrfs_bio(bio)->csum = dip->csums + csum_offset;
7922 ret = btrfs_map_bio(fs_info, bio, 0);
7928 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7929 * or ordered extents whether or not we submit any bios.
7931 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7932 struct inode *inode,
7935 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
7936 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7938 struct btrfs_dio_private *dip;
7940 dip_size = sizeof(*dip);
7941 if (!write && csum) {
7942 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7945 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
7946 dip_size += fs_info->csum_size * nblocks;
7949 dip = kzalloc(dip_size, GFP_NOFS);
7954 dip->file_offset = file_offset;
7955 dip->bytes = dio_bio->bi_iter.bi_size;
7956 dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
7957 dip->dio_bio = dio_bio;
7958 refcount_set(&dip->refs, 1);
7962 static void btrfs_submit_direct(const struct iomap_iter *iter,
7963 struct bio *dio_bio, loff_t file_offset)
7965 struct inode *inode = iter->inode;
7966 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
7967 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7968 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7969 BTRFS_BLOCK_GROUP_RAID56_MASK);
7970 struct btrfs_dio_private *dip;
7973 int async_submit = 0;
7975 u64 clone_offset = 0;
7979 blk_status_t status;
7980 struct btrfs_io_geometry geom;
7981 struct btrfs_dio_data *dio_data = iter->iomap.private;
7982 struct extent_map *em = NULL;
7984 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7987 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7988 file_offset + dio_bio->bi_iter.bi_size - 1);
7990 dio_bio->bi_status = BLK_STS_RESOURCE;
7997 * Load the csums up front to reduce csum tree searches and
7998 * contention when submitting bios.
8000 * If we have csums disabled this will do nothing.
8002 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8003 if (status != BLK_STS_OK)
8007 start_sector = dio_bio->bi_iter.bi_sector;
8008 submit_len = dio_bio->bi_iter.bi_size;
8011 logical = start_sector << 9;
8012 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8014 status = errno_to_blk_status(PTR_ERR(em));
8018 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8021 status = errno_to_blk_status(ret);
8025 clone_len = min(submit_len, geom.len);
8026 ASSERT(clone_len <= UINT_MAX);
8029 * This will never fail as it's passing GPF_NOFS and
8030 * the allocation is backed by btrfs_bioset.
8032 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8033 bio->bi_private = dip;
8034 bio->bi_end_io = btrfs_end_dio_bio;
8036 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8037 status = extract_ordered_extent(BTRFS_I(inode), bio,
8045 ASSERT(submit_len >= clone_len);
8046 submit_len -= clone_len;
8049 * Increase the count before we submit the bio so we know
8050 * the end IO handler won't happen before we increase the
8051 * count. Otherwise, the dip might get freed before we're
8052 * done setting it up.
8054 * We transfer the initial reference to the last bio, so we
8055 * don't need to increment the reference count for the last one.
8057 if (submit_len > 0) {
8058 refcount_inc(&dip->refs);
8060 * If we are submitting more than one bio, submit them
8061 * all asynchronously. The exception is RAID 5 or 6, as
8062 * asynchronous checksums make it difficult to collect
8063 * full stripe writes.
8069 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8074 refcount_dec(&dip->refs);
8078 dio_data->submitted += clone_len;
8079 clone_offset += clone_len;
8080 start_sector += clone_len >> 9;
8081 file_offset += clone_len;
8083 free_extent_map(em);
8084 } while (submit_len > 0);
8088 free_extent_map(em);
8090 dip->dio_bio->bi_status = status;
8091 btrfs_dio_private_put(dip);
8094 const struct iomap_ops btrfs_dio_iomap_ops = {
8095 .iomap_begin = btrfs_dio_iomap_begin,
8096 .iomap_end = btrfs_dio_iomap_end,
8099 const struct iomap_dio_ops btrfs_dio_ops = {
8100 .submit_io = btrfs_submit_direct,
8103 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8108 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8112 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8115 int btrfs_readpage(struct file *file, struct page *page)
8117 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8118 u64 start = page_offset(page);
8119 u64 end = start + PAGE_SIZE - 1;
8120 struct btrfs_bio_ctrl bio_ctrl = { 0 };
8123 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8125 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
8127 ret = submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags);
8131 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8133 struct inode *inode = page->mapping->host;
8136 if (current->flags & PF_MEMALLOC) {
8137 redirty_page_for_writepage(wbc, page);
8143 * If we are under memory pressure we will call this directly from the
8144 * VM, we need to make sure we have the inode referenced for the ordered
8145 * extent. If not just return like we didn't do anything.
8147 if (!igrab(inode)) {
8148 redirty_page_for_writepage(wbc, page);
8149 return AOP_WRITEPAGE_ACTIVATE;
8151 ret = extent_write_full_page(page, wbc);
8152 btrfs_add_delayed_iput(inode);
8156 static int btrfs_writepages(struct address_space *mapping,
8157 struct writeback_control *wbc)
8159 return extent_writepages(mapping, wbc);
8162 static void btrfs_readahead(struct readahead_control *rac)
8164 extent_readahead(rac);
8168 * For releasepage() and invalidatepage() we have a race window where
8169 * end_page_writeback() is called but the subpage spinlock is not yet released.
8170 * If we continue to release/invalidate the page, we could cause use-after-free
8171 * for subpage spinlock. So this function is to spin and wait for subpage
8174 static void wait_subpage_spinlock(struct page *page)
8176 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
8177 struct btrfs_subpage *subpage;
8179 if (fs_info->sectorsize == PAGE_SIZE)
8182 ASSERT(PagePrivate(page) && page->private);
8183 subpage = (struct btrfs_subpage *)page->private;
8186 * This may look insane as we just acquire the spinlock and release it,
8187 * without doing anything. But we just want to make sure no one is
8188 * still holding the subpage spinlock.
8189 * And since the page is not dirty nor writeback, and we have page
8190 * locked, the only possible way to hold a spinlock is from the endio
8191 * function to clear page writeback.
8193 * Here we just acquire the spinlock so that all existing callers
8194 * should exit and we're safe to release/invalidate the page.
8196 spin_lock_irq(&subpage->lock);
8197 spin_unlock_irq(&subpage->lock);
8200 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8202 int ret = try_release_extent_mapping(page, gfp_flags);
8205 wait_subpage_spinlock(page);
8206 clear_page_extent_mapped(page);
8211 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8213 if (PageWriteback(page) || PageDirty(page))
8215 return __btrfs_releasepage(page, gfp_flags);
8218 #ifdef CONFIG_MIGRATION
8219 static int btrfs_migratepage(struct address_space *mapping,
8220 struct page *newpage, struct page *page,
8221 enum migrate_mode mode)
8225 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8226 if (ret != MIGRATEPAGE_SUCCESS)
8229 if (page_has_private(page))
8230 attach_page_private(newpage, detach_page_private(page));
8232 if (PageOrdered(page)) {
8233 ClearPageOrdered(page);
8234 SetPageOrdered(newpage);
8237 if (mode != MIGRATE_SYNC_NO_COPY)
8238 migrate_page_copy(newpage, page);
8240 migrate_page_states(newpage, page);
8241 return MIGRATEPAGE_SUCCESS;
8245 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8246 unsigned int length)
8248 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8249 struct btrfs_fs_info *fs_info = inode->root->fs_info;
8250 struct extent_io_tree *tree = &inode->io_tree;
8251 struct extent_state *cached_state = NULL;
8252 u64 page_start = page_offset(page);
8253 u64 page_end = page_start + PAGE_SIZE - 1;
8255 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8258 * We have page locked so no new ordered extent can be created on this
8259 * page, nor bio can be submitted for this page.
8261 * But already submitted bio can still be finished on this page.
8262 * Furthermore, endio function won't skip page which has Ordered
8263 * (Private2) already cleared, so it's possible for endio and
8264 * invalidatepage to do the same ordered extent accounting twice
8267 * So here we wait for any submitted bios to finish, so that we won't
8268 * do double ordered extent accounting on the same page.
8270 wait_on_page_writeback(page);
8271 wait_subpage_spinlock(page);
8274 * For subpage case, we have call sites like
8275 * btrfs_punch_hole_lock_range() which passes range not aligned to
8277 * If the range doesn't cover the full page, we don't need to and
8278 * shouldn't clear page extent mapped, as page->private can still
8279 * record subpage dirty bits for other part of the range.
8281 * For cases that can invalidate the full even the range doesn't
8282 * cover the full page, like invalidating the last page, we're
8283 * still safe to wait for ordered extent to finish.
8285 if (!(offset == 0 && length == PAGE_SIZE)) {
8286 btrfs_releasepage(page, GFP_NOFS);
8290 if (!inode_evicting)
8291 lock_extent_bits(tree, page_start, page_end, &cached_state);
8294 while (cur < page_end) {
8295 struct btrfs_ordered_extent *ordered;
8300 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8301 page_end + 1 - cur);
8303 range_end = page_end;
8305 * No ordered extent covering this range, we are safe
8306 * to delete all extent states in the range.
8308 delete_states = true;
8311 if (ordered->file_offset > cur) {
8313 * There is a range between [cur, oe->file_offset) not
8314 * covered by any ordered extent.
8315 * We are safe to delete all extent states, and handle
8316 * the ordered extent in the next iteration.
8318 range_end = ordered->file_offset - 1;
8319 delete_states = true;
8323 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8325 ASSERT(range_end + 1 - cur < U32_MAX);
8326 range_len = range_end + 1 - cur;
8327 if (!btrfs_page_test_ordered(fs_info, page, cur, range_len)) {
8329 * If Ordered (Private2) is cleared, it means endio has
8330 * already been executed for the range.
8331 * We can't delete the extent states as
8332 * btrfs_finish_ordered_io() may still use some of them.
8334 delete_states = false;
8337 btrfs_page_clear_ordered(fs_info, page, cur, range_len);
8340 * IO on this page will never be started, so we need to account
8341 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8342 * here, must leave that up for the ordered extent completion.
8344 * This will also unlock the range for incoming
8345 * btrfs_finish_ordered_io().
8347 if (!inode_evicting)
8348 clear_extent_bit(tree, cur, range_end,
8350 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8351 EXTENT_DEFRAG, 1, 0, &cached_state);
8353 spin_lock_irq(&inode->ordered_tree.lock);
8354 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8355 ordered->truncated_len = min(ordered->truncated_len,
8356 cur - ordered->file_offset);
8357 spin_unlock_irq(&inode->ordered_tree.lock);
8359 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8360 cur, range_end + 1 - cur)) {
8361 btrfs_finish_ordered_io(ordered);
8363 * The ordered extent has finished, now we're again
8364 * safe to delete all extent states of the range.
8366 delete_states = true;
8369 * btrfs_finish_ordered_io() will get executed by endio
8370 * of other pages, thus we can't delete extent states
8373 delete_states = false;
8377 btrfs_put_ordered_extent(ordered);
8379 * Qgroup reserved space handler
8380 * Sector(s) here will be either:
8382 * 1) Already written to disk or bio already finished
8383 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8384 * Qgroup will be handled by its qgroup_record then.
8385 * btrfs_qgroup_free_data() call will do nothing here.
8387 * 2) Not written to disk yet
8388 * Then btrfs_qgroup_free_data() call will clear the
8389 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8390 * reserved data space.
8391 * Since the IO will never happen for this page.
8393 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8394 if (!inode_evicting) {
8395 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8396 EXTENT_DELALLOC | EXTENT_UPTODATE |
8397 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8398 delete_states, &cached_state);
8400 cur = range_end + 1;
8403 * We have iterated through all ordered extents of the page, the page
8404 * should not have Ordered (Private2) anymore, or the above iteration
8405 * did something wrong.
8407 ASSERT(!PageOrdered(page));
8408 btrfs_page_clear_checked(fs_info, page, page_offset(page), PAGE_SIZE);
8409 if (!inode_evicting)
8410 __btrfs_releasepage(page, GFP_NOFS);
8411 clear_page_extent_mapped(page);
8415 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8416 * called from a page fault handler when a page is first dirtied. Hence we must
8417 * be careful to check for EOF conditions here. We set the page up correctly
8418 * for a written page which means we get ENOSPC checking when writing into
8419 * holes and correct delalloc and unwritten extent mapping on filesystems that
8420 * support these features.
8422 * We are not allowed to take the i_mutex here so we have to play games to
8423 * protect against truncate races as the page could now be beyond EOF. Because
8424 * truncate_setsize() writes the inode size before removing pages, once we have
8425 * the page lock we can determine safely if the page is beyond EOF. If it is not
8426 * beyond EOF, then the page is guaranteed safe against truncation until we
8429 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8431 struct page *page = vmf->page;
8432 struct inode *inode = file_inode(vmf->vma->vm_file);
8433 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8434 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8435 struct btrfs_ordered_extent *ordered;
8436 struct extent_state *cached_state = NULL;
8437 struct extent_changeset *data_reserved = NULL;
8438 unsigned long zero_start;
8448 reserved_space = PAGE_SIZE;
8450 sb_start_pagefault(inode->i_sb);
8451 page_start = page_offset(page);
8452 page_end = page_start + PAGE_SIZE - 1;
8456 * Reserving delalloc space after obtaining the page lock can lead to
8457 * deadlock. For example, if a dirty page is locked by this function
8458 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8459 * dirty page write out, then the btrfs_writepage() function could
8460 * end up waiting indefinitely to get a lock on the page currently
8461 * being processed by btrfs_page_mkwrite() function.
8463 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8464 page_start, reserved_space);
8466 ret2 = file_update_time(vmf->vma->vm_file);
8470 ret = vmf_error(ret2);
8476 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8478 down_read(&BTRFS_I(inode)->i_mmap_lock);
8480 size = i_size_read(inode);
8482 if ((page->mapping != inode->i_mapping) ||
8483 (page_start >= size)) {
8484 /* page got truncated out from underneath us */
8487 wait_on_page_writeback(page);
8489 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8490 ret2 = set_page_extent_mapped(page);
8492 ret = vmf_error(ret2);
8493 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8498 * we can't set the delalloc bits if there are pending ordered
8499 * extents. Drop our locks and wait for them to finish
8501 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8504 unlock_extent_cached(io_tree, page_start, page_end,
8507 up_read(&BTRFS_I(inode)->i_mmap_lock);
8508 btrfs_start_ordered_extent(ordered, 1);
8509 btrfs_put_ordered_extent(ordered);
8513 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8514 reserved_space = round_up(size - page_start,
8515 fs_info->sectorsize);
8516 if (reserved_space < PAGE_SIZE) {
8517 end = page_start + reserved_space - 1;
8518 btrfs_delalloc_release_space(BTRFS_I(inode),
8519 data_reserved, page_start,
8520 PAGE_SIZE - reserved_space, true);
8525 * page_mkwrite gets called when the page is firstly dirtied after it's
8526 * faulted in, but write(2) could also dirty a page and set delalloc
8527 * bits, thus in this case for space account reason, we still need to
8528 * clear any delalloc bits within this page range since we have to
8529 * reserve data&meta space before lock_page() (see above comments).
8531 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8532 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8533 EXTENT_DEFRAG, 0, 0, &cached_state);
8535 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8538 unlock_extent_cached(io_tree, page_start, page_end,
8540 ret = VM_FAULT_SIGBUS;
8544 /* page is wholly or partially inside EOF */
8545 if (page_start + PAGE_SIZE > size)
8546 zero_start = offset_in_page(size);
8548 zero_start = PAGE_SIZE;
8550 if (zero_start != PAGE_SIZE) {
8551 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8552 flush_dcache_page(page);
8554 btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8555 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8556 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8558 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8560 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8561 up_read(&BTRFS_I(inode)->i_mmap_lock);
8563 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8564 sb_end_pagefault(inode->i_sb);
8565 extent_changeset_free(data_reserved);
8566 return VM_FAULT_LOCKED;
8570 up_read(&BTRFS_I(inode)->i_mmap_lock);
8572 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8573 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8574 reserved_space, (ret != 0));
8576 sb_end_pagefault(inode->i_sb);
8577 extent_changeset_free(data_reserved);
8581 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8583 struct btrfs_truncate_control control = {
8584 .inode = BTRFS_I(inode),
8585 .ino = btrfs_ino(BTRFS_I(inode)),
8586 .min_type = BTRFS_EXTENT_DATA_KEY,
8587 .clear_extent_range = true,
8589 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8590 struct btrfs_root *root = BTRFS_I(inode)->root;
8591 struct btrfs_block_rsv *rsv;
8593 struct btrfs_trans_handle *trans;
8594 u64 mask = fs_info->sectorsize - 1;
8595 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8597 if (!skip_writeback) {
8598 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8605 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8606 * things going on here:
8608 * 1) We need to reserve space to update our inode.
8610 * 2) We need to have something to cache all the space that is going to
8611 * be free'd up by the truncate operation, but also have some slack
8612 * space reserved in case it uses space during the truncate (thank you
8613 * very much snapshotting).
8615 * And we need these to be separate. The fact is we can use a lot of
8616 * space doing the truncate, and we have no earthly idea how much space
8617 * we will use, so we need the truncate reservation to be separate so it
8618 * doesn't end up using space reserved for updating the inode. We also
8619 * need to be able to stop the transaction and start a new one, which
8620 * means we need to be able to update the inode several times, and we
8621 * have no idea of knowing how many times that will be, so we can't just
8622 * reserve 1 item for the entirety of the operation, so that has to be
8623 * done separately as well.
8625 * So that leaves us with
8627 * 1) rsv - for the truncate reservation, which we will steal from the
8628 * transaction reservation.
8629 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8630 * updating the inode.
8632 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8635 rsv->size = min_size;
8639 * 1 for the truncate slack space
8640 * 1 for updating the inode.
8642 trans = btrfs_start_transaction(root, 2);
8643 if (IS_ERR(trans)) {
8644 ret = PTR_ERR(trans);
8648 /* Migrate the slack space for the truncate to our reserve */
8649 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8653 trans->block_rsv = rsv;
8656 struct extent_state *cached_state = NULL;
8657 const u64 new_size = inode->i_size;
8658 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8660 control.new_size = new_size;
8661 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8664 * We want to drop from the next block forward in case this new
8665 * size is not block aligned since we will be keeping the last
8666 * block of the extent just the way it is.
8668 btrfs_drop_extent_cache(BTRFS_I(inode),
8669 ALIGN(new_size, fs_info->sectorsize),
8672 ret = btrfs_truncate_inode_items(trans, root, &control);
8674 inode_sub_bytes(inode, control.sub_bytes);
8675 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), control.last_size);
8677 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
8678 (u64)-1, &cached_state);
8680 trans->block_rsv = &fs_info->trans_block_rsv;
8681 if (ret != -ENOSPC && ret != -EAGAIN)
8684 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8688 btrfs_end_transaction(trans);
8689 btrfs_btree_balance_dirty(fs_info);
8691 trans = btrfs_start_transaction(root, 2);
8692 if (IS_ERR(trans)) {
8693 ret = PTR_ERR(trans);
8698 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8699 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8700 rsv, min_size, false);
8701 BUG_ON(ret); /* shouldn't happen */
8702 trans->block_rsv = rsv;
8706 * We can't call btrfs_truncate_block inside a trans handle as we could
8707 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8708 * know we've truncated everything except the last little bit, and can
8709 * do btrfs_truncate_block and then update the disk_i_size.
8711 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8712 btrfs_end_transaction(trans);
8713 btrfs_btree_balance_dirty(fs_info);
8715 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8718 trans = btrfs_start_transaction(root, 1);
8719 if (IS_ERR(trans)) {
8720 ret = PTR_ERR(trans);
8723 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8729 trans->block_rsv = &fs_info->trans_block_rsv;
8730 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8734 ret2 = btrfs_end_transaction(trans);
8737 btrfs_btree_balance_dirty(fs_info);
8740 btrfs_free_block_rsv(fs_info, rsv);
8742 * So if we truncate and then write and fsync we normally would just
8743 * write the extents that changed, which is a problem if we need to
8744 * first truncate that entire inode. So set this flag so we write out
8745 * all of the extents in the inode to the sync log so we're completely
8748 * If no extents were dropped or trimmed we don't need to force the next
8749 * fsync to truncate all the inode's items from the log and re-log them
8750 * all. This means the truncate operation did not change the file size,
8751 * or changed it to a smaller size but there was only an implicit hole
8752 * between the old i_size and the new i_size, and there were no prealloc
8753 * extents beyond i_size to drop.
8755 if (control.extents_found > 0)
8756 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8762 * create a new subvolume directory/inode (helper for the ioctl).
8764 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8765 struct btrfs_root *new_root,
8766 struct btrfs_root *parent_root,
8767 struct user_namespace *mnt_userns)
8769 struct inode *inode;
8774 err = btrfs_get_free_objectid(new_root, &ino);
8778 inode = btrfs_new_inode(trans, new_root, mnt_userns, NULL, "..", 2,
8780 S_IFDIR | (~current_umask() & S_IRWXUGO),
8783 return PTR_ERR(inode);
8784 inode->i_op = &btrfs_dir_inode_operations;
8785 inode->i_fop = &btrfs_dir_file_operations;
8787 set_nlink(inode, 1);
8788 btrfs_i_size_write(BTRFS_I(inode), 0);
8789 unlock_new_inode(inode);
8791 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8793 btrfs_err(new_root->fs_info,
8794 "error inheriting subvolume %llu properties: %d",
8795 new_root->root_key.objectid, err);
8797 err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
8803 struct inode *btrfs_alloc_inode(struct super_block *sb)
8805 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8806 struct btrfs_inode *ei;
8807 struct inode *inode;
8809 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8816 ei->last_sub_trans = 0;
8817 ei->logged_trans = 0;
8818 ei->delalloc_bytes = 0;
8819 ei->new_delalloc_bytes = 0;
8820 ei->defrag_bytes = 0;
8821 ei->disk_i_size = 0;
8825 ei->index_cnt = (u64)-1;
8827 ei->last_unlink_trans = 0;
8828 ei->last_reflink_trans = 0;
8829 ei->last_log_commit = 0;
8831 spin_lock_init(&ei->lock);
8832 ei->outstanding_extents = 0;
8833 if (sb->s_magic != BTRFS_TEST_MAGIC)
8834 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8835 BTRFS_BLOCK_RSV_DELALLOC);
8836 ei->runtime_flags = 0;
8837 ei->prop_compress = BTRFS_COMPRESS_NONE;
8838 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8840 ei->delayed_node = NULL;
8842 ei->i_otime.tv_sec = 0;
8843 ei->i_otime.tv_nsec = 0;
8845 inode = &ei->vfs_inode;
8846 extent_map_tree_init(&ei->extent_tree);
8847 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8848 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8849 IO_TREE_INODE_IO_FAILURE, inode);
8850 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8851 IO_TREE_INODE_FILE_EXTENT, inode);
8852 ei->io_tree.track_uptodate = true;
8853 ei->io_failure_tree.track_uptodate = true;
8854 atomic_set(&ei->sync_writers, 0);
8855 mutex_init(&ei->log_mutex);
8856 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8857 INIT_LIST_HEAD(&ei->delalloc_inodes);
8858 INIT_LIST_HEAD(&ei->delayed_iput);
8859 RB_CLEAR_NODE(&ei->rb_node);
8860 init_rwsem(&ei->i_mmap_lock);
8865 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8866 void btrfs_test_destroy_inode(struct inode *inode)
8868 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8869 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8873 void btrfs_free_inode(struct inode *inode)
8875 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8878 void btrfs_destroy_inode(struct inode *vfs_inode)
8880 struct btrfs_ordered_extent *ordered;
8881 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8882 struct btrfs_root *root = inode->root;
8884 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8885 WARN_ON(vfs_inode->i_data.nrpages);
8886 WARN_ON(inode->block_rsv.reserved);
8887 WARN_ON(inode->block_rsv.size);
8888 WARN_ON(inode->outstanding_extents);
8889 if (!S_ISDIR(vfs_inode->i_mode)) {
8890 WARN_ON(inode->delalloc_bytes);
8891 WARN_ON(inode->new_delalloc_bytes);
8893 WARN_ON(inode->csum_bytes);
8894 WARN_ON(inode->defrag_bytes);
8897 * This can happen where we create an inode, but somebody else also
8898 * created the same inode and we need to destroy the one we already
8905 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8909 btrfs_err(root->fs_info,
8910 "found ordered extent %llu %llu on inode cleanup",
8911 ordered->file_offset, ordered->num_bytes);
8912 btrfs_remove_ordered_extent(inode, ordered);
8913 btrfs_put_ordered_extent(ordered);
8914 btrfs_put_ordered_extent(ordered);
8917 btrfs_qgroup_check_reserved_leak(inode);
8918 inode_tree_del(inode);
8919 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8920 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8921 btrfs_put_root(inode->root);
8924 int btrfs_drop_inode(struct inode *inode)
8926 struct btrfs_root *root = BTRFS_I(inode)->root;
8931 /* the snap/subvol tree is on deleting */
8932 if (btrfs_root_refs(&root->root_item) == 0)
8935 return generic_drop_inode(inode);
8938 static void init_once(void *foo)
8940 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8942 inode_init_once(&ei->vfs_inode);
8945 void __cold btrfs_destroy_cachep(void)
8948 * Make sure all delayed rcu free inodes are flushed before we
8952 kmem_cache_destroy(btrfs_inode_cachep);
8953 kmem_cache_destroy(btrfs_trans_handle_cachep);
8954 kmem_cache_destroy(btrfs_path_cachep);
8955 kmem_cache_destroy(btrfs_free_space_cachep);
8956 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8959 int __init btrfs_init_cachep(void)
8961 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8962 sizeof(struct btrfs_inode), 0,
8963 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8965 if (!btrfs_inode_cachep)
8968 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8969 sizeof(struct btrfs_trans_handle), 0,
8970 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8971 if (!btrfs_trans_handle_cachep)
8974 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8975 sizeof(struct btrfs_path), 0,
8976 SLAB_MEM_SPREAD, NULL);
8977 if (!btrfs_path_cachep)
8980 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8981 sizeof(struct btrfs_free_space), 0,
8982 SLAB_MEM_SPREAD, NULL);
8983 if (!btrfs_free_space_cachep)
8986 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8987 PAGE_SIZE, PAGE_SIZE,
8988 SLAB_MEM_SPREAD, NULL);
8989 if (!btrfs_free_space_bitmap_cachep)
8994 btrfs_destroy_cachep();
8998 static int btrfs_getattr(struct user_namespace *mnt_userns,
8999 const struct path *path, struct kstat *stat,
9000 u32 request_mask, unsigned int flags)
9004 struct inode *inode = d_inode(path->dentry);
9005 u32 blocksize = inode->i_sb->s_blocksize;
9006 u32 bi_flags = BTRFS_I(inode)->flags;
9007 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
9009 stat->result_mask |= STATX_BTIME;
9010 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9011 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9012 if (bi_flags & BTRFS_INODE_APPEND)
9013 stat->attributes |= STATX_ATTR_APPEND;
9014 if (bi_flags & BTRFS_INODE_COMPRESS)
9015 stat->attributes |= STATX_ATTR_COMPRESSED;
9016 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9017 stat->attributes |= STATX_ATTR_IMMUTABLE;
9018 if (bi_flags & BTRFS_INODE_NODUMP)
9019 stat->attributes |= STATX_ATTR_NODUMP;
9020 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
9021 stat->attributes |= STATX_ATTR_VERITY;
9023 stat->attributes_mask |= (STATX_ATTR_APPEND |
9024 STATX_ATTR_COMPRESSED |
9025 STATX_ATTR_IMMUTABLE |
9028 generic_fillattr(mnt_userns, inode, stat);
9029 stat->dev = BTRFS_I(inode)->root->anon_dev;
9031 spin_lock(&BTRFS_I(inode)->lock);
9032 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9033 inode_bytes = inode_get_bytes(inode);
9034 spin_unlock(&BTRFS_I(inode)->lock);
9035 stat->blocks = (ALIGN(inode_bytes, blocksize) +
9036 ALIGN(delalloc_bytes, blocksize)) >> 9;
9040 static int btrfs_rename_exchange(struct inode *old_dir,
9041 struct dentry *old_dentry,
9042 struct inode *new_dir,
9043 struct dentry *new_dentry)
9045 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9046 struct btrfs_trans_handle *trans;
9047 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9048 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9049 struct inode *new_inode = new_dentry->d_inode;
9050 struct inode *old_inode = old_dentry->d_inode;
9051 struct timespec64 ctime = current_time(old_inode);
9052 struct btrfs_rename_ctx old_rename_ctx;
9053 struct btrfs_rename_ctx new_rename_ctx;
9054 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9055 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9060 bool need_abort = false;
9063 * For non-subvolumes allow exchange only within one subvolume, in the
9064 * same inode namespace. Two subvolumes (represented as directory) can
9065 * be exchanged as they're a logical link and have a fixed inode number.
9068 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9069 new_ino != BTRFS_FIRST_FREE_OBJECTID))
9072 /* close the race window with snapshot create/destroy ioctl */
9073 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9074 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9075 down_read(&fs_info->subvol_sem);
9078 * We want to reserve the absolute worst case amount of items. So if
9079 * both inodes are subvols and we need to unlink them then that would
9080 * require 4 item modifications, but if they are both normal inodes it
9081 * would require 5 item modifications, so we'll assume their normal
9082 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9083 * should cover the worst case number of items we'll modify.
9085 trans = btrfs_start_transaction(root, 12);
9086 if (IS_ERR(trans)) {
9087 ret = PTR_ERR(trans);
9092 ret = btrfs_record_root_in_trans(trans, dest);
9098 * We need to find a free sequence number both in the source and
9099 * in the destination directory for the exchange.
9101 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9104 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9108 BTRFS_I(old_inode)->dir_index = 0ULL;
9109 BTRFS_I(new_inode)->dir_index = 0ULL;
9111 /* Reference for the source. */
9112 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9113 /* force full log commit if subvolume involved. */
9114 btrfs_set_log_full_commit(trans);
9116 ret = btrfs_insert_inode_ref(trans, dest,
9117 new_dentry->d_name.name,
9118 new_dentry->d_name.len,
9120 btrfs_ino(BTRFS_I(new_dir)),
9127 /* And now for the dest. */
9128 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9129 /* force full log commit if subvolume involved. */
9130 btrfs_set_log_full_commit(trans);
9132 ret = btrfs_insert_inode_ref(trans, root,
9133 old_dentry->d_name.name,
9134 old_dentry->d_name.len,
9136 btrfs_ino(BTRFS_I(old_dir)),
9140 btrfs_abort_transaction(trans, ret);
9145 /* Update inode version and ctime/mtime. */
9146 inode_inc_iversion(old_dir);
9147 inode_inc_iversion(new_dir);
9148 inode_inc_iversion(old_inode);
9149 inode_inc_iversion(new_inode);
9150 old_dir->i_ctime = old_dir->i_mtime = ctime;
9151 new_dir->i_ctime = new_dir->i_mtime = ctime;
9152 old_inode->i_ctime = ctime;
9153 new_inode->i_ctime = ctime;
9155 if (old_dentry->d_parent != new_dentry->d_parent) {
9156 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9157 BTRFS_I(old_inode), 1);
9158 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9159 BTRFS_I(new_inode), 1);
9162 /* src is a subvolume */
9163 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9164 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9165 } else { /* src is an inode */
9166 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9167 BTRFS_I(old_dentry->d_inode),
9168 old_dentry->d_name.name,
9169 old_dentry->d_name.len,
9172 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9175 btrfs_abort_transaction(trans, ret);
9179 /* dest is a subvolume */
9180 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9181 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9182 } else { /* dest is an inode */
9183 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9184 BTRFS_I(new_dentry->d_inode),
9185 new_dentry->d_name.name,
9186 new_dentry->d_name.len,
9189 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9192 btrfs_abort_transaction(trans, ret);
9196 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9197 new_dentry->d_name.name,
9198 new_dentry->d_name.len, 0, old_idx);
9200 btrfs_abort_transaction(trans, ret);
9204 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9205 old_dentry->d_name.name,
9206 old_dentry->d_name.len, 0, new_idx);
9208 btrfs_abort_transaction(trans, ret);
9212 if (old_inode->i_nlink == 1)
9213 BTRFS_I(old_inode)->dir_index = old_idx;
9214 if (new_inode->i_nlink == 1)
9215 BTRFS_I(new_inode)->dir_index = new_idx;
9218 * Now pin the logs of the roots. We do it to ensure that no other task
9219 * can sync the logs while we are in progress with the rename, because
9220 * that could result in an inconsistency in case any of the inodes that
9221 * are part of this rename operation were logged before.
9223 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9224 btrfs_pin_log_trans(root);
9225 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9226 btrfs_pin_log_trans(dest);
9228 /* Do the log updates for all inodes. */
9229 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9230 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9231 old_rename_ctx.index, new_dentry->d_parent);
9232 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9233 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
9234 new_rename_ctx.index, old_dentry->d_parent);
9236 /* Now unpin the logs. */
9237 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9238 btrfs_end_log_trans(root);
9239 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9240 btrfs_end_log_trans(dest);
9242 ret2 = btrfs_end_transaction(trans);
9243 ret = ret ? ret : ret2;
9245 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9246 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9247 up_read(&fs_info->subvol_sem);
9252 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9253 struct btrfs_root *root,
9254 struct user_namespace *mnt_userns,
9256 struct dentry *dentry)
9259 struct inode *inode;
9263 ret = btrfs_get_free_objectid(root, &objectid);
9267 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
9268 dentry->d_name.name,
9270 btrfs_ino(BTRFS_I(dir)),
9272 S_IFCHR | WHITEOUT_MODE,
9275 if (IS_ERR(inode)) {
9276 ret = PTR_ERR(inode);
9280 inode->i_op = &btrfs_special_inode_operations;
9281 init_special_inode(inode, inode->i_mode,
9284 ret = btrfs_init_inode_security(trans, inode, dir,
9289 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9290 BTRFS_I(inode), 0, index);
9294 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9296 unlock_new_inode(inode);
9298 inode_dec_link_count(inode);
9304 static int btrfs_rename(struct user_namespace *mnt_userns,
9305 struct inode *old_dir, struct dentry *old_dentry,
9306 struct inode *new_dir, struct dentry *new_dentry,
9309 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9310 struct btrfs_trans_handle *trans;
9311 unsigned int trans_num_items;
9312 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9313 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9314 struct inode *new_inode = d_inode(new_dentry);
9315 struct inode *old_inode = d_inode(old_dentry);
9316 struct btrfs_rename_ctx rename_ctx;
9320 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9322 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9325 /* we only allow rename subvolume link between subvolumes */
9326 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9329 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9330 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9333 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9334 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9338 /* check for collisions, even if the name isn't there */
9339 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9340 new_dentry->d_name.name,
9341 new_dentry->d_name.len);
9344 if (ret == -EEXIST) {
9346 * eexist without a new_inode */
9347 if (WARN_ON(!new_inode)) {
9351 /* maybe -EOVERFLOW */
9358 * we're using rename to replace one file with another. Start IO on it
9359 * now so we don't add too much work to the end of the transaction
9361 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9362 filemap_flush(old_inode->i_mapping);
9364 /* close the racy window with snapshot create/destroy ioctl */
9365 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9366 down_read(&fs_info->subvol_sem);
9368 * We want to reserve the absolute worst case amount of items. So if
9369 * both inodes are subvols and we need to unlink them then that would
9370 * require 4 item modifications, but if they are both normal inodes it
9371 * would require 5 item modifications, so we'll assume they are normal
9372 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9373 * should cover the worst case number of items we'll modify.
9374 * If our rename has the whiteout flag, we need more 5 units for the
9375 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9376 * when selinux is enabled).
9378 trans_num_items = 11;
9379 if (flags & RENAME_WHITEOUT)
9380 trans_num_items += 5;
9381 trans = btrfs_start_transaction(root, trans_num_items);
9382 if (IS_ERR(trans)) {
9383 ret = PTR_ERR(trans);
9388 ret = btrfs_record_root_in_trans(trans, dest);
9393 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9397 BTRFS_I(old_inode)->dir_index = 0ULL;
9398 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9399 /* force full log commit if subvolume involved. */
9400 btrfs_set_log_full_commit(trans);
9402 ret = btrfs_insert_inode_ref(trans, dest,
9403 new_dentry->d_name.name,
9404 new_dentry->d_name.len,
9406 btrfs_ino(BTRFS_I(new_dir)), index);
9411 inode_inc_iversion(old_dir);
9412 inode_inc_iversion(new_dir);
9413 inode_inc_iversion(old_inode);
9414 old_dir->i_ctime = old_dir->i_mtime =
9415 new_dir->i_ctime = new_dir->i_mtime =
9416 old_inode->i_ctime = current_time(old_dir);
9418 if (old_dentry->d_parent != new_dentry->d_parent)
9419 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9420 BTRFS_I(old_inode), 1);
9422 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9423 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9425 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9426 BTRFS_I(d_inode(old_dentry)),
9427 old_dentry->d_name.name,
9428 old_dentry->d_name.len,
9431 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9434 btrfs_abort_transaction(trans, ret);
9439 inode_inc_iversion(new_inode);
9440 new_inode->i_ctime = current_time(new_inode);
9441 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9442 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9443 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9444 BUG_ON(new_inode->i_nlink == 0);
9446 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9447 BTRFS_I(d_inode(new_dentry)),
9448 new_dentry->d_name.name,
9449 new_dentry->d_name.len);
9451 if (!ret && new_inode->i_nlink == 0)
9452 ret = btrfs_orphan_add(trans,
9453 BTRFS_I(d_inode(new_dentry)));
9455 btrfs_abort_transaction(trans, ret);
9460 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9461 new_dentry->d_name.name,
9462 new_dentry->d_name.len, 0, index);
9464 btrfs_abort_transaction(trans, ret);
9468 if (old_inode->i_nlink == 1)
9469 BTRFS_I(old_inode)->dir_index = index;
9471 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9472 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9473 rename_ctx.index, new_dentry->d_parent);
9475 if (flags & RENAME_WHITEOUT) {
9476 ret = btrfs_whiteout_for_rename(trans, root, mnt_userns,
9477 old_dir, old_dentry);
9480 btrfs_abort_transaction(trans, ret);
9485 ret2 = btrfs_end_transaction(trans);
9486 ret = ret ? ret : ret2;
9488 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9489 up_read(&fs_info->subvol_sem);
9494 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9495 struct dentry *old_dentry, struct inode *new_dir,
9496 struct dentry *new_dentry, unsigned int flags)
9498 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9501 if (flags & RENAME_EXCHANGE)
9502 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9505 return btrfs_rename(mnt_userns, old_dir, old_dentry, new_dir,
9509 struct btrfs_delalloc_work {
9510 struct inode *inode;
9511 struct completion completion;
9512 struct list_head list;
9513 struct btrfs_work work;
9516 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9518 struct btrfs_delalloc_work *delalloc_work;
9519 struct inode *inode;
9521 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9523 inode = delalloc_work->inode;
9524 filemap_flush(inode->i_mapping);
9525 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9526 &BTRFS_I(inode)->runtime_flags))
9527 filemap_flush(inode->i_mapping);
9530 complete(&delalloc_work->completion);
9533 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9535 struct btrfs_delalloc_work *work;
9537 work = kmalloc(sizeof(*work), GFP_NOFS);
9541 init_completion(&work->completion);
9542 INIT_LIST_HEAD(&work->list);
9543 work->inode = inode;
9544 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9550 * some fairly slow code that needs optimization. This walks the list
9551 * of all the inodes with pending delalloc and forces them to disk.
9553 static int start_delalloc_inodes(struct btrfs_root *root,
9554 struct writeback_control *wbc, bool snapshot,
9555 bool in_reclaim_context)
9557 struct btrfs_inode *binode;
9558 struct inode *inode;
9559 struct btrfs_delalloc_work *work, *next;
9560 struct list_head works;
9561 struct list_head splice;
9563 bool full_flush = wbc->nr_to_write == LONG_MAX;
9565 INIT_LIST_HEAD(&works);
9566 INIT_LIST_HEAD(&splice);
9568 mutex_lock(&root->delalloc_mutex);
9569 spin_lock(&root->delalloc_lock);
9570 list_splice_init(&root->delalloc_inodes, &splice);
9571 while (!list_empty(&splice)) {
9572 binode = list_entry(splice.next, struct btrfs_inode,
9575 list_move_tail(&binode->delalloc_inodes,
9576 &root->delalloc_inodes);
9578 if (in_reclaim_context &&
9579 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9582 inode = igrab(&binode->vfs_inode);
9584 cond_resched_lock(&root->delalloc_lock);
9587 spin_unlock(&root->delalloc_lock);
9590 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9591 &binode->runtime_flags);
9593 work = btrfs_alloc_delalloc_work(inode);
9599 list_add_tail(&work->list, &works);
9600 btrfs_queue_work(root->fs_info->flush_workers,
9603 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9604 btrfs_add_delayed_iput(inode);
9605 if (ret || wbc->nr_to_write <= 0)
9609 spin_lock(&root->delalloc_lock);
9611 spin_unlock(&root->delalloc_lock);
9614 list_for_each_entry_safe(work, next, &works, list) {
9615 list_del_init(&work->list);
9616 wait_for_completion(&work->completion);
9620 if (!list_empty(&splice)) {
9621 spin_lock(&root->delalloc_lock);
9622 list_splice_tail(&splice, &root->delalloc_inodes);
9623 spin_unlock(&root->delalloc_lock);
9625 mutex_unlock(&root->delalloc_mutex);
9629 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9631 struct writeback_control wbc = {
9632 .nr_to_write = LONG_MAX,
9633 .sync_mode = WB_SYNC_NONE,
9635 .range_end = LLONG_MAX,
9637 struct btrfs_fs_info *fs_info = root->fs_info;
9639 if (BTRFS_FS_ERROR(fs_info))
9642 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9645 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9646 bool in_reclaim_context)
9648 struct writeback_control wbc = {
9650 .sync_mode = WB_SYNC_NONE,
9652 .range_end = LLONG_MAX,
9654 struct btrfs_root *root;
9655 struct list_head splice;
9658 if (BTRFS_FS_ERROR(fs_info))
9661 INIT_LIST_HEAD(&splice);
9663 mutex_lock(&fs_info->delalloc_root_mutex);
9664 spin_lock(&fs_info->delalloc_root_lock);
9665 list_splice_init(&fs_info->delalloc_roots, &splice);
9666 while (!list_empty(&splice)) {
9668 * Reset nr_to_write here so we know that we're doing a full
9672 wbc.nr_to_write = LONG_MAX;
9674 root = list_first_entry(&splice, struct btrfs_root,
9676 root = btrfs_grab_root(root);
9678 list_move_tail(&root->delalloc_root,
9679 &fs_info->delalloc_roots);
9680 spin_unlock(&fs_info->delalloc_root_lock);
9682 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9683 btrfs_put_root(root);
9684 if (ret < 0 || wbc.nr_to_write <= 0)
9686 spin_lock(&fs_info->delalloc_root_lock);
9688 spin_unlock(&fs_info->delalloc_root_lock);
9692 if (!list_empty(&splice)) {
9693 spin_lock(&fs_info->delalloc_root_lock);
9694 list_splice_tail(&splice, &fs_info->delalloc_roots);
9695 spin_unlock(&fs_info->delalloc_root_lock);
9697 mutex_unlock(&fs_info->delalloc_root_mutex);
9701 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9702 struct dentry *dentry, const char *symname)
9704 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9705 struct btrfs_trans_handle *trans;
9706 struct btrfs_root *root = BTRFS_I(dir)->root;
9707 struct btrfs_path *path;
9708 struct btrfs_key key;
9709 struct inode *inode = NULL;
9716 struct btrfs_file_extent_item *ei;
9717 struct extent_buffer *leaf;
9719 name_len = strlen(symname);
9720 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9721 return -ENAMETOOLONG;
9724 * 2 items for inode item and ref
9725 * 2 items for dir items
9726 * 1 item for updating parent inode item
9727 * 1 item for the inline extent item
9728 * 1 item for xattr if selinux is on
9730 trans = btrfs_start_transaction(root, 7);
9732 return PTR_ERR(trans);
9734 err = btrfs_get_free_objectid(root, &objectid);
9738 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
9739 dentry->d_name.name, dentry->d_name.len,
9740 btrfs_ino(BTRFS_I(dir)), objectid,
9741 S_IFLNK | S_IRWXUGO, &index);
9742 if (IS_ERR(inode)) {
9743 err = PTR_ERR(inode);
9749 * If the active LSM wants to access the inode during
9750 * d_instantiate it needs these. Smack checks to see
9751 * if the filesystem supports xattrs by looking at the
9754 inode->i_fop = &btrfs_file_operations;
9755 inode->i_op = &btrfs_file_inode_operations;
9756 inode->i_mapping->a_ops = &btrfs_aops;
9758 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9762 path = btrfs_alloc_path();
9767 key.objectid = btrfs_ino(BTRFS_I(inode));
9769 key.type = BTRFS_EXTENT_DATA_KEY;
9770 datasize = btrfs_file_extent_calc_inline_size(name_len);
9771 err = btrfs_insert_empty_item(trans, root, path, &key,
9774 btrfs_free_path(path);
9777 leaf = path->nodes[0];
9778 ei = btrfs_item_ptr(leaf, path->slots[0],
9779 struct btrfs_file_extent_item);
9780 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9781 btrfs_set_file_extent_type(leaf, ei,
9782 BTRFS_FILE_EXTENT_INLINE);
9783 btrfs_set_file_extent_encryption(leaf, ei, 0);
9784 btrfs_set_file_extent_compression(leaf, ei, 0);
9785 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9786 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9788 ptr = btrfs_file_extent_inline_start(ei);
9789 write_extent_buffer(leaf, symname, ptr, name_len);
9790 btrfs_mark_buffer_dirty(leaf);
9791 btrfs_free_path(path);
9793 inode->i_op = &btrfs_symlink_inode_operations;
9794 inode_nohighmem(inode);
9795 inode_set_bytes(inode, name_len);
9796 btrfs_i_size_write(BTRFS_I(inode), name_len);
9797 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
9799 * Last step, add directory indexes for our symlink inode. This is the
9800 * last step to avoid extra cleanup of these indexes if an error happens
9804 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9805 BTRFS_I(inode), 0, index);
9809 d_instantiate_new(dentry, inode);
9812 btrfs_end_transaction(trans);
9814 inode_dec_link_count(inode);
9815 discard_new_inode(inode);
9817 btrfs_btree_balance_dirty(fs_info);
9821 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9822 struct btrfs_trans_handle *trans_in,
9823 struct btrfs_inode *inode,
9824 struct btrfs_key *ins,
9827 struct btrfs_file_extent_item stack_fi;
9828 struct btrfs_replace_extent_info extent_info;
9829 struct btrfs_trans_handle *trans = trans_in;
9830 struct btrfs_path *path;
9831 u64 start = ins->objectid;
9832 u64 len = ins->offset;
9833 int qgroup_released;
9836 memset(&stack_fi, 0, sizeof(stack_fi));
9838 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9839 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9840 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9841 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9842 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9843 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9844 /* Encryption and other encoding is reserved and all 0 */
9846 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9847 if (qgroup_released < 0)
9848 return ERR_PTR(qgroup_released);
9851 ret = insert_reserved_file_extent(trans, inode,
9852 file_offset, &stack_fi,
9853 true, qgroup_released);
9859 extent_info.disk_offset = start;
9860 extent_info.disk_len = len;
9861 extent_info.data_offset = 0;
9862 extent_info.data_len = len;
9863 extent_info.file_offset = file_offset;
9864 extent_info.extent_buf = (char *)&stack_fi;
9865 extent_info.is_new_extent = true;
9866 extent_info.qgroup_reserved = qgroup_released;
9867 extent_info.insertions = 0;
9869 path = btrfs_alloc_path();
9875 ret = btrfs_replace_file_extents(inode, path, file_offset,
9876 file_offset + len - 1, &extent_info,
9878 btrfs_free_path(path);
9885 * We have released qgroup data range at the beginning of the function,
9886 * and normally qgroup_released bytes will be freed when committing
9888 * But if we error out early, we have to free what we have released
9889 * or we leak qgroup data reservation.
9891 btrfs_qgroup_free_refroot(inode->root->fs_info,
9892 inode->root->root_key.objectid, qgroup_released,
9893 BTRFS_QGROUP_RSV_DATA);
9894 return ERR_PTR(ret);
9897 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9898 u64 start, u64 num_bytes, u64 min_size,
9899 loff_t actual_len, u64 *alloc_hint,
9900 struct btrfs_trans_handle *trans)
9902 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9903 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9904 struct extent_map *em;
9905 struct btrfs_root *root = BTRFS_I(inode)->root;
9906 struct btrfs_key ins;
9907 u64 cur_offset = start;
9908 u64 clear_offset = start;
9911 u64 last_alloc = (u64)-1;
9913 bool own_trans = true;
9914 u64 end = start + num_bytes - 1;
9918 while (num_bytes > 0) {
9919 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9920 cur_bytes = max(cur_bytes, min_size);
9922 * If we are severely fragmented we could end up with really
9923 * small allocations, so if the allocator is returning small
9924 * chunks lets make its job easier by only searching for those
9927 cur_bytes = min(cur_bytes, last_alloc);
9928 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9929 min_size, 0, *alloc_hint, &ins, 1, 0);
9934 * We've reserved this space, and thus converted it from
9935 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9936 * from here on out we will only need to clear our reservation
9937 * for the remaining unreserved area, so advance our
9938 * clear_offset by our extent size.
9940 clear_offset += ins.offset;
9942 last_alloc = ins.offset;
9943 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9946 * Now that we inserted the prealloc extent we can finally
9947 * decrement the number of reservations in the block group.
9948 * If we did it before, we could race with relocation and have
9949 * relocation miss the reserved extent, making it fail later.
9951 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9952 if (IS_ERR(trans)) {
9953 ret = PTR_ERR(trans);
9954 btrfs_free_reserved_extent(fs_info, ins.objectid,
9959 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9960 cur_offset + ins.offset -1, 0);
9962 em = alloc_extent_map();
9964 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9965 &BTRFS_I(inode)->runtime_flags);
9969 em->start = cur_offset;
9970 em->orig_start = cur_offset;
9971 em->len = ins.offset;
9972 em->block_start = ins.objectid;
9973 em->block_len = ins.offset;
9974 em->orig_block_len = ins.offset;
9975 em->ram_bytes = ins.offset;
9976 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9977 em->generation = trans->transid;
9980 write_lock(&em_tree->lock);
9981 ret = add_extent_mapping(em_tree, em, 1);
9982 write_unlock(&em_tree->lock);
9985 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9986 cur_offset + ins.offset - 1,
9989 free_extent_map(em);
9991 num_bytes -= ins.offset;
9992 cur_offset += ins.offset;
9993 *alloc_hint = ins.objectid + ins.offset;
9995 inode_inc_iversion(inode);
9996 inode->i_ctime = current_time(inode);
9997 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9998 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9999 (actual_len > inode->i_size) &&
10000 (cur_offset > inode->i_size)) {
10001 if (cur_offset > actual_len)
10002 i_size = actual_len;
10004 i_size = cur_offset;
10005 i_size_write(inode, i_size);
10006 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10009 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10012 btrfs_abort_transaction(trans, ret);
10014 btrfs_end_transaction(trans);
10019 btrfs_end_transaction(trans);
10023 if (clear_offset < end)
10024 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10025 end - clear_offset + 1);
10029 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10030 u64 start, u64 num_bytes, u64 min_size,
10031 loff_t actual_len, u64 *alloc_hint)
10033 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10034 min_size, actual_len, alloc_hint,
10038 int btrfs_prealloc_file_range_trans(struct inode *inode,
10039 struct btrfs_trans_handle *trans, int mode,
10040 u64 start, u64 num_bytes, u64 min_size,
10041 loff_t actual_len, u64 *alloc_hint)
10043 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10044 min_size, actual_len, alloc_hint, trans);
10047 static int btrfs_set_page_dirty(struct page *page)
10049 return __set_page_dirty_nobuffers(page);
10052 static int btrfs_permission(struct user_namespace *mnt_userns,
10053 struct inode *inode, int mask)
10055 struct btrfs_root *root = BTRFS_I(inode)->root;
10056 umode_t mode = inode->i_mode;
10058 if (mask & MAY_WRITE &&
10059 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10060 if (btrfs_root_readonly(root))
10062 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10065 return generic_permission(mnt_userns, inode, mask);
10068 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10069 struct dentry *dentry, umode_t mode)
10071 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10072 struct btrfs_trans_handle *trans;
10073 struct btrfs_root *root = BTRFS_I(dir)->root;
10074 struct inode *inode = NULL;
10080 * 5 units required for adding orphan entry
10082 trans = btrfs_start_transaction(root, 5);
10084 return PTR_ERR(trans);
10086 ret = btrfs_get_free_objectid(root, &objectid);
10090 inode = btrfs_new_inode(trans, root, mnt_userns, dir, NULL, 0,
10091 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10092 if (IS_ERR(inode)) {
10093 ret = PTR_ERR(inode);
10098 inode->i_fop = &btrfs_file_operations;
10099 inode->i_op = &btrfs_file_inode_operations;
10101 inode->i_mapping->a_ops = &btrfs_aops;
10103 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10107 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10110 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10115 * We set number of links to 0 in btrfs_new_inode(), and here we set
10116 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10119 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10121 set_nlink(inode, 1);
10122 d_tmpfile(dentry, inode);
10123 unlock_new_inode(inode);
10124 mark_inode_dirty(inode);
10126 btrfs_end_transaction(trans);
10128 discard_new_inode(inode);
10129 btrfs_btree_balance_dirty(fs_info);
10133 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
10135 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10136 unsigned long index = start >> PAGE_SHIFT;
10137 unsigned long end_index = end >> PAGE_SHIFT;
10141 ASSERT(end + 1 - start <= U32_MAX);
10142 len = end + 1 - start;
10143 while (index <= end_index) {
10144 page = find_get_page(inode->vfs_inode.i_mapping, index);
10145 ASSERT(page); /* Pages should be in the extent_io_tree */
10147 btrfs_page_set_writeback(fs_info, page, start, len);
10155 * Add an entry indicating a block group or device which is pinned by a
10156 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10157 * negative errno on failure.
10159 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10160 bool is_block_group)
10162 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10163 struct btrfs_swapfile_pin *sp, *entry;
10164 struct rb_node **p;
10165 struct rb_node *parent = NULL;
10167 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10172 sp->is_block_group = is_block_group;
10173 sp->bg_extent_count = 1;
10175 spin_lock(&fs_info->swapfile_pins_lock);
10176 p = &fs_info->swapfile_pins.rb_node;
10179 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10180 if (sp->ptr < entry->ptr ||
10181 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10182 p = &(*p)->rb_left;
10183 } else if (sp->ptr > entry->ptr ||
10184 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10185 p = &(*p)->rb_right;
10187 if (is_block_group)
10188 entry->bg_extent_count++;
10189 spin_unlock(&fs_info->swapfile_pins_lock);
10194 rb_link_node(&sp->node, parent, p);
10195 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10196 spin_unlock(&fs_info->swapfile_pins_lock);
10200 /* Free all of the entries pinned by this swapfile. */
10201 static void btrfs_free_swapfile_pins(struct inode *inode)
10203 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10204 struct btrfs_swapfile_pin *sp;
10205 struct rb_node *node, *next;
10207 spin_lock(&fs_info->swapfile_pins_lock);
10208 node = rb_first(&fs_info->swapfile_pins);
10210 next = rb_next(node);
10211 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10212 if (sp->inode == inode) {
10213 rb_erase(&sp->node, &fs_info->swapfile_pins);
10214 if (sp->is_block_group) {
10215 btrfs_dec_block_group_swap_extents(sp->ptr,
10216 sp->bg_extent_count);
10217 btrfs_put_block_group(sp->ptr);
10223 spin_unlock(&fs_info->swapfile_pins_lock);
10226 struct btrfs_swap_info {
10232 unsigned long nr_pages;
10236 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10237 struct btrfs_swap_info *bsi)
10239 unsigned long nr_pages;
10240 unsigned long max_pages;
10241 u64 first_ppage, first_ppage_reported, next_ppage;
10245 * Our swapfile may have had its size extended after the swap header was
10246 * written. In that case activating the swapfile should not go beyond
10247 * the max size set in the swap header.
10249 if (bsi->nr_pages >= sis->max)
10252 max_pages = sis->max - bsi->nr_pages;
10253 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10254 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10255 PAGE_SIZE) >> PAGE_SHIFT;
10257 if (first_ppage >= next_ppage)
10259 nr_pages = next_ppage - first_ppage;
10260 nr_pages = min(nr_pages, max_pages);
10262 first_ppage_reported = first_ppage;
10263 if (bsi->start == 0)
10264 first_ppage_reported++;
10265 if (bsi->lowest_ppage > first_ppage_reported)
10266 bsi->lowest_ppage = first_ppage_reported;
10267 if (bsi->highest_ppage < (next_ppage - 1))
10268 bsi->highest_ppage = next_ppage - 1;
10270 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10273 bsi->nr_extents += ret;
10274 bsi->nr_pages += nr_pages;
10278 static void btrfs_swap_deactivate(struct file *file)
10280 struct inode *inode = file_inode(file);
10282 btrfs_free_swapfile_pins(inode);
10283 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10286 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10289 struct inode *inode = file_inode(file);
10290 struct btrfs_root *root = BTRFS_I(inode)->root;
10291 struct btrfs_fs_info *fs_info = root->fs_info;
10292 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10293 struct extent_state *cached_state = NULL;
10294 struct extent_map *em = NULL;
10295 struct btrfs_device *device = NULL;
10296 struct btrfs_swap_info bsi = {
10297 .lowest_ppage = (sector_t)-1ULL,
10304 * If the swap file was just created, make sure delalloc is done. If the
10305 * file changes again after this, the user is doing something stupid and
10306 * we don't really care.
10308 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10313 * The inode is locked, so these flags won't change after we check them.
10315 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10316 btrfs_warn(fs_info, "swapfile must not be compressed");
10319 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10320 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10323 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10324 btrfs_warn(fs_info, "swapfile must not be checksummed");
10329 * Balance or device remove/replace/resize can move stuff around from
10330 * under us. The exclop protection makes sure they aren't running/won't
10331 * run concurrently while we are mapping the swap extents, and
10332 * fs_info->swapfile_pins prevents them from running while the swap
10333 * file is active and moving the extents. Note that this also prevents
10334 * a concurrent device add which isn't actually necessary, but it's not
10335 * really worth the trouble to allow it.
10337 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10338 btrfs_warn(fs_info,
10339 "cannot activate swapfile while exclusive operation is running");
10344 * Prevent snapshot creation while we are activating the swap file.
10345 * We do not want to race with snapshot creation. If snapshot creation
10346 * already started before we bumped nr_swapfiles from 0 to 1 and
10347 * completes before the first write into the swap file after it is
10348 * activated, than that write would fallback to COW.
10350 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10351 btrfs_exclop_finish(fs_info);
10352 btrfs_warn(fs_info,
10353 "cannot activate swapfile because snapshot creation is in progress");
10357 * Snapshots can create extents which require COW even if NODATACOW is
10358 * set. We use this counter to prevent snapshots. We must increment it
10359 * before walking the extents because we don't want a concurrent
10360 * snapshot to run after we've already checked the extents.
10362 atomic_inc(&root->nr_swapfiles);
10364 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10366 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10368 while (start < isize) {
10369 u64 logical_block_start, physical_block_start;
10370 struct btrfs_block_group *bg;
10371 u64 len = isize - start;
10373 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10379 if (em->block_start == EXTENT_MAP_HOLE) {
10380 btrfs_warn(fs_info, "swapfile must not have holes");
10384 if (em->block_start == EXTENT_MAP_INLINE) {
10386 * It's unlikely we'll ever actually find ourselves
10387 * here, as a file small enough to fit inline won't be
10388 * big enough to store more than the swap header, but in
10389 * case something changes in the future, let's catch it
10390 * here rather than later.
10392 btrfs_warn(fs_info, "swapfile must not be inline");
10396 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10397 btrfs_warn(fs_info, "swapfile must not be compressed");
10402 logical_block_start = em->block_start + (start - em->start);
10403 len = min(len, em->len - (start - em->start));
10404 free_extent_map(em);
10407 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10413 btrfs_warn(fs_info,
10414 "swapfile must not be copy-on-write");
10419 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10425 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10426 btrfs_warn(fs_info,
10427 "swapfile must have single data profile");
10432 if (device == NULL) {
10433 device = em->map_lookup->stripes[0].dev;
10434 ret = btrfs_add_swapfile_pin(inode, device, false);
10439 } else if (device != em->map_lookup->stripes[0].dev) {
10440 btrfs_warn(fs_info, "swapfile must be on one device");
10445 physical_block_start = (em->map_lookup->stripes[0].physical +
10446 (logical_block_start - em->start));
10447 len = min(len, em->len - (logical_block_start - em->start));
10448 free_extent_map(em);
10451 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10453 btrfs_warn(fs_info,
10454 "could not find block group containing swapfile");
10459 if (!btrfs_inc_block_group_swap_extents(bg)) {
10460 btrfs_warn(fs_info,
10461 "block group for swapfile at %llu is read-only%s",
10463 atomic_read(&fs_info->scrubs_running) ?
10464 " (scrub running)" : "");
10465 btrfs_put_block_group(bg);
10470 ret = btrfs_add_swapfile_pin(inode, bg, true);
10472 btrfs_put_block_group(bg);
10479 if (bsi.block_len &&
10480 bsi.block_start + bsi.block_len == physical_block_start) {
10481 bsi.block_len += len;
10483 if (bsi.block_len) {
10484 ret = btrfs_add_swap_extent(sis, &bsi);
10489 bsi.block_start = physical_block_start;
10490 bsi.block_len = len;
10497 ret = btrfs_add_swap_extent(sis, &bsi);
10500 if (!IS_ERR_OR_NULL(em))
10501 free_extent_map(em);
10503 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10506 btrfs_swap_deactivate(file);
10508 btrfs_drew_write_unlock(&root->snapshot_lock);
10510 btrfs_exclop_finish(fs_info);
10516 sis->bdev = device->bdev;
10517 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10518 sis->max = bsi.nr_pages;
10519 sis->pages = bsi.nr_pages - 1;
10520 sis->highest_bit = bsi.nr_pages - 1;
10521 return bsi.nr_extents;
10524 static void btrfs_swap_deactivate(struct file *file)
10528 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10531 return -EOPNOTSUPP;
10536 * Update the number of bytes used in the VFS' inode. When we replace extents in
10537 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10538 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10539 * always get a correct value.
10541 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10542 const u64 add_bytes,
10543 const u64 del_bytes)
10545 if (add_bytes == del_bytes)
10548 spin_lock(&inode->lock);
10550 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10552 inode_add_bytes(&inode->vfs_inode, add_bytes);
10553 spin_unlock(&inode->lock);
10556 static const struct inode_operations btrfs_dir_inode_operations = {
10557 .getattr = btrfs_getattr,
10558 .lookup = btrfs_lookup,
10559 .create = btrfs_create,
10560 .unlink = btrfs_unlink,
10561 .link = btrfs_link,
10562 .mkdir = btrfs_mkdir,
10563 .rmdir = btrfs_rmdir,
10564 .rename = btrfs_rename2,
10565 .symlink = btrfs_symlink,
10566 .setattr = btrfs_setattr,
10567 .mknod = btrfs_mknod,
10568 .listxattr = btrfs_listxattr,
10569 .permission = btrfs_permission,
10570 .get_acl = btrfs_get_acl,
10571 .set_acl = btrfs_set_acl,
10572 .update_time = btrfs_update_time,
10573 .tmpfile = btrfs_tmpfile,
10574 .fileattr_get = btrfs_fileattr_get,
10575 .fileattr_set = btrfs_fileattr_set,
10578 static const struct file_operations btrfs_dir_file_operations = {
10579 .llseek = generic_file_llseek,
10580 .read = generic_read_dir,
10581 .iterate_shared = btrfs_real_readdir,
10582 .open = btrfs_opendir,
10583 .unlocked_ioctl = btrfs_ioctl,
10584 #ifdef CONFIG_COMPAT
10585 .compat_ioctl = btrfs_compat_ioctl,
10587 .release = btrfs_release_file,
10588 .fsync = btrfs_sync_file,
10592 * btrfs doesn't support the bmap operation because swapfiles
10593 * use bmap to make a mapping of extents in the file. They assume
10594 * these extents won't change over the life of the file and they
10595 * use the bmap result to do IO directly to the drive.
10597 * the btrfs bmap call would return logical addresses that aren't
10598 * suitable for IO and they also will change frequently as COW
10599 * operations happen. So, swapfile + btrfs == corruption.
10601 * For now we're avoiding this by dropping bmap.
10603 static const struct address_space_operations btrfs_aops = {
10604 .readpage = btrfs_readpage,
10605 .writepage = btrfs_writepage,
10606 .writepages = btrfs_writepages,
10607 .readahead = btrfs_readahead,
10608 .direct_IO = noop_direct_IO,
10609 .invalidatepage = btrfs_invalidatepage,
10610 .releasepage = btrfs_releasepage,
10611 #ifdef CONFIG_MIGRATION
10612 .migratepage = btrfs_migratepage,
10614 .set_page_dirty = btrfs_set_page_dirty,
10615 .error_remove_page = generic_error_remove_page,
10616 .swap_activate = btrfs_swap_activate,
10617 .swap_deactivate = btrfs_swap_deactivate,
10620 static const struct inode_operations btrfs_file_inode_operations = {
10621 .getattr = btrfs_getattr,
10622 .setattr = btrfs_setattr,
10623 .listxattr = btrfs_listxattr,
10624 .permission = btrfs_permission,
10625 .fiemap = btrfs_fiemap,
10626 .get_acl = btrfs_get_acl,
10627 .set_acl = btrfs_set_acl,
10628 .update_time = btrfs_update_time,
10629 .fileattr_get = btrfs_fileattr_get,
10630 .fileattr_set = btrfs_fileattr_set,
10632 static const struct inode_operations btrfs_special_inode_operations = {
10633 .getattr = btrfs_getattr,
10634 .setattr = btrfs_setattr,
10635 .permission = btrfs_permission,
10636 .listxattr = btrfs_listxattr,
10637 .get_acl = btrfs_get_acl,
10638 .set_acl = btrfs_set_acl,
10639 .update_time = btrfs_update_time,
10641 static const struct inode_operations btrfs_symlink_inode_operations = {
10642 .get_link = page_get_link,
10643 .getattr = btrfs_getattr,
10644 .setattr = btrfs_setattr,
10645 .permission = btrfs_permission,
10646 .listxattr = btrfs_listxattr,
10647 .update_time = btrfs_update_time,
10650 const struct dentry_operations btrfs_dentry_operations = {
10651 .d_delete = btrfs_dentry_delete,