1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <crypto/hash.h>
7 #include <linux/kernel.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/migrate.h>
32 #include <linux/sched/mm.h>
33 #include <linux/iomap.h>
34 #include <asm/unaligned.h>
38 #include "transaction.h"
39 #include "btrfs_inode.h"
40 #include "print-tree.h"
41 #include "ordered-data.h"
45 #include "compression.h"
47 #include "free-space-cache.h"
48 #include "inode-map.h"
51 #include "delalloc-space.h"
52 #include "block-group.h"
53 #include "space-info.h"
55 struct btrfs_iget_args {
57 struct btrfs_root *root;
60 struct btrfs_dio_data {
64 struct extent_changeset *data_reserved;
67 static const struct inode_operations btrfs_dir_inode_operations;
68 static const struct inode_operations btrfs_symlink_inode_operations;
69 static const struct inode_operations btrfs_special_inode_operations;
70 static const struct inode_operations btrfs_file_inode_operations;
71 static const struct address_space_operations btrfs_aops;
72 static const struct file_operations btrfs_dir_file_operations;
74 static struct kmem_cache *btrfs_inode_cachep;
75 struct kmem_cache *btrfs_trans_handle_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
78 struct kmem_cache *btrfs_free_space_bitmap_cachep;
80 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
81 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
82 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
83 static noinline int cow_file_range(struct btrfs_inode *inode,
84 struct page *locked_page,
85 u64 start, u64 end, int *page_started,
86 unsigned long *nr_written, int unlock);
87 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
88 u64 len, u64 orig_start, u64 block_start,
89 u64 block_len, u64 orig_block_len,
90 u64 ram_bytes, int compress_type,
93 static void __endio_write_update_ordered(struct btrfs_inode *inode,
94 const u64 offset, const u64 bytes,
98 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
100 * ilock_flags can have the following bit set:
102 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
103 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
106 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
108 if (ilock_flags & BTRFS_ILOCK_SHARED) {
109 if (ilock_flags & BTRFS_ILOCK_TRY) {
110 if (!inode_trylock_shared(inode))
115 inode_lock_shared(inode);
117 if (ilock_flags & BTRFS_ILOCK_TRY) {
118 if (!inode_trylock(inode))
129 * btrfs_inode_unlock - unock inode i_rwsem
131 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
132 * to decide whether the lock acquired is shared or exclusive.
134 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
136 if (ilock_flags & BTRFS_ILOCK_SHARED)
137 inode_unlock_shared(inode);
143 * Cleanup all submitted ordered extents in specified range to handle errors
144 * from the btrfs_run_delalloc_range() callback.
146 * NOTE: caller must ensure that when an error happens, it can not call
147 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
148 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
149 * to be released, which we want to happen only when finishing the ordered
150 * extent (btrfs_finish_ordered_io()).
152 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
153 struct page *locked_page,
154 u64 offset, u64 bytes)
156 unsigned long index = offset >> PAGE_SHIFT;
157 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
158 u64 page_start = page_offset(locked_page);
159 u64 page_end = page_start + PAGE_SIZE - 1;
163 while (index <= end_index) {
164 page = find_get_page(inode->vfs_inode.i_mapping, index);
168 ClearPagePrivate2(page);
173 * In case this page belongs to the delalloc range being instantiated
174 * then skip it, since the first page of a range is going to be
175 * properly cleaned up by the caller of run_delalloc_range
177 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
182 return __endio_write_update_ordered(inode, offset, bytes, false);
185 static int btrfs_dirty_inode(struct inode *inode);
187 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
188 struct inode *inode, struct inode *dir,
189 const struct qstr *qstr)
193 err = btrfs_init_acl(trans, inode, dir);
195 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
200 * this does all the hard work for inserting an inline extent into
201 * the btree. The caller should have done a btrfs_drop_extents so that
202 * no overlapping inline items exist in the btree
204 static int insert_inline_extent(struct btrfs_trans_handle *trans,
205 struct btrfs_path *path, bool extent_inserted,
206 struct btrfs_root *root, struct inode *inode,
207 u64 start, size_t size, size_t compressed_size,
209 struct page **compressed_pages)
211 struct extent_buffer *leaf;
212 struct page *page = NULL;
215 struct btrfs_file_extent_item *ei;
217 size_t cur_size = size;
218 unsigned long offset;
220 ASSERT((compressed_size > 0 && compressed_pages) ||
221 (compressed_size == 0 && !compressed_pages));
223 if (compressed_size && compressed_pages)
224 cur_size = compressed_size;
226 inode_add_bytes(inode, size);
228 if (!extent_inserted) {
229 struct btrfs_key key;
232 key.objectid = btrfs_ino(BTRFS_I(inode));
234 key.type = BTRFS_EXTENT_DATA_KEY;
236 datasize = btrfs_file_extent_calc_inline_size(cur_size);
237 ret = btrfs_insert_empty_item(trans, root, path, &key,
242 leaf = path->nodes[0];
243 ei = btrfs_item_ptr(leaf, path->slots[0],
244 struct btrfs_file_extent_item);
245 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
246 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
247 btrfs_set_file_extent_encryption(leaf, ei, 0);
248 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
249 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
250 ptr = btrfs_file_extent_inline_start(ei);
252 if (compress_type != BTRFS_COMPRESS_NONE) {
255 while (compressed_size > 0) {
256 cpage = compressed_pages[i];
257 cur_size = min_t(unsigned long, compressed_size,
260 kaddr = kmap_atomic(cpage);
261 write_extent_buffer(leaf, kaddr, ptr, cur_size);
262 kunmap_atomic(kaddr);
266 compressed_size -= cur_size;
268 btrfs_set_file_extent_compression(leaf, ei,
271 page = find_get_page(inode->i_mapping,
272 start >> PAGE_SHIFT);
273 btrfs_set_file_extent_compression(leaf, ei, 0);
274 kaddr = kmap_atomic(page);
275 offset = offset_in_page(start);
276 write_extent_buffer(leaf, kaddr + offset, ptr, size);
277 kunmap_atomic(kaddr);
280 btrfs_mark_buffer_dirty(leaf);
281 btrfs_release_path(path);
284 * We align size to sectorsize for inline extents just for simplicity
287 size = ALIGN(size, root->fs_info->sectorsize);
288 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
293 * we're an inline extent, so nobody can
294 * extend the file past i_size without locking
295 * a page we already have locked.
297 * We must do any isize and inode updates
298 * before we unlock the pages. Otherwise we
299 * could end up racing with unlink.
301 BTRFS_I(inode)->disk_i_size = inode->i_size;
302 ret = btrfs_update_inode(trans, root, inode);
310 * conditionally insert an inline extent into the file. This
311 * does the checks required to make sure the data is small enough
312 * to fit as an inline extent.
314 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
315 u64 end, size_t compressed_size,
317 struct page **compressed_pages)
319 struct btrfs_drop_extents_args drop_args = { 0 };
320 struct btrfs_root *root = inode->root;
321 struct btrfs_fs_info *fs_info = root->fs_info;
322 struct btrfs_trans_handle *trans;
323 u64 isize = i_size_read(&inode->vfs_inode);
324 u64 actual_end = min(end + 1, isize);
325 u64 inline_len = actual_end - start;
326 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
327 u64 data_len = inline_len;
329 struct btrfs_path *path;
332 data_len = compressed_size;
335 actual_end > fs_info->sectorsize ||
336 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
338 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
340 data_len > fs_info->max_inline) {
344 path = btrfs_alloc_path();
348 trans = btrfs_join_transaction(root);
350 btrfs_free_path(path);
351 return PTR_ERR(trans);
353 trans->block_rsv = &inode->block_rsv;
355 drop_args.path = path;
356 drop_args.start = start;
357 drop_args.end = aligned_end;
358 drop_args.drop_cache = true;
359 drop_args.replace_extent = true;
361 if (compressed_size && compressed_pages)
362 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
365 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
368 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
370 btrfs_abort_transaction(trans, ret);
374 if (isize > actual_end)
375 inline_len = min_t(u64, isize, actual_end);
376 ret = insert_inline_extent(trans, path, drop_args.extent_inserted,
377 root, &inode->vfs_inode, start,
378 inline_len, compressed_size,
379 compress_type, compressed_pages);
380 if (ret && ret != -ENOSPC) {
381 btrfs_abort_transaction(trans, ret);
383 } else if (ret == -ENOSPC) {
388 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
389 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
392 * Don't forget to free the reserved space, as for inlined extent
393 * it won't count as data extent, free them directly here.
394 * And at reserve time, it's always aligned to page size, so
395 * just free one page here.
397 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
398 btrfs_free_path(path);
399 btrfs_end_transaction(trans);
403 struct async_extent {
408 unsigned long nr_pages;
410 struct list_head list;
415 struct page *locked_page;
418 unsigned int write_flags;
419 struct list_head extents;
420 struct cgroup_subsys_state *blkcg_css;
421 struct btrfs_work work;
426 /* Number of chunks in flight; must be first in the structure */
428 struct async_chunk chunks[];
431 static noinline int add_async_extent(struct async_chunk *cow,
432 u64 start, u64 ram_size,
435 unsigned long nr_pages,
438 struct async_extent *async_extent;
440 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
441 BUG_ON(!async_extent); /* -ENOMEM */
442 async_extent->start = start;
443 async_extent->ram_size = ram_size;
444 async_extent->compressed_size = compressed_size;
445 async_extent->pages = pages;
446 async_extent->nr_pages = nr_pages;
447 async_extent->compress_type = compress_type;
448 list_add_tail(&async_extent->list, &cow->extents);
453 * Check if the inode has flags compatible with compression
455 static inline bool inode_can_compress(struct btrfs_inode *inode)
457 if (inode->flags & BTRFS_INODE_NODATACOW ||
458 inode->flags & BTRFS_INODE_NODATASUM)
464 * Check if the inode needs to be submitted to compression, based on mount
465 * options, defragmentation, properties or heuristics.
467 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
470 struct btrfs_fs_info *fs_info = inode->root->fs_info;
472 if (!inode_can_compress(inode)) {
473 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
474 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
479 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
482 if (inode->defrag_compress)
484 /* bad compression ratios */
485 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
487 if (btrfs_test_opt(fs_info, COMPRESS) ||
488 inode->flags & BTRFS_INODE_COMPRESS ||
489 inode->prop_compress)
490 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
494 static inline void inode_should_defrag(struct btrfs_inode *inode,
495 u64 start, u64 end, u64 num_bytes, u64 small_write)
497 /* If this is a small write inside eof, kick off a defrag */
498 if (num_bytes < small_write &&
499 (start > 0 || end + 1 < inode->disk_i_size))
500 btrfs_add_inode_defrag(NULL, inode);
504 * we create compressed extents in two phases. The first
505 * phase compresses a range of pages that have already been
506 * locked (both pages and state bits are locked).
508 * This is done inside an ordered work queue, and the compression
509 * is spread across many cpus. The actual IO submission is step
510 * two, and the ordered work queue takes care of making sure that
511 * happens in the same order things were put onto the queue by
512 * writepages and friends.
514 * If this code finds it can't get good compression, it puts an
515 * entry onto the work queue to write the uncompressed bytes. This
516 * makes sure that both compressed inodes and uncompressed inodes
517 * are written in the same order that the flusher thread sent them
520 static noinline int compress_file_range(struct async_chunk *async_chunk)
522 struct inode *inode = async_chunk->inode;
523 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
524 u64 blocksize = fs_info->sectorsize;
525 u64 start = async_chunk->start;
526 u64 end = async_chunk->end;
530 struct page **pages = NULL;
531 unsigned long nr_pages;
532 unsigned long total_compressed = 0;
533 unsigned long total_in = 0;
536 int compress_type = fs_info->compress_type;
537 int compressed_extents = 0;
540 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
544 * We need to save i_size before now because it could change in between
545 * us evaluating the size and assigning it. This is because we lock and
546 * unlock the page in truncate and fallocate, and then modify the i_size
549 * The barriers are to emulate READ_ONCE, remove that once i_size_read
553 i_size = i_size_read(inode);
555 actual_end = min_t(u64, i_size, end + 1);
558 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
559 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
560 nr_pages = min_t(unsigned long, nr_pages,
561 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
564 * we don't want to send crud past the end of i_size through
565 * compression, that's just a waste of CPU time. So, if the
566 * end of the file is before the start of our current
567 * requested range of bytes, we bail out to the uncompressed
568 * cleanup code that can deal with all of this.
570 * It isn't really the fastest way to fix things, but this is a
571 * very uncommon corner.
573 if (actual_end <= start)
574 goto cleanup_and_bail_uncompressed;
576 total_compressed = actual_end - start;
579 * skip compression for a small file range(<=blocksize) that
580 * isn't an inline extent, since it doesn't save disk space at all.
582 if (total_compressed <= blocksize &&
583 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
584 goto cleanup_and_bail_uncompressed;
586 total_compressed = min_t(unsigned long, total_compressed,
587 BTRFS_MAX_UNCOMPRESSED);
592 * we do compression for mount -o compress and when the
593 * inode has not been flagged as nocompress. This flag can
594 * change at any time if we discover bad compression ratios.
596 if (inode_need_compress(BTRFS_I(inode), start, end)) {
598 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
600 /* just bail out to the uncompressed code */
605 if (BTRFS_I(inode)->defrag_compress)
606 compress_type = BTRFS_I(inode)->defrag_compress;
607 else if (BTRFS_I(inode)->prop_compress)
608 compress_type = BTRFS_I(inode)->prop_compress;
611 * we need to call clear_page_dirty_for_io on each
612 * page in the range. Otherwise applications with the file
613 * mmap'd can wander in and change the page contents while
614 * we are compressing them.
616 * If the compression fails for any reason, we set the pages
617 * dirty again later on.
619 * Note that the remaining part is redirtied, the start pointer
620 * has moved, the end is the original one.
623 extent_range_clear_dirty_for_io(inode, start, end);
627 /* Compression level is applied here and only here */
628 ret = btrfs_compress_pages(
629 compress_type | (fs_info->compress_level << 4),
630 inode->i_mapping, start,
637 unsigned long offset = offset_in_page(total_compressed);
638 struct page *page = pages[nr_pages - 1];
641 /* zero the tail end of the last page, we might be
642 * sending it down to disk
645 kaddr = kmap_atomic(page);
646 memset(kaddr + offset, 0,
648 kunmap_atomic(kaddr);
655 /* lets try to make an inline extent */
656 if (ret || total_in < actual_end) {
657 /* we didn't compress the entire range, try
658 * to make an uncompressed inline extent.
660 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
661 0, BTRFS_COMPRESS_NONE,
664 /* try making a compressed inline extent */
665 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
667 compress_type, pages);
670 unsigned long clear_flags = EXTENT_DELALLOC |
671 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
672 EXTENT_DO_ACCOUNTING;
673 unsigned long page_error_op;
675 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
678 * inline extent creation worked or returned error,
679 * we don't need to create any more async work items.
680 * Unlock and free up our temp pages.
682 * We use DO_ACCOUNTING here because we need the
683 * delalloc_release_metadata to be done _after_ we drop
684 * our outstanding extent for clearing delalloc for this
687 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
697 * Ensure we only free the compressed pages if we have
698 * them allocated, as we can still reach here with
699 * inode_need_compress() == false.
702 for (i = 0; i < nr_pages; i++) {
703 WARN_ON(pages[i]->mapping);
714 * we aren't doing an inline extent round the compressed size
715 * up to a block size boundary so the allocator does sane
718 total_compressed = ALIGN(total_compressed, blocksize);
721 * one last check to make sure the compression is really a
722 * win, compare the page count read with the blocks on disk,
723 * compression must free at least one sector size
725 total_in = ALIGN(total_in, PAGE_SIZE);
726 if (total_compressed + blocksize <= total_in) {
727 compressed_extents++;
730 * The async work queues will take care of doing actual
731 * allocation on disk for these compressed pages, and
732 * will submit them to the elevator.
734 add_async_extent(async_chunk, start, total_in,
735 total_compressed, pages, nr_pages,
738 if (start + total_in < end) {
744 return compressed_extents;
749 * the compression code ran but failed to make things smaller,
750 * free any pages it allocated and our page pointer array
752 for (i = 0; i < nr_pages; i++) {
753 WARN_ON(pages[i]->mapping);
758 total_compressed = 0;
761 /* flag the file so we don't compress in the future */
762 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
763 !(BTRFS_I(inode)->prop_compress)) {
764 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
767 cleanup_and_bail_uncompressed:
769 * No compression, but we still need to write the pages in the file
770 * we've been given so far. redirty the locked page if it corresponds
771 * to our extent and set things up for the async work queue to run
772 * cow_file_range to do the normal delalloc dance.
774 if (async_chunk->locked_page &&
775 (page_offset(async_chunk->locked_page) >= start &&
776 page_offset(async_chunk->locked_page)) <= end) {
777 __set_page_dirty_nobuffers(async_chunk->locked_page);
778 /* unlocked later on in the async handlers */
782 extent_range_redirty_for_io(inode, start, end);
783 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
784 BTRFS_COMPRESS_NONE);
785 compressed_extents++;
787 return compressed_extents;
790 static void free_async_extent_pages(struct async_extent *async_extent)
794 if (!async_extent->pages)
797 for (i = 0; i < async_extent->nr_pages; i++) {
798 WARN_ON(async_extent->pages[i]->mapping);
799 put_page(async_extent->pages[i]);
801 kfree(async_extent->pages);
802 async_extent->nr_pages = 0;
803 async_extent->pages = NULL;
807 * phase two of compressed writeback. This is the ordered portion
808 * of the code, which only gets called in the order the work was
809 * queued. We walk all the async extents created by compress_file_range
810 * and send them down to the disk.
812 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
814 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
815 struct btrfs_fs_info *fs_info = inode->root->fs_info;
816 struct async_extent *async_extent;
818 struct btrfs_key ins;
819 struct extent_map *em;
820 struct btrfs_root *root = inode->root;
821 struct extent_io_tree *io_tree = &inode->io_tree;
825 while (!list_empty(&async_chunk->extents)) {
826 async_extent = list_entry(async_chunk->extents.next,
827 struct async_extent, list);
828 list_del(&async_extent->list);
831 lock_extent(io_tree, async_extent->start,
832 async_extent->start + async_extent->ram_size - 1);
833 /* did the compression code fall back to uncompressed IO? */
834 if (!async_extent->pages) {
835 int page_started = 0;
836 unsigned long nr_written = 0;
838 /* allocate blocks */
839 ret = cow_file_range(inode, async_chunk->locked_page,
841 async_extent->start +
842 async_extent->ram_size - 1,
843 &page_started, &nr_written, 0);
848 * if page_started, cow_file_range inserted an
849 * inline extent and took care of all the unlocking
850 * and IO for us. Otherwise, we need to submit
851 * all those pages down to the drive.
853 if (!page_started && !ret)
854 extent_write_locked_range(&inode->vfs_inode,
856 async_extent->start +
857 async_extent->ram_size - 1,
859 else if (ret && async_chunk->locked_page)
860 unlock_page(async_chunk->locked_page);
866 ret = btrfs_reserve_extent(root, async_extent->ram_size,
867 async_extent->compressed_size,
868 async_extent->compressed_size,
869 0, alloc_hint, &ins, 1, 1);
871 free_async_extent_pages(async_extent);
873 if (ret == -ENOSPC) {
874 unlock_extent(io_tree, async_extent->start,
875 async_extent->start +
876 async_extent->ram_size - 1);
879 * we need to redirty the pages if we decide to
880 * fallback to uncompressed IO, otherwise we
881 * will not submit these pages down to lower
884 extent_range_redirty_for_io(&inode->vfs_inode,
886 async_extent->start +
887 async_extent->ram_size - 1);
894 * here we're doing allocation and writeback of the
897 em = create_io_em(inode, async_extent->start,
898 async_extent->ram_size, /* len */
899 async_extent->start, /* orig_start */
900 ins.objectid, /* block_start */
901 ins.offset, /* block_len */
902 ins.offset, /* orig_block_len */
903 async_extent->ram_size, /* ram_bytes */
904 async_extent->compress_type,
905 BTRFS_ORDERED_COMPRESSED);
907 /* ret value is not necessary due to void function */
908 goto out_free_reserve;
911 ret = btrfs_add_ordered_extent_compress(inode,
914 async_extent->ram_size,
916 BTRFS_ORDERED_COMPRESSED,
917 async_extent->compress_type);
919 btrfs_drop_extent_cache(inode, async_extent->start,
920 async_extent->start +
921 async_extent->ram_size - 1, 0);
922 goto out_free_reserve;
924 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
927 * clear dirty, set writeback and unlock the pages.
929 extent_clear_unlock_delalloc(inode, async_extent->start,
930 async_extent->start +
931 async_extent->ram_size - 1,
932 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
933 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
935 if (btrfs_submit_compressed_write(inode, async_extent->start,
936 async_extent->ram_size,
938 ins.offset, async_extent->pages,
939 async_extent->nr_pages,
940 async_chunk->write_flags,
941 async_chunk->blkcg_css)) {
942 struct page *p = async_extent->pages[0];
943 const u64 start = async_extent->start;
944 const u64 end = start + async_extent->ram_size - 1;
946 p->mapping = inode->vfs_inode.i_mapping;
947 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
950 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
953 free_async_extent_pages(async_extent);
955 alloc_hint = ins.objectid + ins.offset;
961 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
962 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
964 extent_clear_unlock_delalloc(inode, async_extent->start,
965 async_extent->start +
966 async_extent->ram_size - 1,
967 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
968 EXTENT_DELALLOC_NEW |
969 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
970 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
971 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
973 free_async_extent_pages(async_extent);
978 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
981 struct extent_map_tree *em_tree = &inode->extent_tree;
982 struct extent_map *em;
985 read_lock(&em_tree->lock);
986 em = search_extent_mapping(em_tree, start, num_bytes);
989 * if block start isn't an actual block number then find the
990 * first block in this inode and use that as a hint. If that
991 * block is also bogus then just don't worry about it.
993 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
995 em = search_extent_mapping(em_tree, 0, 0);
996 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
997 alloc_hint = em->block_start;
1001 alloc_hint = em->block_start;
1002 free_extent_map(em);
1005 read_unlock(&em_tree->lock);
1011 * when extent_io.c finds a delayed allocation range in the file,
1012 * the call backs end up in this code. The basic idea is to
1013 * allocate extents on disk for the range, and create ordered data structs
1014 * in ram to track those extents.
1016 * locked_page is the page that writepage had locked already. We use
1017 * it to make sure we don't do extra locks or unlocks.
1019 * *page_started is set to one if we unlock locked_page and do everything
1020 * required to start IO on it. It may be clean and already done with
1021 * IO when we return.
1023 static noinline int cow_file_range(struct btrfs_inode *inode,
1024 struct page *locked_page,
1025 u64 start, u64 end, int *page_started,
1026 unsigned long *nr_written, int unlock)
1028 struct btrfs_root *root = inode->root;
1029 struct btrfs_fs_info *fs_info = root->fs_info;
1032 unsigned long ram_size;
1033 u64 cur_alloc_size = 0;
1035 u64 blocksize = fs_info->sectorsize;
1036 struct btrfs_key ins;
1037 struct extent_map *em;
1038 unsigned clear_bits;
1039 unsigned long page_ops;
1040 bool extent_reserved = false;
1043 if (btrfs_is_free_space_inode(inode)) {
1049 num_bytes = ALIGN(end - start + 1, blocksize);
1050 num_bytes = max(blocksize, num_bytes);
1051 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1053 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1056 /* lets try to make an inline extent */
1057 ret = cow_file_range_inline(inode, start, end, 0,
1058 BTRFS_COMPRESS_NONE, NULL);
1061 * We use DO_ACCOUNTING here because we need the
1062 * delalloc_release_metadata to be run _after_ we drop
1063 * our outstanding extent for clearing delalloc for this
1066 extent_clear_unlock_delalloc(inode, start, end, NULL,
1067 EXTENT_LOCKED | EXTENT_DELALLOC |
1068 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1069 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1070 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1071 PAGE_END_WRITEBACK);
1072 *nr_written = *nr_written +
1073 (end - start + PAGE_SIZE) / PAGE_SIZE;
1076 } else if (ret < 0) {
1081 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1082 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1085 * Relocation relies on the relocated extents to have exactly the same
1086 * size as the original extents. Normally writeback for relocation data
1087 * extents follows a NOCOW path because relocation preallocates the
1088 * extents. However, due to an operation such as scrub turning a block
1089 * group to RO mode, it may fallback to COW mode, so we must make sure
1090 * an extent allocated during COW has exactly the requested size and can
1091 * not be split into smaller extents, otherwise relocation breaks and
1092 * fails during the stage where it updates the bytenr of file extent
1095 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1096 min_alloc_size = num_bytes;
1098 min_alloc_size = fs_info->sectorsize;
1100 while (num_bytes > 0) {
1101 cur_alloc_size = num_bytes;
1102 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1103 min_alloc_size, 0, alloc_hint,
1107 cur_alloc_size = ins.offset;
1108 extent_reserved = true;
1110 ram_size = ins.offset;
1111 em = create_io_em(inode, start, ins.offset, /* len */
1112 start, /* orig_start */
1113 ins.objectid, /* block_start */
1114 ins.offset, /* block_len */
1115 ins.offset, /* orig_block_len */
1116 ram_size, /* ram_bytes */
1117 BTRFS_COMPRESS_NONE, /* compress_type */
1118 BTRFS_ORDERED_REGULAR /* type */);
1123 free_extent_map(em);
1125 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1126 ram_size, cur_alloc_size, 0);
1128 goto out_drop_extent_cache;
1130 if (root->root_key.objectid ==
1131 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1132 ret = btrfs_reloc_clone_csums(inode, start,
1135 * Only drop cache here, and process as normal.
1137 * We must not allow extent_clear_unlock_delalloc()
1138 * at out_unlock label to free meta of this ordered
1139 * extent, as its meta should be freed by
1140 * btrfs_finish_ordered_io().
1142 * So we must continue until @start is increased to
1143 * skip current ordered extent.
1146 btrfs_drop_extent_cache(inode, start,
1147 start + ram_size - 1, 0);
1150 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1152 /* we're not doing compressed IO, don't unlock the first
1153 * page (which the caller expects to stay locked), don't
1154 * clear any dirty bits and don't set any writeback bits
1156 * Do set the Private2 bit so we know this page was properly
1157 * setup for writepage
1159 page_ops = unlock ? PAGE_UNLOCK : 0;
1160 page_ops |= PAGE_SET_PRIVATE2;
1162 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1164 EXTENT_LOCKED | EXTENT_DELALLOC,
1166 if (num_bytes < cur_alloc_size)
1169 num_bytes -= cur_alloc_size;
1170 alloc_hint = ins.objectid + ins.offset;
1171 start += cur_alloc_size;
1172 extent_reserved = false;
1175 * btrfs_reloc_clone_csums() error, since start is increased
1176 * extent_clear_unlock_delalloc() at out_unlock label won't
1177 * free metadata of current ordered extent, we're OK to exit.
1185 out_drop_extent_cache:
1186 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1188 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1189 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1191 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1192 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1193 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1196 * If we reserved an extent for our delalloc range (or a subrange) and
1197 * failed to create the respective ordered extent, then it means that
1198 * when we reserved the extent we decremented the extent's size from
1199 * the data space_info's bytes_may_use counter and incremented the
1200 * space_info's bytes_reserved counter by the same amount. We must make
1201 * sure extent_clear_unlock_delalloc() does not try to decrement again
1202 * the data space_info's bytes_may_use counter, therefore we do not pass
1203 * it the flag EXTENT_CLEAR_DATA_RESV.
1205 if (extent_reserved) {
1206 extent_clear_unlock_delalloc(inode, start,
1207 start + cur_alloc_size - 1,
1211 start += cur_alloc_size;
1215 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1216 clear_bits | EXTENT_CLEAR_DATA_RESV,
1222 * work queue call back to started compression on a file and pages
1224 static noinline void async_cow_start(struct btrfs_work *work)
1226 struct async_chunk *async_chunk;
1227 int compressed_extents;
1229 async_chunk = container_of(work, struct async_chunk, work);
1231 compressed_extents = compress_file_range(async_chunk);
1232 if (compressed_extents == 0) {
1233 btrfs_add_delayed_iput(async_chunk->inode);
1234 async_chunk->inode = NULL;
1239 * work queue call back to submit previously compressed pages
1241 static noinline void async_cow_submit(struct btrfs_work *work)
1243 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1245 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1246 unsigned long nr_pages;
1248 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1251 /* atomic_sub_return implies a barrier */
1252 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1254 cond_wake_up_nomb(&fs_info->async_submit_wait);
1257 * ->inode could be NULL if async_chunk_start has failed to compress,
1258 * in which case we don't have anything to submit, yet we need to
1259 * always adjust ->async_delalloc_pages as its paired with the init
1260 * happening in cow_file_range_async
1262 if (async_chunk->inode)
1263 submit_compressed_extents(async_chunk);
1266 static noinline void async_cow_free(struct btrfs_work *work)
1268 struct async_chunk *async_chunk;
1270 async_chunk = container_of(work, struct async_chunk, work);
1271 if (async_chunk->inode)
1272 btrfs_add_delayed_iput(async_chunk->inode);
1273 if (async_chunk->blkcg_css)
1274 css_put(async_chunk->blkcg_css);
1276 * Since the pointer to 'pending' is at the beginning of the array of
1277 * async_chunk's, freeing it ensures the whole array has been freed.
1279 if (atomic_dec_and_test(async_chunk->pending))
1280 kvfree(async_chunk->pending);
1283 static int cow_file_range_async(struct btrfs_inode *inode,
1284 struct writeback_control *wbc,
1285 struct page *locked_page,
1286 u64 start, u64 end, int *page_started,
1287 unsigned long *nr_written)
1289 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1290 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1291 struct async_cow *ctx;
1292 struct async_chunk *async_chunk;
1293 unsigned long nr_pages;
1295 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1297 bool should_compress;
1299 const unsigned int write_flags = wbc_to_write_flags(wbc);
1301 unlock_extent(&inode->io_tree, start, end);
1303 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1304 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1306 should_compress = false;
1308 should_compress = true;
1311 nofs_flag = memalloc_nofs_save();
1312 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1313 memalloc_nofs_restore(nofs_flag);
1316 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1317 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1318 EXTENT_DO_ACCOUNTING;
1319 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1320 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1323 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1324 clear_bits, page_ops);
1328 async_chunk = ctx->chunks;
1329 atomic_set(&ctx->num_chunks, num_chunks);
1331 for (i = 0; i < num_chunks; i++) {
1332 if (should_compress)
1333 cur_end = min(end, start + SZ_512K - 1);
1338 * igrab is called higher up in the call chain, take only the
1339 * lightweight reference for the callback lifetime
1341 ihold(&inode->vfs_inode);
1342 async_chunk[i].pending = &ctx->num_chunks;
1343 async_chunk[i].inode = &inode->vfs_inode;
1344 async_chunk[i].start = start;
1345 async_chunk[i].end = cur_end;
1346 async_chunk[i].write_flags = write_flags;
1347 INIT_LIST_HEAD(&async_chunk[i].extents);
1350 * The locked_page comes all the way from writepage and its
1351 * the original page we were actually given. As we spread
1352 * this large delalloc region across multiple async_chunk
1353 * structs, only the first struct needs a pointer to locked_page
1355 * This way we don't need racey decisions about who is supposed
1360 * Depending on the compressibility, the pages might or
1361 * might not go through async. We want all of them to
1362 * be accounted against wbc once. Let's do it here
1363 * before the paths diverge. wbc accounting is used
1364 * only for foreign writeback detection and doesn't
1365 * need full accuracy. Just account the whole thing
1366 * against the first page.
1368 wbc_account_cgroup_owner(wbc, locked_page,
1370 async_chunk[i].locked_page = locked_page;
1373 async_chunk[i].locked_page = NULL;
1376 if (blkcg_css != blkcg_root_css) {
1378 async_chunk[i].blkcg_css = blkcg_css;
1380 async_chunk[i].blkcg_css = NULL;
1383 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1384 async_cow_submit, async_cow_free);
1386 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1387 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1389 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1391 *nr_written += nr_pages;
1392 start = cur_end + 1;
1398 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1399 u64 bytenr, u64 num_bytes)
1402 struct btrfs_ordered_sum *sums;
1405 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1406 bytenr + num_bytes - 1, &list, 0);
1407 if (ret == 0 && list_empty(&list))
1410 while (!list_empty(&list)) {
1411 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1412 list_del(&sums->list);
1420 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1421 const u64 start, const u64 end,
1422 int *page_started, unsigned long *nr_written)
1424 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1425 const bool is_reloc_ino = (inode->root->root_key.objectid ==
1426 BTRFS_DATA_RELOC_TREE_OBJECTID);
1427 const u64 range_bytes = end + 1 - start;
1428 struct extent_io_tree *io_tree = &inode->io_tree;
1429 u64 range_start = start;
1433 * If EXTENT_NORESERVE is set it means that when the buffered write was
1434 * made we had not enough available data space and therefore we did not
1435 * reserve data space for it, since we though we could do NOCOW for the
1436 * respective file range (either there is prealloc extent or the inode
1437 * has the NOCOW bit set).
1439 * However when we need to fallback to COW mode (because for example the
1440 * block group for the corresponding extent was turned to RO mode by a
1441 * scrub or relocation) we need to do the following:
1443 * 1) We increment the bytes_may_use counter of the data space info.
1444 * If COW succeeds, it allocates a new data extent and after doing
1445 * that it decrements the space info's bytes_may_use counter and
1446 * increments its bytes_reserved counter by the same amount (we do
1447 * this at btrfs_add_reserved_bytes()). So we need to increment the
1448 * bytes_may_use counter to compensate (when space is reserved at
1449 * buffered write time, the bytes_may_use counter is incremented);
1451 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1452 * that if the COW path fails for any reason, it decrements (through
1453 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1454 * data space info, which we incremented in the step above.
1456 * If we need to fallback to cow and the inode corresponds to a free
1457 * space cache inode or an inode of the data relocation tree, we must
1458 * also increment bytes_may_use of the data space_info for the same
1459 * reason. Space caches and relocated data extents always get a prealloc
1460 * extent for them, however scrub or balance may have set the block
1461 * group that contains that extent to RO mode and therefore force COW
1462 * when starting writeback.
1464 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1465 EXTENT_NORESERVE, 0);
1466 if (count > 0 || is_space_ino || is_reloc_ino) {
1468 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1469 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1471 if (is_space_ino || is_reloc_ino)
1472 bytes = range_bytes;
1474 spin_lock(&sinfo->lock);
1475 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1476 spin_unlock(&sinfo->lock);
1479 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1483 return cow_file_range(inode, locked_page, start, end, page_started,
1488 * when nowcow writeback call back. This checks for snapshots or COW copies
1489 * of the extents that exist in the file, and COWs the file as required.
1491 * If no cow copies or snapshots exist, we write directly to the existing
1494 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1495 struct page *locked_page,
1496 const u64 start, const u64 end,
1497 int *page_started, int force,
1498 unsigned long *nr_written)
1500 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1501 struct btrfs_root *root = inode->root;
1502 struct btrfs_path *path;
1503 u64 cow_start = (u64)-1;
1504 u64 cur_offset = start;
1506 bool check_prev = true;
1507 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1508 u64 ino = btrfs_ino(inode);
1510 u64 disk_bytenr = 0;
1512 path = btrfs_alloc_path();
1514 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1515 EXTENT_LOCKED | EXTENT_DELALLOC |
1516 EXTENT_DO_ACCOUNTING |
1517 EXTENT_DEFRAG, PAGE_UNLOCK |
1519 PAGE_SET_WRITEBACK |
1520 PAGE_END_WRITEBACK);
1525 struct btrfs_key found_key;
1526 struct btrfs_file_extent_item *fi;
1527 struct extent_buffer *leaf;
1537 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1543 * If there is no extent for our range when doing the initial
1544 * search, then go back to the previous slot as it will be the
1545 * one containing the search offset
1547 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1548 leaf = path->nodes[0];
1549 btrfs_item_key_to_cpu(leaf, &found_key,
1550 path->slots[0] - 1);
1551 if (found_key.objectid == ino &&
1552 found_key.type == BTRFS_EXTENT_DATA_KEY)
1557 /* Go to next leaf if we have exhausted the current one */
1558 leaf = path->nodes[0];
1559 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1560 ret = btrfs_next_leaf(root, path);
1562 if (cow_start != (u64)-1)
1563 cur_offset = cow_start;
1568 leaf = path->nodes[0];
1571 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1573 /* Didn't find anything for our INO */
1574 if (found_key.objectid > ino)
1577 * Keep searching until we find an EXTENT_ITEM or there are no
1578 * more extents for this inode
1580 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1581 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1586 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1587 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1588 found_key.offset > end)
1592 * If the found extent starts after requested offset, then
1593 * adjust extent_end to be right before this extent begins
1595 if (found_key.offset > cur_offset) {
1596 extent_end = found_key.offset;
1602 * Found extent which begins before our range and potentially
1605 fi = btrfs_item_ptr(leaf, path->slots[0],
1606 struct btrfs_file_extent_item);
1607 extent_type = btrfs_file_extent_type(leaf, fi);
1609 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1610 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1611 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1612 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1613 extent_offset = btrfs_file_extent_offset(leaf, fi);
1614 extent_end = found_key.offset +
1615 btrfs_file_extent_num_bytes(leaf, fi);
1617 btrfs_file_extent_disk_num_bytes(leaf, fi);
1619 * If the extent we got ends before our current offset,
1620 * skip to the next extent.
1622 if (extent_end <= cur_offset) {
1627 if (disk_bytenr == 0)
1629 /* Skip compressed/encrypted/encoded extents */
1630 if (btrfs_file_extent_compression(leaf, fi) ||
1631 btrfs_file_extent_encryption(leaf, fi) ||
1632 btrfs_file_extent_other_encoding(leaf, fi))
1635 * If extent is created before the last volume's snapshot
1636 * this implies the extent is shared, hence we can't do
1637 * nocow. This is the same check as in
1638 * btrfs_cross_ref_exist but without calling
1639 * btrfs_search_slot.
1641 if (!freespace_inode &&
1642 btrfs_file_extent_generation(leaf, fi) <=
1643 btrfs_root_last_snapshot(&root->root_item))
1645 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1647 /* If extent is RO, we must COW it */
1648 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1650 ret = btrfs_cross_ref_exist(root, ino,
1652 extent_offset, disk_bytenr, false);
1655 * ret could be -EIO if the above fails to read
1659 if (cow_start != (u64)-1)
1660 cur_offset = cow_start;
1664 WARN_ON_ONCE(freespace_inode);
1667 disk_bytenr += extent_offset;
1668 disk_bytenr += cur_offset - found_key.offset;
1669 num_bytes = min(end + 1, extent_end) - cur_offset;
1671 * If there are pending snapshots for this root, we
1672 * fall into common COW way
1674 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1677 * force cow if csum exists in the range.
1678 * this ensure that csum for a given extent are
1679 * either valid or do not exist.
1681 ret = csum_exist_in_range(fs_info, disk_bytenr,
1685 * ret could be -EIO if the above fails to read
1689 if (cow_start != (u64)-1)
1690 cur_offset = cow_start;
1693 WARN_ON_ONCE(freespace_inode);
1696 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1699 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1700 extent_end = found_key.offset + ram_bytes;
1701 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1702 /* Skip extents outside of our requested range */
1703 if (extent_end <= start) {
1708 /* If this triggers then we have a memory corruption */
1713 * If nocow is false then record the beginning of the range
1714 * that needs to be COWed
1717 if (cow_start == (u64)-1)
1718 cow_start = cur_offset;
1719 cur_offset = extent_end;
1720 if (cur_offset > end)
1726 btrfs_release_path(path);
1729 * COW range from cow_start to found_key.offset - 1. As the key
1730 * will contain the beginning of the first extent that can be
1731 * NOCOW, following one which needs to be COW'ed
1733 if (cow_start != (u64)-1) {
1734 ret = fallback_to_cow(inode, locked_page,
1735 cow_start, found_key.offset - 1,
1736 page_started, nr_written);
1739 cow_start = (u64)-1;
1742 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1743 u64 orig_start = found_key.offset - extent_offset;
1744 struct extent_map *em;
1746 em = create_io_em(inode, cur_offset, num_bytes,
1748 disk_bytenr, /* block_start */
1749 num_bytes, /* block_len */
1750 disk_num_bytes, /* orig_block_len */
1751 ram_bytes, BTRFS_COMPRESS_NONE,
1752 BTRFS_ORDERED_PREALLOC);
1757 free_extent_map(em);
1758 ret = btrfs_add_ordered_extent(inode, cur_offset,
1759 disk_bytenr, num_bytes,
1761 BTRFS_ORDERED_PREALLOC);
1763 btrfs_drop_extent_cache(inode, cur_offset,
1764 cur_offset + num_bytes - 1,
1769 ret = btrfs_add_ordered_extent(inode, cur_offset,
1770 disk_bytenr, num_bytes,
1772 BTRFS_ORDERED_NOCOW);
1778 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1781 if (root->root_key.objectid ==
1782 BTRFS_DATA_RELOC_TREE_OBJECTID)
1784 * Error handled later, as we must prevent
1785 * extent_clear_unlock_delalloc() in error handler
1786 * from freeing metadata of created ordered extent.
1788 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1791 extent_clear_unlock_delalloc(inode, cur_offset,
1792 cur_offset + num_bytes - 1,
1793 locked_page, EXTENT_LOCKED |
1795 EXTENT_CLEAR_DATA_RESV,
1796 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1798 cur_offset = extent_end;
1801 * btrfs_reloc_clone_csums() error, now we're OK to call error
1802 * handler, as metadata for created ordered extent will only
1803 * be freed by btrfs_finish_ordered_io().
1807 if (cur_offset > end)
1810 btrfs_release_path(path);
1812 if (cur_offset <= end && cow_start == (u64)-1)
1813 cow_start = cur_offset;
1815 if (cow_start != (u64)-1) {
1817 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1818 page_started, nr_written);
1825 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1827 if (ret && cur_offset < end)
1828 extent_clear_unlock_delalloc(inode, cur_offset, end,
1829 locked_page, EXTENT_LOCKED |
1830 EXTENT_DELALLOC | EXTENT_DEFRAG |
1831 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1833 PAGE_SET_WRITEBACK |
1834 PAGE_END_WRITEBACK);
1835 btrfs_free_path(path);
1839 static inline int need_force_cow(struct btrfs_inode *inode, u64 start, u64 end)
1842 if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1843 !(inode->flags & BTRFS_INODE_PREALLOC))
1847 * @defrag_bytes is a hint value, no spinlock held here,
1848 * if is not zero, it means the file is defragging.
1849 * Force cow if given extent needs to be defragged.
1851 if (inode->defrag_bytes &&
1852 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG, 0, NULL))
1859 * Function to process delayed allocation (create CoW) for ranges which are
1860 * being touched for the first time.
1862 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1863 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1864 struct writeback_control *wbc)
1867 int force_cow = need_force_cow(inode, start, end);
1869 if (inode->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1870 ret = run_delalloc_nocow(inode, locked_page, start, end,
1871 page_started, 1, nr_written);
1872 } else if (inode->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1873 ret = run_delalloc_nocow(inode, locked_page, start, end,
1874 page_started, 0, nr_written);
1875 } else if (!inode_can_compress(inode) ||
1876 !inode_need_compress(inode, start, end)) {
1877 ret = cow_file_range(inode, locked_page, start, end,
1878 page_started, nr_written, 1);
1880 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1881 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1882 page_started, nr_written);
1885 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1890 void btrfs_split_delalloc_extent(struct inode *inode,
1891 struct extent_state *orig, u64 split)
1895 /* not delalloc, ignore it */
1896 if (!(orig->state & EXTENT_DELALLOC))
1899 size = orig->end - orig->start + 1;
1900 if (size > BTRFS_MAX_EXTENT_SIZE) {
1905 * See the explanation in btrfs_merge_delalloc_extent, the same
1906 * applies here, just in reverse.
1908 new_size = orig->end - split + 1;
1909 num_extents = count_max_extents(new_size);
1910 new_size = split - orig->start;
1911 num_extents += count_max_extents(new_size);
1912 if (count_max_extents(size) >= num_extents)
1916 spin_lock(&BTRFS_I(inode)->lock);
1917 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1918 spin_unlock(&BTRFS_I(inode)->lock);
1922 * Handle merged delayed allocation extents so we can keep track of new extents
1923 * that are just merged onto old extents, such as when we are doing sequential
1924 * writes, so we can properly account for the metadata space we'll need.
1926 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1927 struct extent_state *other)
1929 u64 new_size, old_size;
1932 /* not delalloc, ignore it */
1933 if (!(other->state & EXTENT_DELALLOC))
1936 if (new->start > other->start)
1937 new_size = new->end - other->start + 1;
1939 new_size = other->end - new->start + 1;
1941 /* we're not bigger than the max, unreserve the space and go */
1942 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1943 spin_lock(&BTRFS_I(inode)->lock);
1944 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1945 spin_unlock(&BTRFS_I(inode)->lock);
1950 * We have to add up either side to figure out how many extents were
1951 * accounted for before we merged into one big extent. If the number of
1952 * extents we accounted for is <= the amount we need for the new range
1953 * then we can return, otherwise drop. Think of it like this
1957 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1958 * need 2 outstanding extents, on one side we have 1 and the other side
1959 * we have 1 so they are == and we can return. But in this case
1961 * [MAX_SIZE+4k][MAX_SIZE+4k]
1963 * Each range on their own accounts for 2 extents, but merged together
1964 * they are only 3 extents worth of accounting, so we need to drop in
1967 old_size = other->end - other->start + 1;
1968 num_extents = count_max_extents(old_size);
1969 old_size = new->end - new->start + 1;
1970 num_extents += count_max_extents(old_size);
1971 if (count_max_extents(new_size) >= num_extents)
1974 spin_lock(&BTRFS_I(inode)->lock);
1975 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1976 spin_unlock(&BTRFS_I(inode)->lock);
1979 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1980 struct inode *inode)
1982 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1984 spin_lock(&root->delalloc_lock);
1985 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1986 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1987 &root->delalloc_inodes);
1988 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1989 &BTRFS_I(inode)->runtime_flags);
1990 root->nr_delalloc_inodes++;
1991 if (root->nr_delalloc_inodes == 1) {
1992 spin_lock(&fs_info->delalloc_root_lock);
1993 BUG_ON(!list_empty(&root->delalloc_root));
1994 list_add_tail(&root->delalloc_root,
1995 &fs_info->delalloc_roots);
1996 spin_unlock(&fs_info->delalloc_root_lock);
1999 spin_unlock(&root->delalloc_lock);
2003 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2004 struct btrfs_inode *inode)
2006 struct btrfs_fs_info *fs_info = root->fs_info;
2008 if (!list_empty(&inode->delalloc_inodes)) {
2009 list_del_init(&inode->delalloc_inodes);
2010 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2011 &inode->runtime_flags);
2012 root->nr_delalloc_inodes--;
2013 if (!root->nr_delalloc_inodes) {
2014 ASSERT(list_empty(&root->delalloc_inodes));
2015 spin_lock(&fs_info->delalloc_root_lock);
2016 BUG_ON(list_empty(&root->delalloc_root));
2017 list_del_init(&root->delalloc_root);
2018 spin_unlock(&fs_info->delalloc_root_lock);
2023 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2024 struct btrfs_inode *inode)
2026 spin_lock(&root->delalloc_lock);
2027 __btrfs_del_delalloc_inode(root, inode);
2028 spin_unlock(&root->delalloc_lock);
2032 * Properly track delayed allocation bytes in the inode and to maintain the
2033 * list of inodes that have pending delalloc work to be done.
2035 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2038 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2040 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2043 * set_bit and clear bit hooks normally require _irqsave/restore
2044 * but in this case, we are only testing for the DELALLOC
2045 * bit, which is only set or cleared with irqs on
2047 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2048 struct btrfs_root *root = BTRFS_I(inode)->root;
2049 u64 len = state->end + 1 - state->start;
2050 u32 num_extents = count_max_extents(len);
2051 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2053 spin_lock(&BTRFS_I(inode)->lock);
2054 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2055 spin_unlock(&BTRFS_I(inode)->lock);
2057 /* For sanity tests */
2058 if (btrfs_is_testing(fs_info))
2061 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2062 fs_info->delalloc_batch);
2063 spin_lock(&BTRFS_I(inode)->lock);
2064 BTRFS_I(inode)->delalloc_bytes += len;
2065 if (*bits & EXTENT_DEFRAG)
2066 BTRFS_I(inode)->defrag_bytes += len;
2067 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2068 &BTRFS_I(inode)->runtime_flags))
2069 btrfs_add_delalloc_inodes(root, inode);
2070 spin_unlock(&BTRFS_I(inode)->lock);
2073 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2074 (*bits & EXTENT_DELALLOC_NEW)) {
2075 spin_lock(&BTRFS_I(inode)->lock);
2076 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2078 spin_unlock(&BTRFS_I(inode)->lock);
2083 * Once a range is no longer delalloc this function ensures that proper
2084 * accounting happens.
2086 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2087 struct extent_state *state, unsigned *bits)
2089 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2090 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2091 u64 len = state->end + 1 - state->start;
2092 u32 num_extents = count_max_extents(len);
2094 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2095 spin_lock(&inode->lock);
2096 inode->defrag_bytes -= len;
2097 spin_unlock(&inode->lock);
2101 * set_bit and clear bit hooks normally require _irqsave/restore
2102 * but in this case, we are only testing for the DELALLOC
2103 * bit, which is only set or cleared with irqs on
2105 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2106 struct btrfs_root *root = inode->root;
2107 bool do_list = !btrfs_is_free_space_inode(inode);
2109 spin_lock(&inode->lock);
2110 btrfs_mod_outstanding_extents(inode, -num_extents);
2111 spin_unlock(&inode->lock);
2114 * We don't reserve metadata space for space cache inodes so we
2115 * don't need to call delalloc_release_metadata if there is an
2118 if (*bits & EXTENT_CLEAR_META_RESV &&
2119 root != fs_info->tree_root)
2120 btrfs_delalloc_release_metadata(inode, len, false);
2122 /* For sanity tests. */
2123 if (btrfs_is_testing(fs_info))
2126 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2127 do_list && !(state->state & EXTENT_NORESERVE) &&
2128 (*bits & EXTENT_CLEAR_DATA_RESV))
2129 btrfs_free_reserved_data_space_noquota(fs_info, len);
2131 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2132 fs_info->delalloc_batch);
2133 spin_lock(&inode->lock);
2134 inode->delalloc_bytes -= len;
2135 if (do_list && inode->delalloc_bytes == 0 &&
2136 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2137 &inode->runtime_flags))
2138 btrfs_del_delalloc_inode(root, inode);
2139 spin_unlock(&inode->lock);
2142 if ((state->state & EXTENT_DELALLOC_NEW) &&
2143 (*bits & EXTENT_DELALLOC_NEW)) {
2144 spin_lock(&inode->lock);
2145 ASSERT(inode->new_delalloc_bytes >= len);
2146 inode->new_delalloc_bytes -= len;
2147 spin_unlock(&inode->lock);
2152 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2153 * in a chunk's stripe. This function ensures that bios do not span a
2156 * @page - The page we are about to add to the bio
2157 * @size - size we want to add to the bio
2158 * @bio - bio we want to ensure is smaller than a stripe
2159 * @bio_flags - flags of the bio
2161 * return 1 if page cannot be added to the bio
2162 * return 0 if page can be added to the bio
2163 * return error otherwise
2165 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2166 unsigned long bio_flags)
2168 struct inode *inode = page->mapping->host;
2169 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2170 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2174 struct btrfs_io_geometry geom;
2176 if (bio_flags & EXTENT_BIO_COMPRESSED)
2179 length = bio->bi_iter.bi_size;
2180 map_length = length;
2181 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2186 if (geom.len < length + size)
2192 * in order to insert checksums into the metadata in large chunks,
2193 * we wait until bio submission time. All the pages in the bio are
2194 * checksummed and sums are attached onto the ordered extent record.
2196 * At IO completion time the cums attached on the ordered extent record
2197 * are inserted into the btree
2199 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2202 return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2206 * extent_io.c submission hook. This does the right thing for csum calculation
2207 * on write, or reading the csums from the tree before a read.
2209 * Rules about async/sync submit,
2210 * a) read: sync submit
2212 * b) write without checksum: sync submit
2214 * c) write with checksum:
2215 * c-1) if bio is issued by fsync: sync submit
2216 * (sync_writers != 0)
2218 * c-2) if root is reloc root: sync submit
2219 * (only in case of buffered IO)
2221 * c-3) otherwise: async submit
2223 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2224 int mirror_num, unsigned long bio_flags)
2227 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2228 struct btrfs_root *root = BTRFS_I(inode)->root;
2229 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2230 blk_status_t ret = 0;
2232 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2234 skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2235 !fs_info->csum_root;
2237 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2238 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2240 if (bio_op(bio) != REQ_OP_WRITE) {
2241 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2245 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2246 ret = btrfs_submit_compressed_read(inode, bio,
2252 * Lookup bio sums does extra checks around whether we
2253 * need to csum or not, which is why we ignore skip_sum
2256 ret = btrfs_lookup_bio_sums(inode, bio, (u64)-1, NULL);
2261 } else if (async && !skip_sum) {
2262 /* csum items have already been cloned */
2263 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2265 /* we're doing a write, do the async checksumming */
2266 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2267 0, btrfs_submit_bio_start);
2269 } else if (!skip_sum) {
2270 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2276 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2280 bio->bi_status = ret;
2287 * given a list of ordered sums record them in the inode. This happens
2288 * at IO completion time based on sums calculated at bio submission time.
2290 static int add_pending_csums(struct btrfs_trans_handle *trans,
2291 struct list_head *list)
2293 struct btrfs_ordered_sum *sum;
2296 list_for_each_entry(sum, list, list) {
2297 trans->adding_csums = true;
2298 ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2299 trans->adding_csums = false;
2306 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2309 struct extent_state **cached_state)
2311 u64 search_start = start;
2312 const u64 end = start + len - 1;
2314 while (search_start < end) {
2315 const u64 search_len = end - search_start + 1;
2316 struct extent_map *em;
2320 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2324 if (em->block_start != EXTENT_MAP_HOLE)
2328 if (em->start < search_start)
2329 em_len -= search_start - em->start;
2330 if (em_len > search_len)
2331 em_len = search_len;
2333 ret = set_extent_bit(&inode->io_tree, search_start,
2334 search_start + em_len - 1,
2335 EXTENT_DELALLOC_NEW,
2336 NULL, cached_state, GFP_NOFS);
2338 search_start = extent_map_end(em);
2339 free_extent_map(em);
2346 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2347 unsigned int extra_bits,
2348 struct extent_state **cached_state)
2350 WARN_ON(PAGE_ALIGNED(end));
2352 if (start >= i_size_read(&inode->vfs_inode) &&
2353 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2355 * There can't be any extents following eof in this case so just
2356 * set the delalloc new bit for the range directly.
2358 extra_bits |= EXTENT_DELALLOC_NEW;
2362 ret = btrfs_find_new_delalloc_bytes(inode, start,
2369 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2373 /* see btrfs_writepage_start_hook for details on why this is required */
2374 struct btrfs_writepage_fixup {
2376 struct inode *inode;
2377 struct btrfs_work work;
2380 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2382 struct btrfs_writepage_fixup *fixup;
2383 struct btrfs_ordered_extent *ordered;
2384 struct extent_state *cached_state = NULL;
2385 struct extent_changeset *data_reserved = NULL;
2387 struct btrfs_inode *inode;
2391 bool free_delalloc_space = true;
2393 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2395 inode = BTRFS_I(fixup->inode);
2396 page_start = page_offset(page);
2397 page_end = page_offset(page) + PAGE_SIZE - 1;
2400 * This is similar to page_mkwrite, we need to reserve the space before
2401 * we take the page lock.
2403 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2409 * Before we queued this fixup, we took a reference on the page.
2410 * page->mapping may go NULL, but it shouldn't be moved to a different
2413 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2415 * Unfortunately this is a little tricky, either
2417 * 1) We got here and our page had already been dealt with and
2418 * we reserved our space, thus ret == 0, so we need to just
2419 * drop our space reservation and bail. This can happen the
2420 * first time we come into the fixup worker, or could happen
2421 * while waiting for the ordered extent.
2422 * 2) Our page was already dealt with, but we happened to get an
2423 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2424 * this case we obviously don't have anything to release, but
2425 * because the page was already dealt with we don't want to
2426 * mark the page with an error, so make sure we're resetting
2427 * ret to 0. This is why we have this check _before_ the ret
2428 * check, because we do not want to have a surprise ENOSPC
2429 * when the page was already properly dealt with.
2432 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2433 btrfs_delalloc_release_space(inode, data_reserved,
2434 page_start, PAGE_SIZE,
2442 * We can't mess with the page state unless it is locked, so now that
2443 * it is locked bail if we failed to make our space reservation.
2448 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2450 /* already ordered? We're done */
2451 if (PagePrivate2(page))
2454 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2456 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2459 btrfs_start_ordered_extent(ordered, 1);
2460 btrfs_put_ordered_extent(ordered);
2464 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2470 * Everything went as planned, we're now the owner of a dirty page with
2471 * delayed allocation bits set and space reserved for our COW
2474 * The page was dirty when we started, nothing should have cleaned it.
2476 BUG_ON(!PageDirty(page));
2477 free_delalloc_space = false;
2479 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2480 if (free_delalloc_space)
2481 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2483 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2488 * We hit ENOSPC or other errors. Update the mapping and page
2489 * to reflect the errors and clean the page.
2491 mapping_set_error(page->mapping, ret);
2492 end_extent_writepage(page, ret, page_start, page_end);
2493 clear_page_dirty_for_io(page);
2496 ClearPageChecked(page);
2500 extent_changeset_free(data_reserved);
2502 * As a precaution, do a delayed iput in case it would be the last iput
2503 * that could need flushing space. Recursing back to fixup worker would
2506 btrfs_add_delayed_iput(&inode->vfs_inode);
2510 * There are a few paths in the higher layers of the kernel that directly
2511 * set the page dirty bit without asking the filesystem if it is a
2512 * good idea. This causes problems because we want to make sure COW
2513 * properly happens and the data=ordered rules are followed.
2515 * In our case any range that doesn't have the ORDERED bit set
2516 * hasn't been properly setup for IO. We kick off an async process
2517 * to fix it up. The async helper will wait for ordered extents, set
2518 * the delalloc bit and make it safe to write the page.
2520 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2522 struct inode *inode = page->mapping->host;
2523 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2524 struct btrfs_writepage_fixup *fixup;
2526 /* this page is properly in the ordered list */
2527 if (TestClearPagePrivate2(page))
2531 * PageChecked is set below when we create a fixup worker for this page,
2532 * don't try to create another one if we're already PageChecked()
2534 * The extent_io writepage code will redirty the page if we send back
2537 if (PageChecked(page))
2540 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2545 * We are already holding a reference to this inode from
2546 * write_cache_pages. We need to hold it because the space reservation
2547 * takes place outside of the page lock, and we can't trust
2548 * page->mapping outside of the page lock.
2551 SetPageChecked(page);
2553 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2555 fixup->inode = inode;
2556 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2561 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2562 struct btrfs_inode *inode, u64 file_pos,
2563 struct btrfs_file_extent_item *stack_fi,
2564 u64 qgroup_reserved)
2566 struct btrfs_root *root = inode->root;
2567 struct btrfs_path *path;
2568 struct extent_buffer *leaf;
2569 struct btrfs_key ins;
2570 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2571 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2572 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2573 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2574 struct btrfs_drop_extents_args drop_args = { 0 };
2577 path = btrfs_alloc_path();
2582 * we may be replacing one extent in the tree with another.
2583 * The new extent is pinned in the extent map, and we don't want
2584 * to drop it from the cache until it is completely in the btree.
2586 * So, tell btrfs_drop_extents to leave this extent in the cache.
2587 * the caller is expected to unpin it and allow it to be merged
2590 drop_args.path = path;
2591 drop_args.start = file_pos;
2592 drop_args.end = file_pos + num_bytes;
2593 drop_args.replace_extent = true;
2594 drop_args.extent_item_size = sizeof(*stack_fi);
2595 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2599 if (!drop_args.extent_inserted) {
2600 ins.objectid = btrfs_ino(inode);
2601 ins.offset = file_pos;
2602 ins.type = BTRFS_EXTENT_DATA_KEY;
2604 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2609 leaf = path->nodes[0];
2610 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2611 write_extent_buffer(leaf, stack_fi,
2612 btrfs_item_ptr_offset(leaf, path->slots[0]),
2613 sizeof(struct btrfs_file_extent_item));
2615 btrfs_mark_buffer_dirty(leaf);
2616 btrfs_release_path(path);
2618 inode_add_bytes(&inode->vfs_inode, num_bytes);
2620 ins.objectid = disk_bytenr;
2621 ins.offset = disk_num_bytes;
2622 ins.type = BTRFS_EXTENT_ITEM_KEY;
2624 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2628 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2629 file_pos, qgroup_reserved, &ins);
2631 btrfs_free_path(path);
2636 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2639 struct btrfs_block_group *cache;
2641 cache = btrfs_lookup_block_group(fs_info, start);
2644 spin_lock(&cache->lock);
2645 cache->delalloc_bytes -= len;
2646 spin_unlock(&cache->lock);
2648 btrfs_put_block_group(cache);
2651 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2652 struct btrfs_ordered_extent *oe)
2654 struct btrfs_file_extent_item stack_fi;
2657 memset(&stack_fi, 0, sizeof(stack_fi));
2658 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2659 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2660 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2661 oe->disk_num_bytes);
2662 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2663 logical_len = oe->truncated_len;
2665 logical_len = oe->num_bytes;
2666 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2667 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2668 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2669 /* Encryption and other encoding is reserved and all 0 */
2671 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
2672 oe->file_offset, &stack_fi,
2677 * As ordered data IO finishes, this gets called so we can finish
2678 * an ordered extent if the range of bytes in the file it covers are
2681 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2683 struct inode *inode = ordered_extent->inode;
2684 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2685 struct btrfs_root *root = BTRFS_I(inode)->root;
2686 struct btrfs_trans_handle *trans = NULL;
2687 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2688 struct extent_state *cached_state = NULL;
2690 int compress_type = 0;
2692 u64 logical_len = ordered_extent->num_bytes;
2693 bool freespace_inode;
2694 bool truncated = false;
2695 bool range_locked = false;
2696 bool clear_new_delalloc_bytes = false;
2697 bool clear_reserved_extent = true;
2698 unsigned int clear_bits;
2700 start = ordered_extent->file_offset;
2701 end = start + ordered_extent->num_bytes - 1;
2703 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2704 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2705 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2706 clear_new_delalloc_bytes = true;
2708 freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
2710 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2715 btrfs_free_io_failure_record(BTRFS_I(inode), start, end);
2717 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2719 logical_len = ordered_extent->truncated_len;
2720 /* Truncated the entire extent, don't bother adding */
2725 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2726 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2728 btrfs_inode_safe_disk_i_size_write(inode, 0);
2729 if (freespace_inode)
2730 trans = btrfs_join_transaction_spacecache(root);
2732 trans = btrfs_join_transaction(root);
2733 if (IS_ERR(trans)) {
2734 ret = PTR_ERR(trans);
2738 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2739 ret = btrfs_update_inode_fallback(trans, root, inode);
2740 if (ret) /* -ENOMEM or corruption */
2741 btrfs_abort_transaction(trans, ret);
2745 range_locked = true;
2746 lock_extent_bits(io_tree, start, end, &cached_state);
2748 if (freespace_inode)
2749 trans = btrfs_join_transaction_spacecache(root);
2751 trans = btrfs_join_transaction(root);
2752 if (IS_ERR(trans)) {
2753 ret = PTR_ERR(trans);
2758 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2760 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2761 compress_type = ordered_extent->compress_type;
2762 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2763 BUG_ON(compress_type);
2764 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2765 ordered_extent->file_offset,
2766 ordered_extent->file_offset +
2769 BUG_ON(root == fs_info->tree_root);
2770 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
2772 clear_reserved_extent = false;
2773 btrfs_release_delalloc_bytes(fs_info,
2774 ordered_extent->disk_bytenr,
2775 ordered_extent->disk_num_bytes);
2778 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2779 ordered_extent->file_offset,
2780 ordered_extent->num_bytes, trans->transid);
2782 btrfs_abort_transaction(trans, ret);
2786 ret = add_pending_csums(trans, &ordered_extent->list);
2788 btrfs_abort_transaction(trans, ret);
2792 btrfs_inode_safe_disk_i_size_write(inode, 0);
2793 ret = btrfs_update_inode_fallback(trans, root, inode);
2794 if (ret) { /* -ENOMEM or corruption */
2795 btrfs_abort_transaction(trans, ret);
2800 clear_bits = EXTENT_DEFRAG;
2802 clear_bits |= EXTENT_LOCKED;
2803 if (clear_new_delalloc_bytes)
2804 clear_bits |= EXTENT_DELALLOC_NEW;
2805 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits,
2806 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2810 btrfs_end_transaction(trans);
2812 if (ret || truncated) {
2813 u64 unwritten_start = start;
2816 unwritten_start += logical_len;
2817 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
2819 /* Drop the cache for the part of the extent we didn't write. */
2820 btrfs_drop_extent_cache(BTRFS_I(inode), unwritten_start, end, 0);
2823 * If the ordered extent had an IOERR or something else went
2824 * wrong we need to return the space for this ordered extent
2825 * back to the allocator. We only free the extent in the
2826 * truncated case if we didn't write out the extent at all.
2828 * If we made it past insert_reserved_file_extent before we
2829 * errored out then we don't need to do this as the accounting
2830 * has already been done.
2832 if ((ret || !logical_len) &&
2833 clear_reserved_extent &&
2834 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2835 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2837 * Discard the range before returning it back to the
2840 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
2841 btrfs_discard_extent(fs_info,
2842 ordered_extent->disk_bytenr,
2843 ordered_extent->disk_num_bytes,
2845 btrfs_free_reserved_extent(fs_info,
2846 ordered_extent->disk_bytenr,
2847 ordered_extent->disk_num_bytes, 1);
2852 * This needs to be done to make sure anybody waiting knows we are done
2853 * updating everything for this ordered extent.
2855 btrfs_remove_ordered_extent(BTRFS_I(inode), ordered_extent);
2858 btrfs_put_ordered_extent(ordered_extent);
2859 /* once for the tree */
2860 btrfs_put_ordered_extent(ordered_extent);
2865 static void finish_ordered_fn(struct btrfs_work *work)
2867 struct btrfs_ordered_extent *ordered_extent;
2868 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2869 btrfs_finish_ordered_io(ordered_extent);
2872 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
2873 u64 end, int uptodate)
2875 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
2876 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2877 struct btrfs_ordered_extent *ordered_extent = NULL;
2878 struct btrfs_workqueue *wq;
2880 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2882 ClearPagePrivate2(page);
2883 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2884 end - start + 1, uptodate))
2887 if (btrfs_is_free_space_inode(inode))
2888 wq = fs_info->endio_freespace_worker;
2890 wq = fs_info->endio_write_workers;
2892 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2893 btrfs_queue_work(wq, &ordered_extent->work);
2897 * check_data_csum - verify checksum of one sector of uncompressed data
2899 * @io_bio: btrfs_io_bio which contains the csum
2900 * @icsum: checksum index in the io_bio->csum array, size of csum_size
2901 * @page: page where is the data to be verified
2902 * @pgoff: offset inside the page
2904 * The length of such check is always one sector size.
2906 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
2907 int icsum, struct page *page, int pgoff)
2909 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2910 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2912 u32 len = fs_info->sectorsize;
2913 const u32 csum_size = fs_info->csum_size;
2915 u8 csum[BTRFS_CSUM_SIZE];
2917 ASSERT(pgoff + len <= PAGE_SIZE);
2919 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
2921 kaddr = kmap_atomic(page);
2922 shash->tfm = fs_info->csum_shash;
2924 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
2926 if (memcmp(csum, csum_expected, csum_size))
2929 kunmap_atomic(kaddr);
2932 btrfs_print_data_csum_error(BTRFS_I(inode), page_offset(page) + pgoff,
2933 csum, csum_expected, io_bio->mirror_num);
2935 btrfs_dev_stat_inc_and_print(io_bio->device,
2936 BTRFS_DEV_STAT_CORRUPTION_ERRS);
2937 memset(kaddr + pgoff, 1, len);
2938 flush_dcache_page(page);
2939 kunmap_atomic(kaddr);
2944 * when reads are done, we need to check csums to verify the data is correct
2945 * if there's a match, we allow the bio to finish. If not, the code in
2946 * extent_io.c will try to find good copies for us.
2948 int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u64 phy_offset,
2949 struct page *page, u64 start, u64 end, int mirror)
2951 size_t offset = start - page_offset(page);
2952 struct inode *inode = page->mapping->host;
2953 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2954 struct btrfs_root *root = BTRFS_I(inode)->root;
2956 if (PageChecked(page)) {
2957 ClearPageChecked(page);
2961 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2964 if (!root->fs_info->csum_root)
2967 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2968 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2969 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2973 phy_offset >>= root->fs_info->sectorsize_bits;
2974 return check_data_csum(inode, io_bio, phy_offset, page, offset);
2978 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2980 * @inode: The inode we want to perform iput on
2982 * This function uses the generic vfs_inode::i_count to track whether we should
2983 * just decrement it (in case it's > 1) or if this is the last iput then link
2984 * the inode to the delayed iput machinery. Delayed iputs are processed at
2985 * transaction commit time/superblock commit/cleaner kthread.
2987 void btrfs_add_delayed_iput(struct inode *inode)
2989 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2990 struct btrfs_inode *binode = BTRFS_I(inode);
2992 if (atomic_add_unless(&inode->i_count, -1, 1))
2995 atomic_inc(&fs_info->nr_delayed_iputs);
2996 spin_lock(&fs_info->delayed_iput_lock);
2997 ASSERT(list_empty(&binode->delayed_iput));
2998 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2999 spin_unlock(&fs_info->delayed_iput_lock);
3000 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3001 wake_up_process(fs_info->cleaner_kthread);
3004 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3005 struct btrfs_inode *inode)
3007 list_del_init(&inode->delayed_iput);
3008 spin_unlock(&fs_info->delayed_iput_lock);
3009 iput(&inode->vfs_inode);
3010 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3011 wake_up(&fs_info->delayed_iputs_wait);
3012 spin_lock(&fs_info->delayed_iput_lock);
3015 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3016 struct btrfs_inode *inode)
3018 if (!list_empty(&inode->delayed_iput)) {
3019 spin_lock(&fs_info->delayed_iput_lock);
3020 if (!list_empty(&inode->delayed_iput))
3021 run_delayed_iput_locked(fs_info, inode);
3022 spin_unlock(&fs_info->delayed_iput_lock);
3026 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3029 spin_lock(&fs_info->delayed_iput_lock);
3030 while (!list_empty(&fs_info->delayed_iputs)) {
3031 struct btrfs_inode *inode;
3033 inode = list_first_entry(&fs_info->delayed_iputs,
3034 struct btrfs_inode, delayed_iput);
3035 run_delayed_iput_locked(fs_info, inode);
3037 spin_unlock(&fs_info->delayed_iput_lock);
3041 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3042 * @fs_info - the fs_info for this fs
3043 * @return - EINTR if we were killed, 0 if nothing's pending
3045 * This will wait on any delayed iputs that are currently running with KILLABLE
3046 * set. Once they are all done running we will return, unless we are killed in
3047 * which case we return EINTR. This helps in user operations like fallocate etc
3048 * that might get blocked on the iputs.
3050 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3052 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3053 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3060 * This creates an orphan entry for the given inode in case something goes wrong
3061 * in the middle of an unlink.
3063 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3064 struct btrfs_inode *inode)
3068 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3069 if (ret && ret != -EEXIST) {
3070 btrfs_abort_transaction(trans, ret);
3078 * We have done the delete so we can go ahead and remove the orphan item for
3079 * this particular inode.
3081 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3082 struct btrfs_inode *inode)
3084 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3088 * this cleans up any orphans that may be left on the list from the last use
3091 int btrfs_orphan_cleanup(struct btrfs_root *root)
3093 struct btrfs_fs_info *fs_info = root->fs_info;
3094 struct btrfs_path *path;
3095 struct extent_buffer *leaf;
3096 struct btrfs_key key, found_key;
3097 struct btrfs_trans_handle *trans;
3098 struct inode *inode;
3099 u64 last_objectid = 0;
3100 int ret = 0, nr_unlink = 0;
3102 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3105 path = btrfs_alloc_path();
3110 path->reada = READA_BACK;
3112 key.objectid = BTRFS_ORPHAN_OBJECTID;
3113 key.type = BTRFS_ORPHAN_ITEM_KEY;
3114 key.offset = (u64)-1;
3117 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3122 * if ret == 0 means we found what we were searching for, which
3123 * is weird, but possible, so only screw with path if we didn't
3124 * find the key and see if we have stuff that matches
3128 if (path->slots[0] == 0)
3133 /* pull out the item */
3134 leaf = path->nodes[0];
3135 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3137 /* make sure the item matches what we want */
3138 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3140 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3143 /* release the path since we're done with it */
3144 btrfs_release_path(path);
3147 * this is where we are basically btrfs_lookup, without the
3148 * crossing root thing. we store the inode number in the
3149 * offset of the orphan item.
3152 if (found_key.offset == last_objectid) {
3154 "Error removing orphan entry, stopping orphan cleanup");
3159 last_objectid = found_key.offset;
3161 found_key.objectid = found_key.offset;
3162 found_key.type = BTRFS_INODE_ITEM_KEY;
3163 found_key.offset = 0;
3164 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3165 ret = PTR_ERR_OR_ZERO(inode);
3166 if (ret && ret != -ENOENT)
3169 if (ret == -ENOENT && root == fs_info->tree_root) {
3170 struct btrfs_root *dead_root;
3171 int is_dead_root = 0;
3174 * this is an orphan in the tree root. Currently these
3175 * could come from 2 sources:
3176 * a) a snapshot deletion in progress
3177 * b) a free space cache inode
3178 * We need to distinguish those two, as the snapshot
3179 * orphan must not get deleted.
3180 * find_dead_roots already ran before us, so if this
3181 * is a snapshot deletion, we should find the root
3182 * in the fs_roots radix tree.
3185 spin_lock(&fs_info->fs_roots_radix_lock);
3186 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3187 (unsigned long)found_key.objectid);
3188 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3190 spin_unlock(&fs_info->fs_roots_radix_lock);
3193 /* prevent this orphan from being found again */
3194 key.offset = found_key.objectid - 1;
3201 * If we have an inode with links, there are a couple of
3202 * possibilities. Old kernels (before v3.12) used to create an
3203 * orphan item for truncate indicating that there were possibly
3204 * extent items past i_size that needed to be deleted. In v3.12,
3205 * truncate was changed to update i_size in sync with the extent
3206 * items, but the (useless) orphan item was still created. Since
3207 * v4.18, we don't create the orphan item for truncate at all.
3209 * So, this item could mean that we need to do a truncate, but
3210 * only if this filesystem was last used on a pre-v3.12 kernel
3211 * and was not cleanly unmounted. The odds of that are quite
3212 * slim, and it's a pain to do the truncate now, so just delete
3215 * It's also possible that this orphan item was supposed to be
3216 * deleted but wasn't. The inode number may have been reused,
3217 * but either way, we can delete the orphan item.
3219 if (ret == -ENOENT || inode->i_nlink) {
3222 trans = btrfs_start_transaction(root, 1);
3223 if (IS_ERR(trans)) {
3224 ret = PTR_ERR(trans);
3227 btrfs_debug(fs_info, "auto deleting %Lu",
3228 found_key.objectid);
3229 ret = btrfs_del_orphan_item(trans, root,
3230 found_key.objectid);
3231 btrfs_end_transaction(trans);
3239 /* this will do delete_inode and everything for us */
3242 /* release the path since we're done with it */
3243 btrfs_release_path(path);
3245 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3247 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3248 trans = btrfs_join_transaction(root);
3250 btrfs_end_transaction(trans);
3254 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3258 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3259 btrfs_free_path(path);
3264 * very simple check to peek ahead in the leaf looking for xattrs. If we
3265 * don't find any xattrs, we know there can't be any acls.
3267 * slot is the slot the inode is in, objectid is the objectid of the inode
3269 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3270 int slot, u64 objectid,
3271 int *first_xattr_slot)
3273 u32 nritems = btrfs_header_nritems(leaf);
3274 struct btrfs_key found_key;
3275 static u64 xattr_access = 0;
3276 static u64 xattr_default = 0;
3279 if (!xattr_access) {
3280 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3281 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3282 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3283 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3287 *first_xattr_slot = -1;
3288 while (slot < nritems) {
3289 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3291 /* we found a different objectid, there must not be acls */
3292 if (found_key.objectid != objectid)
3295 /* we found an xattr, assume we've got an acl */
3296 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3297 if (*first_xattr_slot == -1)
3298 *first_xattr_slot = slot;
3299 if (found_key.offset == xattr_access ||
3300 found_key.offset == xattr_default)
3305 * we found a key greater than an xattr key, there can't
3306 * be any acls later on
3308 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3315 * it goes inode, inode backrefs, xattrs, extents,
3316 * so if there are a ton of hard links to an inode there can
3317 * be a lot of backrefs. Don't waste time searching too hard,
3318 * this is just an optimization
3323 /* we hit the end of the leaf before we found an xattr or
3324 * something larger than an xattr. We have to assume the inode
3327 if (*first_xattr_slot == -1)
3328 *first_xattr_slot = slot;
3333 * read an inode from the btree into the in-memory inode
3335 static int btrfs_read_locked_inode(struct inode *inode,
3336 struct btrfs_path *in_path)
3338 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3339 struct btrfs_path *path = in_path;
3340 struct extent_buffer *leaf;
3341 struct btrfs_inode_item *inode_item;
3342 struct btrfs_root *root = BTRFS_I(inode)->root;
3343 struct btrfs_key location;
3348 bool filled = false;
3349 int first_xattr_slot;
3351 ret = btrfs_fill_inode(inode, &rdev);
3356 path = btrfs_alloc_path();
3361 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3363 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3365 if (path != in_path)
3366 btrfs_free_path(path);
3370 leaf = path->nodes[0];
3375 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3376 struct btrfs_inode_item);
3377 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3378 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3379 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3380 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3381 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3382 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3383 round_up(i_size_read(inode), fs_info->sectorsize));
3385 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3386 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3388 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3389 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3391 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3392 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3394 BTRFS_I(inode)->i_otime.tv_sec =
3395 btrfs_timespec_sec(leaf, &inode_item->otime);
3396 BTRFS_I(inode)->i_otime.tv_nsec =
3397 btrfs_timespec_nsec(leaf, &inode_item->otime);
3399 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3400 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3401 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3403 inode_set_iversion_queried(inode,
3404 btrfs_inode_sequence(leaf, inode_item));
3405 inode->i_generation = BTRFS_I(inode)->generation;
3407 rdev = btrfs_inode_rdev(leaf, inode_item);
3409 BTRFS_I(inode)->index_cnt = (u64)-1;
3410 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3414 * If we were modified in the current generation and evicted from memory
3415 * and then re-read we need to do a full sync since we don't have any
3416 * idea about which extents were modified before we were evicted from
3419 * This is required for both inode re-read from disk and delayed inode
3420 * in delayed_nodes_tree.
3422 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3423 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3424 &BTRFS_I(inode)->runtime_flags);
3427 * We don't persist the id of the transaction where an unlink operation
3428 * against the inode was last made. So here we assume the inode might
3429 * have been evicted, and therefore the exact value of last_unlink_trans
3430 * lost, and set it to last_trans to avoid metadata inconsistencies
3431 * between the inode and its parent if the inode is fsync'ed and the log
3432 * replayed. For example, in the scenario:
3435 * ln mydir/foo mydir/bar
3438 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3439 * xfs_io -c fsync mydir/foo
3441 * mount fs, triggers fsync log replay
3443 * We must make sure that when we fsync our inode foo we also log its
3444 * parent inode, otherwise after log replay the parent still has the
3445 * dentry with the "bar" name but our inode foo has a link count of 1
3446 * and doesn't have an inode ref with the name "bar" anymore.
3448 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3449 * but it guarantees correctness at the expense of occasional full
3450 * transaction commits on fsync if our inode is a directory, or if our
3451 * inode is not a directory, logging its parent unnecessarily.
3453 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3456 * Same logic as for last_unlink_trans. We don't persist the generation
3457 * of the last transaction where this inode was used for a reflink
3458 * operation, so after eviction and reloading the inode we must be
3459 * pessimistic and assume the last transaction that modified the inode.
3461 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3464 if (inode->i_nlink != 1 ||
3465 path->slots[0] >= btrfs_header_nritems(leaf))
3468 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3469 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3472 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3473 if (location.type == BTRFS_INODE_REF_KEY) {
3474 struct btrfs_inode_ref *ref;
3476 ref = (struct btrfs_inode_ref *)ptr;
3477 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3478 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3479 struct btrfs_inode_extref *extref;
3481 extref = (struct btrfs_inode_extref *)ptr;
3482 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3487 * try to precache a NULL acl entry for files that don't have
3488 * any xattrs or acls
3490 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3491 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3492 if (first_xattr_slot != -1) {
3493 path->slots[0] = first_xattr_slot;
3494 ret = btrfs_load_inode_props(inode, path);
3497 "error loading props for ino %llu (root %llu): %d",
3498 btrfs_ino(BTRFS_I(inode)),
3499 root->root_key.objectid, ret);
3501 if (path != in_path)
3502 btrfs_free_path(path);
3505 cache_no_acl(inode);
3507 switch (inode->i_mode & S_IFMT) {
3509 inode->i_mapping->a_ops = &btrfs_aops;
3510 inode->i_fop = &btrfs_file_operations;
3511 inode->i_op = &btrfs_file_inode_operations;
3514 inode->i_fop = &btrfs_dir_file_operations;
3515 inode->i_op = &btrfs_dir_inode_operations;
3518 inode->i_op = &btrfs_symlink_inode_operations;
3519 inode_nohighmem(inode);
3520 inode->i_mapping->a_ops = &btrfs_aops;
3523 inode->i_op = &btrfs_special_inode_operations;
3524 init_special_inode(inode, inode->i_mode, rdev);
3528 btrfs_sync_inode_flags_to_i_flags(inode);
3533 * given a leaf and an inode, copy the inode fields into the leaf
3535 static void fill_inode_item(struct btrfs_trans_handle *trans,
3536 struct extent_buffer *leaf,
3537 struct btrfs_inode_item *item,
3538 struct inode *inode)
3540 struct btrfs_map_token token;
3542 btrfs_init_map_token(&token, leaf);
3544 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3545 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3546 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3547 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3548 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3550 btrfs_set_token_timespec_sec(&token, &item->atime,
3551 inode->i_atime.tv_sec);
3552 btrfs_set_token_timespec_nsec(&token, &item->atime,
3553 inode->i_atime.tv_nsec);
3555 btrfs_set_token_timespec_sec(&token, &item->mtime,
3556 inode->i_mtime.tv_sec);
3557 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3558 inode->i_mtime.tv_nsec);
3560 btrfs_set_token_timespec_sec(&token, &item->ctime,
3561 inode->i_ctime.tv_sec);
3562 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3563 inode->i_ctime.tv_nsec);
3565 btrfs_set_token_timespec_sec(&token, &item->otime,
3566 BTRFS_I(inode)->i_otime.tv_sec);
3567 btrfs_set_token_timespec_nsec(&token, &item->otime,
3568 BTRFS_I(inode)->i_otime.tv_nsec);
3570 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3571 btrfs_set_token_inode_generation(&token, item,
3572 BTRFS_I(inode)->generation);
3573 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3574 btrfs_set_token_inode_transid(&token, item, trans->transid);
3575 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3576 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3577 btrfs_set_token_inode_block_group(&token, item, 0);
3581 * copy everything in the in-memory inode into the btree.
3583 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3584 struct btrfs_root *root, struct inode *inode)
3586 struct btrfs_inode_item *inode_item;
3587 struct btrfs_path *path;
3588 struct extent_buffer *leaf;
3591 path = btrfs_alloc_path();
3595 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3603 leaf = path->nodes[0];
3604 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3605 struct btrfs_inode_item);
3607 fill_inode_item(trans, leaf, inode_item, inode);
3608 btrfs_mark_buffer_dirty(leaf);
3609 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
3612 btrfs_free_path(path);
3617 * copy everything in the in-memory inode into the btree.
3619 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3620 struct btrfs_root *root, struct inode *inode)
3622 struct btrfs_fs_info *fs_info = root->fs_info;
3626 * If the inode is a free space inode, we can deadlock during commit
3627 * if we put it into the delayed code.
3629 * The data relocation inode should also be directly updated
3632 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3633 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3634 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3635 btrfs_update_root_times(trans, root);
3637 ret = btrfs_delayed_update_inode(trans, root, inode);
3639 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
3643 return btrfs_update_inode_item(trans, root, inode);
3646 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3647 struct btrfs_root *root,
3648 struct inode *inode)
3652 ret = btrfs_update_inode(trans, root, inode);
3654 return btrfs_update_inode_item(trans, root, inode);
3659 * unlink helper that gets used here in inode.c and in the tree logging
3660 * recovery code. It remove a link in a directory with a given name, and
3661 * also drops the back refs in the inode to the directory
3663 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3664 struct btrfs_root *root,
3665 struct btrfs_inode *dir,
3666 struct btrfs_inode *inode,
3667 const char *name, int name_len)
3669 struct btrfs_fs_info *fs_info = root->fs_info;
3670 struct btrfs_path *path;
3672 struct btrfs_dir_item *di;
3674 u64 ino = btrfs_ino(inode);
3675 u64 dir_ino = btrfs_ino(dir);
3677 path = btrfs_alloc_path();
3683 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3684 name, name_len, -1);
3685 if (IS_ERR_OR_NULL(di)) {
3686 ret = di ? PTR_ERR(di) : -ENOENT;
3689 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3692 btrfs_release_path(path);
3695 * If we don't have dir index, we have to get it by looking up
3696 * the inode ref, since we get the inode ref, remove it directly,
3697 * it is unnecessary to do delayed deletion.
3699 * But if we have dir index, needn't search inode ref to get it.
3700 * Since the inode ref is close to the inode item, it is better
3701 * that we delay to delete it, and just do this deletion when
3702 * we update the inode item.
3704 if (inode->dir_index) {
3705 ret = btrfs_delayed_delete_inode_ref(inode);
3707 index = inode->dir_index;
3712 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3716 "failed to delete reference to %.*s, inode %llu parent %llu",
3717 name_len, name, ino, dir_ino);
3718 btrfs_abort_transaction(trans, ret);
3722 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3724 btrfs_abort_transaction(trans, ret);
3728 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3730 if (ret != 0 && ret != -ENOENT) {
3731 btrfs_abort_transaction(trans, ret);
3735 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3740 btrfs_abort_transaction(trans, ret);
3743 * If we have a pending delayed iput we could end up with the final iput
3744 * being run in btrfs-cleaner context. If we have enough of these built
3745 * up we can end up burning a lot of time in btrfs-cleaner without any
3746 * way to throttle the unlinks. Since we're currently holding a ref on
3747 * the inode we can run the delayed iput here without any issues as the
3748 * final iput won't be done until after we drop the ref we're currently
3751 btrfs_run_delayed_iput(fs_info, inode);
3753 btrfs_free_path(path);
3757 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3758 inode_inc_iversion(&inode->vfs_inode);
3759 inode_inc_iversion(&dir->vfs_inode);
3760 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3761 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3762 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3767 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3768 struct btrfs_root *root,
3769 struct btrfs_inode *dir, struct btrfs_inode *inode,
3770 const char *name, int name_len)
3773 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3775 drop_nlink(&inode->vfs_inode);
3776 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3782 * helper to start transaction for unlink and rmdir.
3784 * unlink and rmdir are special in btrfs, they do not always free space, so
3785 * if we cannot make our reservations the normal way try and see if there is
3786 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3787 * allow the unlink to occur.
3789 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3791 struct btrfs_root *root = BTRFS_I(dir)->root;
3794 * 1 for the possible orphan item
3795 * 1 for the dir item
3796 * 1 for the dir index
3797 * 1 for the inode ref
3800 return btrfs_start_transaction_fallback_global_rsv(root, 5);
3803 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3805 struct btrfs_root *root = BTRFS_I(dir)->root;
3806 struct btrfs_trans_handle *trans;
3807 struct inode *inode = d_inode(dentry);
3810 trans = __unlink_start_trans(dir);
3812 return PTR_ERR(trans);
3814 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3817 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3818 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3819 dentry->d_name.len);
3823 if (inode->i_nlink == 0) {
3824 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3830 btrfs_end_transaction(trans);
3831 btrfs_btree_balance_dirty(root->fs_info);
3835 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3836 struct inode *dir, struct dentry *dentry)
3838 struct btrfs_root *root = BTRFS_I(dir)->root;
3839 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3840 struct btrfs_path *path;
3841 struct extent_buffer *leaf;
3842 struct btrfs_dir_item *di;
3843 struct btrfs_key key;
3844 const char *name = dentry->d_name.name;
3845 int name_len = dentry->d_name.len;
3849 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3851 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3852 objectid = inode->root->root_key.objectid;
3853 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3854 objectid = inode->location.objectid;
3860 path = btrfs_alloc_path();
3864 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3865 name, name_len, -1);
3866 if (IS_ERR_OR_NULL(di)) {
3867 ret = di ? PTR_ERR(di) : -ENOENT;
3871 leaf = path->nodes[0];
3872 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3873 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3874 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3876 btrfs_abort_transaction(trans, ret);
3879 btrfs_release_path(path);
3882 * This is a placeholder inode for a subvolume we didn't have a
3883 * reference to at the time of the snapshot creation. In the meantime
3884 * we could have renamed the real subvol link into our snapshot, so
3885 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3886 * Instead simply lookup the dir_index_item for this entry so we can
3887 * remove it. Otherwise we know we have a ref to the root and we can
3888 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3890 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3891 di = btrfs_search_dir_index_item(root, path, dir_ino,
3893 if (IS_ERR_OR_NULL(di)) {
3898 btrfs_abort_transaction(trans, ret);
3902 leaf = path->nodes[0];
3903 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3905 btrfs_release_path(path);
3907 ret = btrfs_del_root_ref(trans, objectid,
3908 root->root_key.objectid, dir_ino,
3909 &index, name, name_len);
3911 btrfs_abort_transaction(trans, ret);
3916 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3918 btrfs_abort_transaction(trans, ret);
3922 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3923 inode_inc_iversion(dir);
3924 dir->i_mtime = dir->i_ctime = current_time(dir);
3925 ret = btrfs_update_inode_fallback(trans, root, dir);
3927 btrfs_abort_transaction(trans, ret);
3929 btrfs_free_path(path);
3934 * Helper to check if the subvolume references other subvolumes or if it's
3937 static noinline int may_destroy_subvol(struct btrfs_root *root)
3939 struct btrfs_fs_info *fs_info = root->fs_info;
3940 struct btrfs_path *path;
3941 struct btrfs_dir_item *di;
3942 struct btrfs_key key;
3946 path = btrfs_alloc_path();
3950 /* Make sure this root isn't set as the default subvol */
3951 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3952 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3953 dir_id, "default", 7, 0);
3954 if (di && !IS_ERR(di)) {
3955 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3956 if (key.objectid == root->root_key.objectid) {
3959 "deleting default subvolume %llu is not allowed",
3963 btrfs_release_path(path);
3966 key.objectid = root->root_key.objectid;
3967 key.type = BTRFS_ROOT_REF_KEY;
3968 key.offset = (u64)-1;
3970 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3976 if (path->slots[0] > 0) {
3978 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3979 if (key.objectid == root->root_key.objectid &&
3980 key.type == BTRFS_ROOT_REF_KEY)
3984 btrfs_free_path(path);
3988 /* Delete all dentries for inodes belonging to the root */
3989 static void btrfs_prune_dentries(struct btrfs_root *root)
3991 struct btrfs_fs_info *fs_info = root->fs_info;
3992 struct rb_node *node;
3993 struct rb_node *prev;
3994 struct btrfs_inode *entry;
3995 struct inode *inode;
3998 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3999 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4001 spin_lock(&root->inode_lock);
4003 node = root->inode_tree.rb_node;
4007 entry = rb_entry(node, struct btrfs_inode, rb_node);
4009 if (objectid < btrfs_ino(entry))
4010 node = node->rb_left;
4011 else if (objectid > btrfs_ino(entry))
4012 node = node->rb_right;
4018 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4019 if (objectid <= btrfs_ino(entry)) {
4023 prev = rb_next(prev);
4027 entry = rb_entry(node, struct btrfs_inode, rb_node);
4028 objectid = btrfs_ino(entry) + 1;
4029 inode = igrab(&entry->vfs_inode);
4031 spin_unlock(&root->inode_lock);
4032 if (atomic_read(&inode->i_count) > 1)
4033 d_prune_aliases(inode);
4035 * btrfs_drop_inode will have it removed from the inode
4036 * cache when its usage count hits zero.
4040 spin_lock(&root->inode_lock);
4044 if (cond_resched_lock(&root->inode_lock))
4047 node = rb_next(node);
4049 spin_unlock(&root->inode_lock);
4052 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4054 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4055 struct btrfs_root *root = BTRFS_I(dir)->root;
4056 struct inode *inode = d_inode(dentry);
4057 struct btrfs_root *dest = BTRFS_I(inode)->root;
4058 struct btrfs_trans_handle *trans;
4059 struct btrfs_block_rsv block_rsv;
4065 * Don't allow to delete a subvolume with send in progress. This is
4066 * inside the inode lock so the error handling that has to drop the bit
4067 * again is not run concurrently.
4069 spin_lock(&dest->root_item_lock);
4070 if (dest->send_in_progress) {
4071 spin_unlock(&dest->root_item_lock);
4073 "attempt to delete subvolume %llu during send",
4074 dest->root_key.objectid);
4077 root_flags = btrfs_root_flags(&dest->root_item);
4078 btrfs_set_root_flags(&dest->root_item,
4079 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4080 spin_unlock(&dest->root_item_lock);
4082 down_write(&fs_info->subvol_sem);
4084 err = may_destroy_subvol(dest);
4088 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4090 * One for dir inode,
4091 * two for dir entries,
4092 * two for root ref/backref.
4094 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4098 trans = btrfs_start_transaction(root, 0);
4099 if (IS_ERR(trans)) {
4100 err = PTR_ERR(trans);
4103 trans->block_rsv = &block_rsv;
4104 trans->bytes_reserved = block_rsv.size;
4106 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4108 ret = btrfs_unlink_subvol(trans, dir, dentry);
4111 btrfs_abort_transaction(trans, ret);
4115 btrfs_record_root_in_trans(trans, dest);
4117 memset(&dest->root_item.drop_progress, 0,
4118 sizeof(dest->root_item.drop_progress));
4119 btrfs_set_root_drop_level(&dest->root_item, 0);
4120 btrfs_set_root_refs(&dest->root_item, 0);
4122 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4123 ret = btrfs_insert_orphan_item(trans,
4125 dest->root_key.objectid);
4127 btrfs_abort_transaction(trans, ret);
4133 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4134 BTRFS_UUID_KEY_SUBVOL,
4135 dest->root_key.objectid);
4136 if (ret && ret != -ENOENT) {
4137 btrfs_abort_transaction(trans, ret);
4141 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4142 ret = btrfs_uuid_tree_remove(trans,
4143 dest->root_item.received_uuid,
4144 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4145 dest->root_key.objectid);
4146 if (ret && ret != -ENOENT) {
4147 btrfs_abort_transaction(trans, ret);
4153 free_anon_bdev(dest->anon_dev);
4156 trans->block_rsv = NULL;
4157 trans->bytes_reserved = 0;
4158 ret = btrfs_end_transaction(trans);
4161 inode->i_flags |= S_DEAD;
4163 btrfs_subvolume_release_metadata(root, &block_rsv);
4165 up_write(&fs_info->subvol_sem);
4167 spin_lock(&dest->root_item_lock);
4168 root_flags = btrfs_root_flags(&dest->root_item);
4169 btrfs_set_root_flags(&dest->root_item,
4170 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4171 spin_unlock(&dest->root_item_lock);
4173 d_invalidate(dentry);
4174 btrfs_prune_dentries(dest);
4175 ASSERT(dest->send_in_progress == 0);
4178 if (dest->ino_cache_inode) {
4179 iput(dest->ino_cache_inode);
4180 dest->ino_cache_inode = NULL;
4187 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4189 struct inode *inode = d_inode(dentry);
4191 struct btrfs_root *root = BTRFS_I(dir)->root;
4192 struct btrfs_trans_handle *trans;
4193 u64 last_unlink_trans;
4195 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4197 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4198 return btrfs_delete_subvolume(dir, dentry);
4200 trans = __unlink_start_trans(dir);
4202 return PTR_ERR(trans);
4204 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4205 err = btrfs_unlink_subvol(trans, dir, dentry);
4209 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4213 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4215 /* now the directory is empty */
4216 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4217 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4218 dentry->d_name.len);
4220 btrfs_i_size_write(BTRFS_I(inode), 0);
4222 * Propagate the last_unlink_trans value of the deleted dir to
4223 * its parent directory. This is to prevent an unrecoverable
4224 * log tree in the case we do something like this:
4226 * 2) create snapshot under dir foo
4227 * 3) delete the snapshot
4230 * 6) fsync foo or some file inside foo
4232 if (last_unlink_trans >= trans->transid)
4233 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4236 btrfs_end_transaction(trans);
4237 btrfs_btree_balance_dirty(root->fs_info);
4243 * Return this if we need to call truncate_block for the last bit of the
4246 #define NEED_TRUNCATE_BLOCK 1
4249 * this can truncate away extent items, csum items and directory items.
4250 * It starts at a high offset and removes keys until it can't find
4251 * any higher than new_size
4253 * csum items that cross the new i_size are truncated to the new size
4256 * min_type is the minimum key type to truncate down to. If set to 0, this
4257 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4259 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4260 struct btrfs_root *root,
4261 struct inode *inode,
4262 u64 new_size, u32 min_type)
4264 struct btrfs_fs_info *fs_info = root->fs_info;
4265 struct btrfs_path *path;
4266 struct extent_buffer *leaf;
4267 struct btrfs_file_extent_item *fi;
4268 struct btrfs_key key;
4269 struct btrfs_key found_key;
4270 u64 extent_start = 0;
4271 u64 extent_num_bytes = 0;
4272 u64 extent_offset = 0;
4274 u64 last_size = new_size;
4275 u32 found_type = (u8)-1;
4278 int pending_del_nr = 0;
4279 int pending_del_slot = 0;
4280 int extent_type = -1;
4282 u64 ino = btrfs_ino(BTRFS_I(inode));
4283 u64 bytes_deleted = 0;
4284 bool be_nice = false;
4285 bool should_throttle = false;
4286 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4287 struct extent_state *cached_state = NULL;
4289 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4292 * For non-free space inodes and non-shareable roots, we want to back
4293 * off from time to time. This means all inodes in subvolume roots,
4294 * reloc roots, and data reloc roots.
4296 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4297 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4300 path = btrfs_alloc_path();
4303 path->reada = READA_BACK;
4305 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4306 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4310 * We want to drop from the next block forward in case this
4311 * new size is not block aligned since we will be keeping the
4312 * last block of the extent just the way it is.
4314 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4315 fs_info->sectorsize),
4320 * This function is also used to drop the items in the log tree before
4321 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4322 * it is used to drop the logged items. So we shouldn't kill the delayed
4325 if (min_type == 0 && root == BTRFS_I(inode)->root)
4326 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4329 key.offset = (u64)-1;
4334 * with a 16K leaf size and 128MB extents, you can actually queue
4335 * up a huge file in a single leaf. Most of the time that
4336 * bytes_deleted is > 0, it will be huge by the time we get here
4338 if (be_nice && bytes_deleted > SZ_32M &&
4339 btrfs_should_end_transaction(trans)) {
4344 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4350 /* there are no items in the tree for us to truncate, we're
4353 if (path->slots[0] == 0)
4359 u64 clear_start = 0, clear_len = 0;
4362 leaf = path->nodes[0];
4363 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4364 found_type = found_key.type;
4366 if (found_key.objectid != ino)
4369 if (found_type < min_type)
4372 item_end = found_key.offset;
4373 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4374 fi = btrfs_item_ptr(leaf, path->slots[0],
4375 struct btrfs_file_extent_item);
4376 extent_type = btrfs_file_extent_type(leaf, fi);
4377 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4379 btrfs_file_extent_num_bytes(leaf, fi);
4381 trace_btrfs_truncate_show_fi_regular(
4382 BTRFS_I(inode), leaf, fi,
4384 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4385 item_end += btrfs_file_extent_ram_bytes(leaf,
4388 trace_btrfs_truncate_show_fi_inline(
4389 BTRFS_I(inode), leaf, fi, path->slots[0],
4394 if (found_type > min_type) {
4397 if (item_end < new_size)
4399 if (found_key.offset >= new_size)
4405 /* FIXME, shrink the extent if the ref count is only 1 */
4406 if (found_type != BTRFS_EXTENT_DATA_KEY)
4409 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4412 clear_start = found_key.offset;
4413 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4415 u64 orig_num_bytes =
4416 btrfs_file_extent_num_bytes(leaf, fi);
4417 extent_num_bytes = ALIGN(new_size -
4419 fs_info->sectorsize);
4420 clear_start = ALIGN(new_size, fs_info->sectorsize);
4421 btrfs_set_file_extent_num_bytes(leaf, fi,
4423 num_dec = (orig_num_bytes -
4425 if (test_bit(BTRFS_ROOT_SHAREABLE,
4428 inode_sub_bytes(inode, num_dec);
4429 btrfs_mark_buffer_dirty(leaf);
4432 btrfs_file_extent_disk_num_bytes(leaf,
4434 extent_offset = found_key.offset -
4435 btrfs_file_extent_offset(leaf, fi);
4437 /* FIXME blocksize != 4096 */
4438 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4439 if (extent_start != 0) {
4441 if (test_bit(BTRFS_ROOT_SHAREABLE,
4443 inode_sub_bytes(inode, num_dec);
4446 clear_len = num_dec;
4447 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4449 * we can't truncate inline items that have had
4453 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4454 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4455 btrfs_file_extent_compression(leaf, fi) == 0) {
4456 u32 size = (u32)(new_size - found_key.offset);
4458 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4459 size = btrfs_file_extent_calc_inline_size(size);
4460 btrfs_truncate_item(path, size, 1);
4461 } else if (!del_item) {
4463 * We have to bail so the last_size is set to
4464 * just before this extent.
4466 ret = NEED_TRUNCATE_BLOCK;
4470 * Inline extents are special, we just treat
4471 * them as a full sector worth in the file
4472 * extent tree just for simplicity sake.
4474 clear_len = fs_info->sectorsize;
4477 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4478 inode_sub_bytes(inode, item_end + 1 - new_size);
4482 * We use btrfs_truncate_inode_items() to clean up log trees for
4483 * multiple fsyncs, and in this case we don't want to clear the
4484 * file extent range because it's just the log.
4486 if (root == BTRFS_I(inode)->root) {
4487 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4488 clear_start, clear_len);
4490 btrfs_abort_transaction(trans, ret);
4496 last_size = found_key.offset;
4498 last_size = new_size;
4500 if (!pending_del_nr) {
4501 /* no pending yet, add ourselves */
4502 pending_del_slot = path->slots[0];
4504 } else if (pending_del_nr &&
4505 path->slots[0] + 1 == pending_del_slot) {
4506 /* hop on the pending chunk */
4508 pending_del_slot = path->slots[0];
4515 should_throttle = false;
4518 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4519 struct btrfs_ref ref = { 0 };
4521 bytes_deleted += extent_num_bytes;
4523 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4524 extent_start, extent_num_bytes, 0);
4525 ref.real_root = root->root_key.objectid;
4526 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4527 ino, extent_offset);
4528 ret = btrfs_free_extent(trans, &ref);
4530 btrfs_abort_transaction(trans, ret);
4534 if (btrfs_should_throttle_delayed_refs(trans))
4535 should_throttle = true;
4539 if (found_type == BTRFS_INODE_ITEM_KEY)
4542 if (path->slots[0] == 0 ||
4543 path->slots[0] != pending_del_slot ||
4545 if (pending_del_nr) {
4546 ret = btrfs_del_items(trans, root, path,
4550 btrfs_abort_transaction(trans, ret);
4555 btrfs_release_path(path);
4558 * We can generate a lot of delayed refs, so we need to
4559 * throttle every once and a while and make sure we're
4560 * adding enough space to keep up with the work we are
4561 * generating. Since we hold a transaction here we
4562 * can't flush, and we don't want to FLUSH_LIMIT because
4563 * we could have generated too many delayed refs to
4564 * actually allocate, so just bail if we're short and
4565 * let the normal reservation dance happen higher up.
4567 if (should_throttle) {
4568 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4569 BTRFS_RESERVE_NO_FLUSH);
4581 if (ret >= 0 && pending_del_nr) {
4584 err = btrfs_del_items(trans, root, path, pending_del_slot,
4587 btrfs_abort_transaction(trans, err);
4591 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4592 ASSERT(last_size >= new_size);
4593 if (!ret && last_size > new_size)
4594 last_size = new_size;
4595 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4596 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4597 (u64)-1, &cached_state);
4600 btrfs_free_path(path);
4605 * btrfs_truncate_block - read, zero a chunk and write a block
4606 * @inode - inode that we're zeroing
4607 * @from - the offset to start zeroing
4608 * @len - the length to zero, 0 to zero the entire range respective to the
4610 * @front - zero up to the offset instead of from the offset on
4612 * This will find the block for the "from" offset and cow the block and zero the
4613 * part we want to zero. This is used with truncate and hole punching.
4615 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4618 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4619 struct address_space *mapping = inode->i_mapping;
4620 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4621 struct btrfs_ordered_extent *ordered;
4622 struct extent_state *cached_state = NULL;
4623 struct extent_changeset *data_reserved = NULL;
4625 bool only_release_metadata = false;
4626 u32 blocksize = fs_info->sectorsize;
4627 pgoff_t index = from >> PAGE_SHIFT;
4628 unsigned offset = from & (blocksize - 1);
4630 gfp_t mask = btrfs_alloc_write_mask(mapping);
4631 size_t write_bytes = blocksize;
4636 if (IS_ALIGNED(offset, blocksize) &&
4637 (!len || IS_ALIGNED(len, blocksize)))
4640 block_start = round_down(from, blocksize);
4641 block_end = block_start + blocksize - 1;
4643 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved,
4644 block_start, blocksize);
4646 if (btrfs_check_nocow_lock(BTRFS_I(inode), block_start,
4647 &write_bytes) > 0) {
4648 /* For nocow case, no need to reserve data space */
4649 only_release_metadata = true;
4654 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), blocksize);
4656 if (!only_release_metadata)
4657 btrfs_free_reserved_data_space(BTRFS_I(inode),
4658 data_reserved, block_start, blocksize);
4662 page = find_or_create_page(mapping, index, mask);
4664 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
4665 block_start, blocksize, true);
4666 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4671 if (!PageUptodate(page)) {
4672 ret = btrfs_readpage(NULL, page);
4674 if (page->mapping != mapping) {
4679 if (!PageUptodate(page)) {
4684 wait_on_page_writeback(page);
4686 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4687 set_page_extent_mapped(page);
4689 ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode), block_start);
4691 unlock_extent_cached(io_tree, block_start, block_end,
4695 btrfs_start_ordered_extent(ordered, 1);
4696 btrfs_put_ordered_extent(ordered);
4700 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4701 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4702 0, 0, &cached_state);
4704 ret = btrfs_set_extent_delalloc(BTRFS_I(inode), block_start, block_end, 0,
4707 unlock_extent_cached(io_tree, block_start, block_end,
4712 if (offset != blocksize) {
4714 len = blocksize - offset;
4717 memset(kaddr + (block_start - page_offset(page)),
4720 memset(kaddr + (block_start - page_offset(page)) + offset,
4722 flush_dcache_page(page);
4725 ClearPageChecked(page);
4726 set_page_dirty(page);
4727 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4729 if (only_release_metadata)
4730 set_extent_bit(&BTRFS_I(inode)->io_tree, block_start,
4731 block_end, EXTENT_NORESERVE, NULL, GFP_NOFS);
4735 if (only_release_metadata)
4736 btrfs_delalloc_release_metadata(BTRFS_I(inode),
4739 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
4740 block_start, blocksize, true);
4742 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4746 if (only_release_metadata)
4747 btrfs_check_nocow_unlock(BTRFS_I(inode));
4748 extent_changeset_free(data_reserved);
4752 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4753 u64 offset, u64 len)
4755 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4756 struct btrfs_trans_handle *trans;
4757 struct btrfs_drop_extents_args drop_args = { 0 };
4761 * Still need to make sure the inode looks like it's been updated so
4762 * that any holes get logged if we fsync.
4764 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4765 BTRFS_I(inode)->last_trans = fs_info->generation;
4766 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4767 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4772 * 1 - for the one we're dropping
4773 * 1 - for the one we're adding
4774 * 1 - for updating the inode.
4776 trans = btrfs_start_transaction(root, 3);
4778 return PTR_ERR(trans);
4780 drop_args.start = offset;
4781 drop_args.end = offset + len;
4782 drop_args.drop_cache = true;
4784 ret = btrfs_drop_extents(trans, root, BTRFS_I(inode), &drop_args);
4786 btrfs_abort_transaction(trans, ret);
4787 btrfs_end_transaction(trans);
4791 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4792 offset, 0, 0, len, 0, len, 0, 0, 0);
4794 btrfs_abort_transaction(trans, ret);
4796 btrfs_update_inode(trans, root, inode);
4797 btrfs_end_transaction(trans);
4802 * This function puts in dummy file extents for the area we're creating a hole
4803 * for. So if we are truncating this file to a larger size we need to insert
4804 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4805 * the range between oldsize and size
4807 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4809 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4810 struct btrfs_root *root = BTRFS_I(inode)->root;
4811 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4812 struct extent_map *em = NULL;
4813 struct extent_state *cached_state = NULL;
4814 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4815 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4816 u64 block_end = ALIGN(size, fs_info->sectorsize);
4823 * If our size started in the middle of a block we need to zero out the
4824 * rest of the block before we expand the i_size, otherwise we could
4825 * expose stale data.
4827 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4831 if (size <= hole_start)
4834 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4835 block_end - 1, &cached_state);
4836 cur_offset = hole_start;
4838 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4839 block_end - cur_offset);
4845 last_byte = min(extent_map_end(em), block_end);
4846 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4847 hole_size = last_byte - cur_offset;
4849 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4850 struct extent_map *hole_em;
4852 err = maybe_insert_hole(root, inode, cur_offset,
4857 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4858 cur_offset, hole_size);
4862 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4863 cur_offset + hole_size - 1, 0);
4864 hole_em = alloc_extent_map();
4866 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4867 &BTRFS_I(inode)->runtime_flags);
4870 hole_em->start = cur_offset;
4871 hole_em->len = hole_size;
4872 hole_em->orig_start = cur_offset;
4874 hole_em->block_start = EXTENT_MAP_HOLE;
4875 hole_em->block_len = 0;
4876 hole_em->orig_block_len = 0;
4877 hole_em->ram_bytes = hole_size;
4878 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4879 hole_em->generation = fs_info->generation;
4882 write_lock(&em_tree->lock);
4883 err = add_extent_mapping(em_tree, hole_em, 1);
4884 write_unlock(&em_tree->lock);
4887 btrfs_drop_extent_cache(BTRFS_I(inode),
4892 free_extent_map(hole_em);
4894 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4895 cur_offset, hole_size);
4900 free_extent_map(em);
4902 cur_offset = last_byte;
4903 if (cur_offset >= block_end)
4906 free_extent_map(em);
4907 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4911 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4913 struct btrfs_root *root = BTRFS_I(inode)->root;
4914 struct btrfs_trans_handle *trans;
4915 loff_t oldsize = i_size_read(inode);
4916 loff_t newsize = attr->ia_size;
4917 int mask = attr->ia_valid;
4921 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4922 * special case where we need to update the times despite not having
4923 * these flags set. For all other operations the VFS set these flags
4924 * explicitly if it wants a timestamp update.
4926 if (newsize != oldsize) {
4927 inode_inc_iversion(inode);
4928 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4929 inode->i_ctime = inode->i_mtime =
4930 current_time(inode);
4933 if (newsize > oldsize) {
4935 * Don't do an expanding truncate while snapshotting is ongoing.
4936 * This is to ensure the snapshot captures a fully consistent
4937 * state of this file - if the snapshot captures this expanding
4938 * truncation, it must capture all writes that happened before
4941 btrfs_drew_write_lock(&root->snapshot_lock);
4942 ret = btrfs_cont_expand(inode, oldsize, newsize);
4944 btrfs_drew_write_unlock(&root->snapshot_lock);
4948 trans = btrfs_start_transaction(root, 1);
4949 if (IS_ERR(trans)) {
4950 btrfs_drew_write_unlock(&root->snapshot_lock);
4951 return PTR_ERR(trans);
4954 i_size_write(inode, newsize);
4955 btrfs_inode_safe_disk_i_size_write(inode, 0);
4956 pagecache_isize_extended(inode, oldsize, newsize);
4957 ret = btrfs_update_inode(trans, root, inode);
4958 btrfs_drew_write_unlock(&root->snapshot_lock);
4959 btrfs_end_transaction(trans);
4963 * We're truncating a file that used to have good data down to
4964 * zero. Make sure any new writes to the file get on disk
4968 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
4969 &BTRFS_I(inode)->runtime_flags);
4971 truncate_setsize(inode, newsize);
4973 inode_dio_wait(inode);
4975 ret = btrfs_truncate(inode, newsize == oldsize);
4976 if (ret && inode->i_nlink) {
4980 * Truncate failed, so fix up the in-memory size. We
4981 * adjusted disk_i_size down as we removed extents, so
4982 * wait for disk_i_size to be stable and then update the
4983 * in-memory size to match.
4985 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4988 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4995 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4997 struct inode *inode = d_inode(dentry);
4998 struct btrfs_root *root = BTRFS_I(inode)->root;
5001 if (btrfs_root_readonly(root))
5004 err = setattr_prepare(dentry, attr);
5008 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5009 err = btrfs_setsize(inode, attr);
5014 if (attr->ia_valid) {
5015 setattr_copy(inode, attr);
5016 inode_inc_iversion(inode);
5017 err = btrfs_dirty_inode(inode);
5019 if (!err && attr->ia_valid & ATTR_MODE)
5020 err = posix_acl_chmod(inode, inode->i_mode);
5027 * While truncating the inode pages during eviction, we get the VFS calling
5028 * btrfs_invalidatepage() against each page of the inode. This is slow because
5029 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5030 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5031 * extent_state structures over and over, wasting lots of time.
5033 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5034 * those expensive operations on a per page basis and do only the ordered io
5035 * finishing, while we release here the extent_map and extent_state structures,
5036 * without the excessive merging and splitting.
5038 static void evict_inode_truncate_pages(struct inode *inode)
5040 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5041 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5042 struct rb_node *node;
5044 ASSERT(inode->i_state & I_FREEING);
5045 truncate_inode_pages_final(&inode->i_data);
5047 write_lock(&map_tree->lock);
5048 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5049 struct extent_map *em;
5051 node = rb_first_cached(&map_tree->map);
5052 em = rb_entry(node, struct extent_map, rb_node);
5053 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5054 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5055 remove_extent_mapping(map_tree, em);
5056 free_extent_map(em);
5057 if (need_resched()) {
5058 write_unlock(&map_tree->lock);
5060 write_lock(&map_tree->lock);
5063 write_unlock(&map_tree->lock);
5066 * Keep looping until we have no more ranges in the io tree.
5067 * We can have ongoing bios started by readahead that have
5068 * their endio callback (extent_io.c:end_bio_extent_readpage)
5069 * still in progress (unlocked the pages in the bio but did not yet
5070 * unlocked the ranges in the io tree). Therefore this means some
5071 * ranges can still be locked and eviction started because before
5072 * submitting those bios, which are executed by a separate task (work
5073 * queue kthread), inode references (inode->i_count) were not taken
5074 * (which would be dropped in the end io callback of each bio).
5075 * Therefore here we effectively end up waiting for those bios and
5076 * anyone else holding locked ranges without having bumped the inode's
5077 * reference count - if we don't do it, when they access the inode's
5078 * io_tree to unlock a range it may be too late, leading to an
5079 * use-after-free issue.
5081 spin_lock(&io_tree->lock);
5082 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5083 struct extent_state *state;
5084 struct extent_state *cached_state = NULL;
5087 unsigned state_flags;
5089 node = rb_first(&io_tree->state);
5090 state = rb_entry(node, struct extent_state, rb_node);
5091 start = state->start;
5093 state_flags = state->state;
5094 spin_unlock(&io_tree->lock);
5096 lock_extent_bits(io_tree, start, end, &cached_state);
5099 * If still has DELALLOC flag, the extent didn't reach disk,
5100 * and its reserved space won't be freed by delayed_ref.
5101 * So we need to free its reserved space here.
5102 * (Refer to comment in btrfs_invalidatepage, case 2)
5104 * Note, end is the bytenr of last byte, so we need + 1 here.
5106 if (state_flags & EXTENT_DELALLOC)
5107 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5110 clear_extent_bit(io_tree, start, end,
5111 EXTENT_LOCKED | EXTENT_DELALLOC |
5112 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5116 spin_lock(&io_tree->lock);
5118 spin_unlock(&io_tree->lock);
5121 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5122 struct btrfs_block_rsv *rsv)
5124 struct btrfs_fs_info *fs_info = root->fs_info;
5125 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5126 struct btrfs_trans_handle *trans;
5127 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5131 * Eviction should be taking place at some place safe because of our
5132 * delayed iputs. However the normal flushing code will run delayed
5133 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5135 * We reserve the delayed_refs_extra here again because we can't use
5136 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5137 * above. We reserve our extra bit here because we generate a ton of
5138 * delayed refs activity by truncating.
5140 * If we cannot make our reservation we'll attempt to steal from the
5141 * global reserve, because we really want to be able to free up space.
5143 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5144 BTRFS_RESERVE_FLUSH_EVICT);
5147 * Try to steal from the global reserve if there is space for
5150 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5151 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5153 "could not allocate space for delete; will truncate on mount");
5154 return ERR_PTR(-ENOSPC);
5156 delayed_refs_extra = 0;
5159 trans = btrfs_join_transaction(root);
5163 if (delayed_refs_extra) {
5164 trans->block_rsv = &fs_info->trans_block_rsv;
5165 trans->bytes_reserved = delayed_refs_extra;
5166 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5167 delayed_refs_extra, 1);
5172 void btrfs_evict_inode(struct inode *inode)
5174 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5175 struct btrfs_trans_handle *trans;
5176 struct btrfs_root *root = BTRFS_I(inode)->root;
5177 struct btrfs_block_rsv *rsv;
5180 trace_btrfs_inode_evict(inode);
5187 evict_inode_truncate_pages(inode);
5189 if (inode->i_nlink &&
5190 ((btrfs_root_refs(&root->root_item) != 0 &&
5191 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5192 btrfs_is_free_space_inode(BTRFS_I(inode))))
5195 if (is_bad_inode(inode))
5198 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5200 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5203 if (inode->i_nlink > 0) {
5204 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5205 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5209 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5213 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5216 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5219 btrfs_i_size_write(BTRFS_I(inode), 0);
5222 trans = evict_refill_and_join(root, rsv);
5226 trans->block_rsv = rsv;
5228 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5229 trans->block_rsv = &fs_info->trans_block_rsv;
5230 btrfs_end_transaction(trans);
5231 btrfs_btree_balance_dirty(fs_info);
5232 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5239 * Errors here aren't a big deal, it just means we leave orphan items in
5240 * the tree. They will be cleaned up on the next mount. If the inode
5241 * number gets reused, cleanup deletes the orphan item without doing
5242 * anything, and unlink reuses the existing orphan item.
5244 * If it turns out that we are dropping too many of these, we might want
5245 * to add a mechanism for retrying these after a commit.
5247 trans = evict_refill_and_join(root, rsv);
5248 if (!IS_ERR(trans)) {
5249 trans->block_rsv = rsv;
5250 btrfs_orphan_del(trans, BTRFS_I(inode));
5251 trans->block_rsv = &fs_info->trans_block_rsv;
5252 btrfs_end_transaction(trans);
5255 if (!(root == fs_info->tree_root ||
5256 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5257 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5260 btrfs_free_block_rsv(fs_info, rsv);
5263 * If we didn't successfully delete, the orphan item will still be in
5264 * the tree and we'll retry on the next mount. Again, we might also want
5265 * to retry these periodically in the future.
5267 btrfs_remove_delayed_node(BTRFS_I(inode));
5272 * Return the key found in the dir entry in the location pointer, fill @type
5273 * with BTRFS_FT_*, and return 0.
5275 * If no dir entries were found, returns -ENOENT.
5276 * If found a corrupted location in dir entry, returns -EUCLEAN.
5278 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5279 struct btrfs_key *location, u8 *type)
5281 const char *name = dentry->d_name.name;
5282 int namelen = dentry->d_name.len;
5283 struct btrfs_dir_item *di;
5284 struct btrfs_path *path;
5285 struct btrfs_root *root = BTRFS_I(dir)->root;
5288 path = btrfs_alloc_path();
5292 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5294 if (IS_ERR_OR_NULL(di)) {
5295 ret = di ? PTR_ERR(di) : -ENOENT;
5299 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5300 if (location->type != BTRFS_INODE_ITEM_KEY &&
5301 location->type != BTRFS_ROOT_ITEM_KEY) {
5303 btrfs_warn(root->fs_info,
5304 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5305 __func__, name, btrfs_ino(BTRFS_I(dir)),
5306 location->objectid, location->type, location->offset);
5309 *type = btrfs_dir_type(path->nodes[0], di);
5311 btrfs_free_path(path);
5316 * when we hit a tree root in a directory, the btrfs part of the inode
5317 * needs to be changed to reflect the root directory of the tree root. This
5318 * is kind of like crossing a mount point.
5320 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5322 struct dentry *dentry,
5323 struct btrfs_key *location,
5324 struct btrfs_root **sub_root)
5326 struct btrfs_path *path;
5327 struct btrfs_root *new_root;
5328 struct btrfs_root_ref *ref;
5329 struct extent_buffer *leaf;
5330 struct btrfs_key key;
5334 path = btrfs_alloc_path();
5341 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5342 key.type = BTRFS_ROOT_REF_KEY;
5343 key.offset = location->objectid;
5345 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5352 leaf = path->nodes[0];
5353 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5354 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5355 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5358 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5359 (unsigned long)(ref + 1),
5360 dentry->d_name.len);
5364 btrfs_release_path(path);
5366 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5367 if (IS_ERR(new_root)) {
5368 err = PTR_ERR(new_root);
5372 *sub_root = new_root;
5373 location->objectid = btrfs_root_dirid(&new_root->root_item);
5374 location->type = BTRFS_INODE_ITEM_KEY;
5375 location->offset = 0;
5378 btrfs_free_path(path);
5382 static void inode_tree_add(struct inode *inode)
5384 struct btrfs_root *root = BTRFS_I(inode)->root;
5385 struct btrfs_inode *entry;
5387 struct rb_node *parent;
5388 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5389 u64 ino = btrfs_ino(BTRFS_I(inode));
5391 if (inode_unhashed(inode))
5394 spin_lock(&root->inode_lock);
5395 p = &root->inode_tree.rb_node;
5398 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5400 if (ino < btrfs_ino(entry))
5401 p = &parent->rb_left;
5402 else if (ino > btrfs_ino(entry))
5403 p = &parent->rb_right;
5405 WARN_ON(!(entry->vfs_inode.i_state &
5406 (I_WILL_FREE | I_FREEING)));
5407 rb_replace_node(parent, new, &root->inode_tree);
5408 RB_CLEAR_NODE(parent);
5409 spin_unlock(&root->inode_lock);
5413 rb_link_node(new, parent, p);
5414 rb_insert_color(new, &root->inode_tree);
5415 spin_unlock(&root->inode_lock);
5418 static void inode_tree_del(struct btrfs_inode *inode)
5420 struct btrfs_root *root = inode->root;
5423 spin_lock(&root->inode_lock);
5424 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5425 rb_erase(&inode->rb_node, &root->inode_tree);
5426 RB_CLEAR_NODE(&inode->rb_node);
5427 empty = RB_EMPTY_ROOT(&root->inode_tree);
5429 spin_unlock(&root->inode_lock);
5431 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5432 spin_lock(&root->inode_lock);
5433 empty = RB_EMPTY_ROOT(&root->inode_tree);
5434 spin_unlock(&root->inode_lock);
5436 btrfs_add_dead_root(root);
5441 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5443 struct btrfs_iget_args *args = p;
5445 inode->i_ino = args->ino;
5446 BTRFS_I(inode)->location.objectid = args->ino;
5447 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5448 BTRFS_I(inode)->location.offset = 0;
5449 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5450 BUG_ON(args->root && !BTRFS_I(inode)->root);
5454 static int btrfs_find_actor(struct inode *inode, void *opaque)
5456 struct btrfs_iget_args *args = opaque;
5458 return args->ino == BTRFS_I(inode)->location.objectid &&
5459 args->root == BTRFS_I(inode)->root;
5462 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5463 struct btrfs_root *root)
5465 struct inode *inode;
5466 struct btrfs_iget_args args;
5467 unsigned long hashval = btrfs_inode_hash(ino, root);
5472 inode = iget5_locked(s, hashval, btrfs_find_actor,
5473 btrfs_init_locked_inode,
5479 * Get an inode object given its inode number and corresponding root.
5480 * Path can be preallocated to prevent recursing back to iget through
5481 * allocator. NULL is also valid but may require an additional allocation
5484 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5485 struct btrfs_root *root, struct btrfs_path *path)
5487 struct inode *inode;
5489 inode = btrfs_iget_locked(s, ino, root);
5491 return ERR_PTR(-ENOMEM);
5493 if (inode->i_state & I_NEW) {
5496 ret = btrfs_read_locked_inode(inode, path);
5498 inode_tree_add(inode);
5499 unlock_new_inode(inode);
5503 * ret > 0 can come from btrfs_search_slot called by
5504 * btrfs_read_locked_inode, this means the inode item
5509 inode = ERR_PTR(ret);
5516 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5518 return btrfs_iget_path(s, ino, root, NULL);
5521 static struct inode *new_simple_dir(struct super_block *s,
5522 struct btrfs_key *key,
5523 struct btrfs_root *root)
5525 struct inode *inode = new_inode(s);
5528 return ERR_PTR(-ENOMEM);
5530 BTRFS_I(inode)->root = btrfs_grab_root(root);
5531 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5532 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5534 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5536 * We only need lookup, the rest is read-only and there's no inode
5537 * associated with the dentry
5539 inode->i_op = &simple_dir_inode_operations;
5540 inode->i_opflags &= ~IOP_XATTR;
5541 inode->i_fop = &simple_dir_operations;
5542 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5543 inode->i_mtime = current_time(inode);
5544 inode->i_atime = inode->i_mtime;
5545 inode->i_ctime = inode->i_mtime;
5546 BTRFS_I(inode)->i_otime = inode->i_mtime;
5551 static inline u8 btrfs_inode_type(struct inode *inode)
5554 * Compile-time asserts that generic FT_* types still match
5557 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5558 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5559 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5560 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5561 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5562 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5563 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5564 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5566 return fs_umode_to_ftype(inode->i_mode);
5569 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5571 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5572 struct inode *inode;
5573 struct btrfs_root *root = BTRFS_I(dir)->root;
5574 struct btrfs_root *sub_root = root;
5575 struct btrfs_key location;
5579 if (dentry->d_name.len > BTRFS_NAME_LEN)
5580 return ERR_PTR(-ENAMETOOLONG);
5582 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5584 return ERR_PTR(ret);
5586 if (location.type == BTRFS_INODE_ITEM_KEY) {
5587 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5591 /* Do extra check against inode mode with di_type */
5592 if (btrfs_inode_type(inode) != di_type) {
5594 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5595 inode->i_mode, btrfs_inode_type(inode),
5598 return ERR_PTR(-EUCLEAN);
5603 ret = fixup_tree_root_location(fs_info, dir, dentry,
5604 &location, &sub_root);
5607 inode = ERR_PTR(ret);
5609 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5611 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5613 if (root != sub_root)
5614 btrfs_put_root(sub_root);
5616 if (!IS_ERR(inode) && root != sub_root) {
5617 down_read(&fs_info->cleanup_work_sem);
5618 if (!sb_rdonly(inode->i_sb))
5619 ret = btrfs_orphan_cleanup(sub_root);
5620 up_read(&fs_info->cleanup_work_sem);
5623 inode = ERR_PTR(ret);
5630 static int btrfs_dentry_delete(const struct dentry *dentry)
5632 struct btrfs_root *root;
5633 struct inode *inode = d_inode(dentry);
5635 if (!inode && !IS_ROOT(dentry))
5636 inode = d_inode(dentry->d_parent);
5639 root = BTRFS_I(inode)->root;
5640 if (btrfs_root_refs(&root->root_item) == 0)
5643 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5649 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5652 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5654 if (inode == ERR_PTR(-ENOENT))
5656 return d_splice_alias(inode, dentry);
5660 * All this infrastructure exists because dir_emit can fault, and we are holding
5661 * the tree lock when doing readdir. For now just allocate a buffer and copy
5662 * our information into that, and then dir_emit from the buffer. This is
5663 * similar to what NFS does, only we don't keep the buffer around in pagecache
5664 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5665 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5668 static int btrfs_opendir(struct inode *inode, struct file *file)
5670 struct btrfs_file_private *private;
5672 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5675 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5676 if (!private->filldir_buf) {
5680 file->private_data = private;
5691 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5694 struct dir_entry *entry = addr;
5695 char *name = (char *)(entry + 1);
5697 ctx->pos = get_unaligned(&entry->offset);
5698 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5699 get_unaligned(&entry->ino),
5700 get_unaligned(&entry->type)))
5702 addr += sizeof(struct dir_entry) +
5703 get_unaligned(&entry->name_len);
5709 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5711 struct inode *inode = file_inode(file);
5712 struct btrfs_root *root = BTRFS_I(inode)->root;
5713 struct btrfs_file_private *private = file->private_data;
5714 struct btrfs_dir_item *di;
5715 struct btrfs_key key;
5716 struct btrfs_key found_key;
5717 struct btrfs_path *path;
5719 struct list_head ins_list;
5720 struct list_head del_list;
5722 struct extent_buffer *leaf;
5729 struct btrfs_key location;
5731 if (!dir_emit_dots(file, ctx))
5734 path = btrfs_alloc_path();
5738 addr = private->filldir_buf;
5739 path->reada = READA_FORWARD;
5741 INIT_LIST_HEAD(&ins_list);
5742 INIT_LIST_HEAD(&del_list);
5743 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5746 key.type = BTRFS_DIR_INDEX_KEY;
5747 key.offset = ctx->pos;
5748 key.objectid = btrfs_ino(BTRFS_I(inode));
5750 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5755 struct dir_entry *entry;
5757 leaf = path->nodes[0];
5758 slot = path->slots[0];
5759 if (slot >= btrfs_header_nritems(leaf)) {
5760 ret = btrfs_next_leaf(root, path);
5768 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5770 if (found_key.objectid != key.objectid)
5772 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5774 if (found_key.offset < ctx->pos)
5776 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5778 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5779 name_len = btrfs_dir_name_len(leaf, di);
5780 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5782 btrfs_release_path(path);
5783 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5786 addr = private->filldir_buf;
5793 put_unaligned(name_len, &entry->name_len);
5794 name_ptr = (char *)(entry + 1);
5795 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5797 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5799 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5800 put_unaligned(location.objectid, &entry->ino);
5801 put_unaligned(found_key.offset, &entry->offset);
5803 addr += sizeof(struct dir_entry) + name_len;
5804 total_len += sizeof(struct dir_entry) + name_len;
5808 btrfs_release_path(path);
5810 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5814 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5819 * Stop new entries from being returned after we return the last
5822 * New directory entries are assigned a strictly increasing
5823 * offset. This means that new entries created during readdir
5824 * are *guaranteed* to be seen in the future by that readdir.
5825 * This has broken buggy programs which operate on names as
5826 * they're returned by readdir. Until we re-use freed offsets
5827 * we have this hack to stop new entries from being returned
5828 * under the assumption that they'll never reach this huge
5831 * This is being careful not to overflow 32bit loff_t unless the
5832 * last entry requires it because doing so has broken 32bit apps
5835 if (ctx->pos >= INT_MAX)
5836 ctx->pos = LLONG_MAX;
5843 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5844 btrfs_free_path(path);
5849 * This is somewhat expensive, updating the tree every time the
5850 * inode changes. But, it is most likely to find the inode in cache.
5851 * FIXME, needs more benchmarking...there are no reasons other than performance
5852 * to keep or drop this code.
5854 static int btrfs_dirty_inode(struct inode *inode)
5856 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5857 struct btrfs_root *root = BTRFS_I(inode)->root;
5858 struct btrfs_trans_handle *trans;
5861 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5864 trans = btrfs_join_transaction(root);
5866 return PTR_ERR(trans);
5868 ret = btrfs_update_inode(trans, root, inode);
5869 if (ret && ret == -ENOSPC) {
5870 /* whoops, lets try again with the full transaction */
5871 btrfs_end_transaction(trans);
5872 trans = btrfs_start_transaction(root, 1);
5874 return PTR_ERR(trans);
5876 ret = btrfs_update_inode(trans, root, inode);
5878 btrfs_end_transaction(trans);
5879 if (BTRFS_I(inode)->delayed_node)
5880 btrfs_balance_delayed_items(fs_info);
5886 * This is a copy of file_update_time. We need this so we can return error on
5887 * ENOSPC for updating the inode in the case of file write and mmap writes.
5889 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5892 struct btrfs_root *root = BTRFS_I(inode)->root;
5893 bool dirty = flags & ~S_VERSION;
5895 if (btrfs_root_readonly(root))
5898 if (flags & S_VERSION)
5899 dirty |= inode_maybe_inc_iversion(inode, dirty);
5900 if (flags & S_CTIME)
5901 inode->i_ctime = *now;
5902 if (flags & S_MTIME)
5903 inode->i_mtime = *now;
5904 if (flags & S_ATIME)
5905 inode->i_atime = *now;
5906 return dirty ? btrfs_dirty_inode(inode) : 0;
5910 * find the highest existing sequence number in a directory
5911 * and then set the in-memory index_cnt variable to reflect
5912 * free sequence numbers
5914 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5916 struct btrfs_root *root = inode->root;
5917 struct btrfs_key key, found_key;
5918 struct btrfs_path *path;
5919 struct extent_buffer *leaf;
5922 key.objectid = btrfs_ino(inode);
5923 key.type = BTRFS_DIR_INDEX_KEY;
5924 key.offset = (u64)-1;
5926 path = btrfs_alloc_path();
5930 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5933 /* FIXME: we should be able to handle this */
5939 * MAGIC NUMBER EXPLANATION:
5940 * since we search a directory based on f_pos we have to start at 2
5941 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5942 * else has to start at 2
5944 if (path->slots[0] == 0) {
5945 inode->index_cnt = 2;
5951 leaf = path->nodes[0];
5952 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5954 if (found_key.objectid != btrfs_ino(inode) ||
5955 found_key.type != BTRFS_DIR_INDEX_KEY) {
5956 inode->index_cnt = 2;
5960 inode->index_cnt = found_key.offset + 1;
5962 btrfs_free_path(path);
5967 * helper to find a free sequence number in a given directory. This current
5968 * code is very simple, later versions will do smarter things in the btree
5970 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5974 if (dir->index_cnt == (u64)-1) {
5975 ret = btrfs_inode_delayed_dir_index_count(dir);
5977 ret = btrfs_set_inode_index_count(dir);
5983 *index = dir->index_cnt;
5989 static int btrfs_insert_inode_locked(struct inode *inode)
5991 struct btrfs_iget_args args;
5993 args.ino = BTRFS_I(inode)->location.objectid;
5994 args.root = BTRFS_I(inode)->root;
5996 return insert_inode_locked4(inode,
5997 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5998 btrfs_find_actor, &args);
6002 * Inherit flags from the parent inode.
6004 * Currently only the compression flags and the cow flags are inherited.
6006 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6013 flags = BTRFS_I(dir)->flags;
6015 if (flags & BTRFS_INODE_NOCOMPRESS) {
6016 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6017 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6018 } else if (flags & BTRFS_INODE_COMPRESS) {
6019 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6020 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6023 if (flags & BTRFS_INODE_NODATACOW) {
6024 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6025 if (S_ISREG(inode->i_mode))
6026 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6029 btrfs_sync_inode_flags_to_i_flags(inode);
6032 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6033 struct btrfs_root *root,
6035 const char *name, int name_len,
6036 u64 ref_objectid, u64 objectid,
6037 umode_t mode, u64 *index)
6039 struct btrfs_fs_info *fs_info = root->fs_info;
6040 struct inode *inode;
6041 struct btrfs_inode_item *inode_item;
6042 struct btrfs_key *location;
6043 struct btrfs_path *path;
6044 struct btrfs_inode_ref *ref;
6045 struct btrfs_key key[2];
6047 int nitems = name ? 2 : 1;
6049 unsigned int nofs_flag;
6052 path = btrfs_alloc_path();
6054 return ERR_PTR(-ENOMEM);
6056 nofs_flag = memalloc_nofs_save();
6057 inode = new_inode(fs_info->sb);
6058 memalloc_nofs_restore(nofs_flag);
6060 btrfs_free_path(path);
6061 return ERR_PTR(-ENOMEM);
6065 * O_TMPFILE, set link count to 0, so that after this point,
6066 * we fill in an inode item with the correct link count.
6069 set_nlink(inode, 0);
6072 * we have to initialize this early, so we can reclaim the inode
6073 * number if we fail afterwards in this function.
6075 inode->i_ino = objectid;
6078 trace_btrfs_inode_request(dir);
6080 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6082 btrfs_free_path(path);
6084 return ERR_PTR(ret);
6090 * index_cnt is ignored for everything but a dir,
6091 * btrfs_set_inode_index_count has an explanation for the magic
6094 BTRFS_I(inode)->index_cnt = 2;
6095 BTRFS_I(inode)->dir_index = *index;
6096 BTRFS_I(inode)->root = btrfs_grab_root(root);
6097 BTRFS_I(inode)->generation = trans->transid;
6098 inode->i_generation = BTRFS_I(inode)->generation;
6101 * We could have gotten an inode number from somebody who was fsynced
6102 * and then removed in this same transaction, so let's just set full
6103 * sync since it will be a full sync anyway and this will blow away the
6104 * old info in the log.
6106 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6108 key[0].objectid = objectid;
6109 key[0].type = BTRFS_INODE_ITEM_KEY;
6112 sizes[0] = sizeof(struct btrfs_inode_item);
6116 * Start new inodes with an inode_ref. This is slightly more
6117 * efficient for small numbers of hard links since they will
6118 * be packed into one item. Extended refs will kick in if we
6119 * add more hard links than can fit in the ref item.
6121 key[1].objectid = objectid;
6122 key[1].type = BTRFS_INODE_REF_KEY;
6123 key[1].offset = ref_objectid;
6125 sizes[1] = name_len + sizeof(*ref);
6128 location = &BTRFS_I(inode)->location;
6129 location->objectid = objectid;
6130 location->offset = 0;
6131 location->type = BTRFS_INODE_ITEM_KEY;
6133 ret = btrfs_insert_inode_locked(inode);
6139 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6143 inode_init_owner(inode, dir, mode);
6144 inode_set_bytes(inode, 0);
6146 inode->i_mtime = current_time(inode);
6147 inode->i_atime = inode->i_mtime;
6148 inode->i_ctime = inode->i_mtime;
6149 BTRFS_I(inode)->i_otime = inode->i_mtime;
6151 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6152 struct btrfs_inode_item);
6153 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6154 sizeof(*inode_item));
6155 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6158 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6159 struct btrfs_inode_ref);
6160 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6161 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6162 ptr = (unsigned long)(ref + 1);
6163 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6166 btrfs_mark_buffer_dirty(path->nodes[0]);
6167 btrfs_free_path(path);
6169 btrfs_inherit_iflags(inode, dir);
6171 if (S_ISREG(mode)) {
6172 if (btrfs_test_opt(fs_info, NODATASUM))
6173 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6174 if (btrfs_test_opt(fs_info, NODATACOW))
6175 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6176 BTRFS_INODE_NODATASUM;
6179 inode_tree_add(inode);
6181 trace_btrfs_inode_new(inode);
6182 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6184 btrfs_update_root_times(trans, root);
6186 ret = btrfs_inode_inherit_props(trans, inode, dir);
6189 "error inheriting props for ino %llu (root %llu): %d",
6190 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6195 discard_new_inode(inode);
6198 BTRFS_I(dir)->index_cnt--;
6199 btrfs_free_path(path);
6200 return ERR_PTR(ret);
6204 * utility function to add 'inode' into 'parent_inode' with
6205 * a give name and a given sequence number.
6206 * if 'add_backref' is true, also insert a backref from the
6207 * inode to the parent directory.
6209 int btrfs_add_link(struct btrfs_trans_handle *trans,
6210 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6211 const char *name, int name_len, int add_backref, u64 index)
6214 struct btrfs_key key;
6215 struct btrfs_root *root = parent_inode->root;
6216 u64 ino = btrfs_ino(inode);
6217 u64 parent_ino = btrfs_ino(parent_inode);
6219 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6220 memcpy(&key, &inode->root->root_key, sizeof(key));
6223 key.type = BTRFS_INODE_ITEM_KEY;
6227 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6228 ret = btrfs_add_root_ref(trans, key.objectid,
6229 root->root_key.objectid, parent_ino,
6230 index, name, name_len);
6231 } else if (add_backref) {
6232 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6236 /* Nothing to clean up yet */
6240 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6241 btrfs_inode_type(&inode->vfs_inode), index);
6242 if (ret == -EEXIST || ret == -EOVERFLOW)
6245 btrfs_abort_transaction(trans, ret);
6249 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6251 inode_inc_iversion(&parent_inode->vfs_inode);
6253 * If we are replaying a log tree, we do not want to update the mtime
6254 * and ctime of the parent directory with the current time, since the
6255 * log replay procedure is responsible for setting them to their correct
6256 * values (the ones it had when the fsync was done).
6258 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6259 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6261 parent_inode->vfs_inode.i_mtime = now;
6262 parent_inode->vfs_inode.i_ctime = now;
6264 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6266 btrfs_abort_transaction(trans, ret);
6270 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6273 err = btrfs_del_root_ref(trans, key.objectid,
6274 root->root_key.objectid, parent_ino,
6275 &local_index, name, name_len);
6277 btrfs_abort_transaction(trans, err);
6278 } else if (add_backref) {
6282 err = btrfs_del_inode_ref(trans, root, name, name_len,
6283 ino, parent_ino, &local_index);
6285 btrfs_abort_transaction(trans, err);
6288 /* Return the original error code */
6292 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6293 struct btrfs_inode *dir, struct dentry *dentry,
6294 struct btrfs_inode *inode, int backref, u64 index)
6296 int err = btrfs_add_link(trans, dir, inode,
6297 dentry->d_name.name, dentry->d_name.len,
6304 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6305 umode_t mode, dev_t rdev)
6307 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6308 struct btrfs_trans_handle *trans;
6309 struct btrfs_root *root = BTRFS_I(dir)->root;
6310 struct inode *inode = NULL;
6316 * 2 for inode item and ref
6318 * 1 for xattr if selinux is on
6320 trans = btrfs_start_transaction(root, 5);
6322 return PTR_ERR(trans);
6324 err = btrfs_find_free_ino(root, &objectid);
6328 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6329 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6331 if (IS_ERR(inode)) {
6332 err = PTR_ERR(inode);
6338 * If the active LSM wants to access the inode during
6339 * d_instantiate it needs these. Smack checks to see
6340 * if the filesystem supports xattrs by looking at the
6343 inode->i_op = &btrfs_special_inode_operations;
6344 init_special_inode(inode, inode->i_mode, rdev);
6346 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6350 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6355 btrfs_update_inode(trans, root, inode);
6356 d_instantiate_new(dentry, inode);
6359 btrfs_end_transaction(trans);
6360 btrfs_btree_balance_dirty(fs_info);
6362 inode_dec_link_count(inode);
6363 discard_new_inode(inode);
6368 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6369 umode_t mode, bool excl)
6371 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6372 struct btrfs_trans_handle *trans;
6373 struct btrfs_root *root = BTRFS_I(dir)->root;
6374 struct inode *inode = NULL;
6380 * 2 for inode item and ref
6382 * 1 for xattr if selinux is on
6384 trans = btrfs_start_transaction(root, 5);
6386 return PTR_ERR(trans);
6388 err = btrfs_find_free_ino(root, &objectid);
6392 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6393 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6395 if (IS_ERR(inode)) {
6396 err = PTR_ERR(inode);
6401 * If the active LSM wants to access the inode during
6402 * d_instantiate it needs these. Smack checks to see
6403 * if the filesystem supports xattrs by looking at the
6406 inode->i_fop = &btrfs_file_operations;
6407 inode->i_op = &btrfs_file_inode_operations;
6408 inode->i_mapping->a_ops = &btrfs_aops;
6410 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6414 err = btrfs_update_inode(trans, root, inode);
6418 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6423 d_instantiate_new(dentry, inode);
6426 btrfs_end_transaction(trans);
6428 inode_dec_link_count(inode);
6429 discard_new_inode(inode);
6431 btrfs_btree_balance_dirty(fs_info);
6435 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6436 struct dentry *dentry)
6438 struct btrfs_trans_handle *trans = NULL;
6439 struct btrfs_root *root = BTRFS_I(dir)->root;
6440 struct inode *inode = d_inode(old_dentry);
6441 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6446 /* do not allow sys_link's with other subvols of the same device */
6447 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6450 if (inode->i_nlink >= BTRFS_LINK_MAX)
6453 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6458 * 2 items for inode and inode ref
6459 * 2 items for dir items
6460 * 1 item for parent inode
6461 * 1 item for orphan item deletion if O_TMPFILE
6463 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6464 if (IS_ERR(trans)) {
6465 err = PTR_ERR(trans);
6470 /* There are several dir indexes for this inode, clear the cache. */
6471 BTRFS_I(inode)->dir_index = 0ULL;
6473 inode_inc_iversion(inode);
6474 inode->i_ctime = current_time(inode);
6476 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6478 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6484 struct dentry *parent = dentry->d_parent;
6486 err = btrfs_update_inode(trans, root, inode);
6489 if (inode->i_nlink == 1) {
6491 * If new hard link count is 1, it's a file created
6492 * with open(2) O_TMPFILE flag.
6494 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6498 d_instantiate(dentry, inode);
6499 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6504 btrfs_end_transaction(trans);
6506 inode_dec_link_count(inode);
6509 btrfs_btree_balance_dirty(fs_info);
6513 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6515 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6516 struct inode *inode = NULL;
6517 struct btrfs_trans_handle *trans;
6518 struct btrfs_root *root = BTRFS_I(dir)->root;
6524 * 2 items for inode and ref
6525 * 2 items for dir items
6526 * 1 for xattr if selinux is on
6528 trans = btrfs_start_transaction(root, 5);
6530 return PTR_ERR(trans);
6532 err = btrfs_find_free_ino(root, &objectid);
6536 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6537 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6538 S_IFDIR | mode, &index);
6539 if (IS_ERR(inode)) {
6540 err = PTR_ERR(inode);
6545 /* these must be set before we unlock the inode */
6546 inode->i_op = &btrfs_dir_inode_operations;
6547 inode->i_fop = &btrfs_dir_file_operations;
6549 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6553 btrfs_i_size_write(BTRFS_I(inode), 0);
6554 err = btrfs_update_inode(trans, root, inode);
6558 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6559 dentry->d_name.name,
6560 dentry->d_name.len, 0, index);
6564 d_instantiate_new(dentry, inode);
6567 btrfs_end_transaction(trans);
6569 inode_dec_link_count(inode);
6570 discard_new_inode(inode);
6572 btrfs_btree_balance_dirty(fs_info);
6576 static noinline int uncompress_inline(struct btrfs_path *path,
6578 size_t pg_offset, u64 extent_offset,
6579 struct btrfs_file_extent_item *item)
6582 struct extent_buffer *leaf = path->nodes[0];
6585 unsigned long inline_size;
6589 WARN_ON(pg_offset != 0);
6590 compress_type = btrfs_file_extent_compression(leaf, item);
6591 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6592 inline_size = btrfs_file_extent_inline_item_len(leaf,
6593 btrfs_item_nr(path->slots[0]));
6594 tmp = kmalloc(inline_size, GFP_NOFS);
6597 ptr = btrfs_file_extent_inline_start(item);
6599 read_extent_buffer(leaf, tmp, ptr, inline_size);
6601 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6602 ret = btrfs_decompress(compress_type, tmp, page,
6603 extent_offset, inline_size, max_size);
6606 * decompression code contains a memset to fill in any space between the end
6607 * of the uncompressed data and the end of max_size in case the decompressed
6608 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6609 * the end of an inline extent and the beginning of the next block, so we
6610 * cover that region here.
6613 if (max_size + pg_offset < PAGE_SIZE) {
6614 char *map = kmap(page);
6615 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6623 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6624 * @inode: file to search in
6625 * @page: page to read extent data into if the extent is inline
6626 * @pg_offset: offset into @page to copy to
6627 * @start: file offset
6628 * @len: length of range starting at @start
6630 * This returns the first &struct extent_map which overlaps with the given
6631 * range, reading it from the B-tree and caching it if necessary. Note that
6632 * there may be more extents which overlap the given range after the returned
6635 * If @page is not NULL and the extent is inline, this also reads the extent
6636 * data directly into the page and marks the extent up to date in the io_tree.
6638 * Return: ERR_PTR on error, non-NULL extent_map on success.
6640 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6641 struct page *page, size_t pg_offset,
6644 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6646 u64 extent_start = 0;
6648 u64 objectid = btrfs_ino(inode);
6649 int extent_type = -1;
6650 struct btrfs_path *path = NULL;
6651 struct btrfs_root *root = inode->root;
6652 struct btrfs_file_extent_item *item;
6653 struct extent_buffer *leaf;
6654 struct btrfs_key found_key;
6655 struct extent_map *em = NULL;
6656 struct extent_map_tree *em_tree = &inode->extent_tree;
6657 struct extent_io_tree *io_tree = &inode->io_tree;
6659 read_lock(&em_tree->lock);
6660 em = lookup_extent_mapping(em_tree, start, len);
6661 read_unlock(&em_tree->lock);
6664 if (em->start > start || em->start + em->len <= start)
6665 free_extent_map(em);
6666 else if (em->block_start == EXTENT_MAP_INLINE && page)
6667 free_extent_map(em);
6671 em = alloc_extent_map();
6676 em->start = EXTENT_MAP_HOLE;
6677 em->orig_start = EXTENT_MAP_HOLE;
6679 em->block_len = (u64)-1;
6681 path = btrfs_alloc_path();
6687 /* Chances are we'll be called again, so go ahead and do readahead */
6688 path->reada = READA_FORWARD;
6691 * The same explanation in load_free_space_cache applies here as well,
6692 * we only read when we're loading the free space cache, and at that
6693 * point the commit_root has everything we need.
6695 if (btrfs_is_free_space_inode(inode)) {
6696 path->search_commit_root = 1;
6697 path->skip_locking = 1;
6700 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6703 } else if (ret > 0) {
6704 if (path->slots[0] == 0)
6710 leaf = path->nodes[0];
6711 item = btrfs_item_ptr(leaf, path->slots[0],
6712 struct btrfs_file_extent_item);
6713 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6714 if (found_key.objectid != objectid ||
6715 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6717 * If we backup past the first extent we want to move forward
6718 * and see if there is an extent in front of us, otherwise we'll
6719 * say there is a hole for our whole search range which can
6726 extent_type = btrfs_file_extent_type(leaf, item);
6727 extent_start = found_key.offset;
6728 extent_end = btrfs_file_extent_end(path);
6729 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6730 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6731 /* Only regular file could have regular/prealloc extent */
6732 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6735 "regular/prealloc extent found for non-regular inode %llu",
6739 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6741 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6742 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6747 if (start >= extent_end) {
6749 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6750 ret = btrfs_next_leaf(root, path);
6756 leaf = path->nodes[0];
6758 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6759 if (found_key.objectid != objectid ||
6760 found_key.type != BTRFS_EXTENT_DATA_KEY)
6762 if (start + len <= found_key.offset)
6764 if (start > found_key.offset)
6767 /* New extent overlaps with existing one */
6769 em->orig_start = start;
6770 em->len = found_key.offset - start;
6771 em->block_start = EXTENT_MAP_HOLE;
6775 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6777 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6778 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6780 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6784 size_t extent_offset;
6790 size = btrfs_file_extent_ram_bytes(leaf, item);
6791 extent_offset = page_offset(page) + pg_offset - extent_start;
6792 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6793 size - extent_offset);
6794 em->start = extent_start + extent_offset;
6795 em->len = ALIGN(copy_size, fs_info->sectorsize);
6796 em->orig_block_len = em->len;
6797 em->orig_start = em->start;
6798 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6800 if (!PageUptodate(page)) {
6801 if (btrfs_file_extent_compression(leaf, item) !=
6802 BTRFS_COMPRESS_NONE) {
6803 ret = uncompress_inline(path, page, pg_offset,
6804 extent_offset, item);
6809 read_extent_buffer(leaf, map + pg_offset, ptr,
6811 if (pg_offset + copy_size < PAGE_SIZE) {
6812 memset(map + pg_offset + copy_size, 0,
6813 PAGE_SIZE - pg_offset -
6818 flush_dcache_page(page);
6820 set_extent_uptodate(io_tree, em->start,
6821 extent_map_end(em) - 1, NULL, GFP_NOFS);
6826 em->orig_start = start;
6828 em->block_start = EXTENT_MAP_HOLE;
6831 btrfs_release_path(path);
6832 if (em->start > start || extent_map_end(em) <= start) {
6834 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6835 em->start, em->len, start, len);
6840 write_lock(&em_tree->lock);
6841 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6842 write_unlock(&em_tree->lock);
6844 btrfs_free_path(path);
6846 trace_btrfs_get_extent(root, inode, em);
6849 free_extent_map(em);
6850 return ERR_PTR(ret);
6855 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6858 struct extent_map *em;
6859 struct extent_map *hole_em = NULL;
6860 u64 delalloc_start = start;
6866 em = btrfs_get_extent(inode, NULL, 0, start, len);
6870 * If our em maps to:
6872 * - a pre-alloc extent,
6873 * there might actually be delalloc bytes behind it.
6875 if (em->block_start != EXTENT_MAP_HOLE &&
6876 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6881 /* check to see if we've wrapped (len == -1 or similar) */
6890 /* ok, we didn't find anything, lets look for delalloc */
6891 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6892 end, len, EXTENT_DELALLOC, 1);
6893 delalloc_end = delalloc_start + delalloc_len;
6894 if (delalloc_end < delalloc_start)
6895 delalloc_end = (u64)-1;
6898 * We didn't find anything useful, return the original results from
6901 if (delalloc_start > end || delalloc_end <= start) {
6908 * Adjust the delalloc_start to make sure it doesn't go backwards from
6909 * the start they passed in
6911 delalloc_start = max(start, delalloc_start);
6912 delalloc_len = delalloc_end - delalloc_start;
6914 if (delalloc_len > 0) {
6917 const u64 hole_end = extent_map_end(hole_em);
6919 em = alloc_extent_map();
6927 * When btrfs_get_extent can't find anything it returns one
6930 * Make sure what it found really fits our range, and adjust to
6931 * make sure it is based on the start from the caller
6933 if (hole_end <= start || hole_em->start > end) {
6934 free_extent_map(hole_em);
6937 hole_start = max(hole_em->start, start);
6938 hole_len = hole_end - hole_start;
6941 if (hole_em && delalloc_start > hole_start) {
6943 * Our hole starts before our delalloc, so we have to
6944 * return just the parts of the hole that go until the
6947 em->len = min(hole_len, delalloc_start - hole_start);
6948 em->start = hole_start;
6949 em->orig_start = hole_start;
6951 * Don't adjust block start at all, it is fixed at
6954 em->block_start = hole_em->block_start;
6955 em->block_len = hole_len;
6956 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6957 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6960 * Hole is out of passed range or it starts after
6963 em->start = delalloc_start;
6964 em->len = delalloc_len;
6965 em->orig_start = delalloc_start;
6966 em->block_start = EXTENT_MAP_DELALLOC;
6967 em->block_len = delalloc_len;
6974 free_extent_map(hole_em);
6976 free_extent_map(em);
6977 return ERR_PTR(err);
6982 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
6985 const u64 orig_start,
6986 const u64 block_start,
6987 const u64 block_len,
6988 const u64 orig_block_len,
6989 const u64 ram_bytes,
6992 struct extent_map *em = NULL;
6995 if (type != BTRFS_ORDERED_NOCOW) {
6996 em = create_io_em(inode, start, len, orig_start, block_start,
6997 block_len, orig_block_len, ram_bytes,
6998 BTRFS_COMPRESS_NONE, /* compress_type */
7003 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7007 free_extent_map(em);
7008 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7017 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7020 struct btrfs_root *root = inode->root;
7021 struct btrfs_fs_info *fs_info = root->fs_info;
7022 struct extent_map *em;
7023 struct btrfs_key ins;
7027 alloc_hint = get_extent_allocation_hint(inode, start, len);
7028 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7029 0, alloc_hint, &ins, 1, 1);
7031 return ERR_PTR(ret);
7033 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7034 ins.objectid, ins.offset, ins.offset,
7035 ins.offset, BTRFS_ORDERED_REGULAR);
7036 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7038 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7045 * Check if we can do nocow write into the range [@offset, @offset + @len)
7047 * @offset: File offset
7048 * @len: The length to write, will be updated to the nocow writeable
7050 * @orig_start: (optional) Return the original file offset of the file extent
7051 * @orig_len: (optional) Return the original on-disk length of the file extent
7052 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7053 * @strict: if true, omit optimizations that might force us into unnecessary
7054 * cow. e.g., don't trust generation number.
7056 * This function will flush ordered extents in the range to ensure proper
7057 * nocow checks for (nowait == false) case.
7060 * >0 and update @len if we can do nocow write
7061 * 0 if we can't do nocow write
7062 * <0 if error happened
7064 * NOTE: This only checks the file extents, caller is responsible to wait for
7065 * any ordered extents.
7067 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7068 u64 *orig_start, u64 *orig_block_len,
7069 u64 *ram_bytes, bool strict)
7071 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7072 struct btrfs_path *path;
7074 struct extent_buffer *leaf;
7075 struct btrfs_root *root = BTRFS_I(inode)->root;
7076 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7077 struct btrfs_file_extent_item *fi;
7078 struct btrfs_key key;
7085 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7087 path = btrfs_alloc_path();
7091 ret = btrfs_lookup_file_extent(NULL, root, path,
7092 btrfs_ino(BTRFS_I(inode)), offset, 0);
7096 slot = path->slots[0];
7099 /* can't find the item, must cow */
7106 leaf = path->nodes[0];
7107 btrfs_item_key_to_cpu(leaf, &key, slot);
7108 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7109 key.type != BTRFS_EXTENT_DATA_KEY) {
7110 /* not our file or wrong item type, must cow */
7114 if (key.offset > offset) {
7115 /* Wrong offset, must cow */
7119 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7120 found_type = btrfs_file_extent_type(leaf, fi);
7121 if (found_type != BTRFS_FILE_EXTENT_REG &&
7122 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7123 /* not a regular extent, must cow */
7127 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7130 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7131 if (extent_end <= offset)
7134 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7135 if (disk_bytenr == 0)
7138 if (btrfs_file_extent_compression(leaf, fi) ||
7139 btrfs_file_extent_encryption(leaf, fi) ||
7140 btrfs_file_extent_other_encoding(leaf, fi))
7144 * Do the same check as in btrfs_cross_ref_exist but without the
7145 * unnecessary search.
7148 (btrfs_file_extent_generation(leaf, fi) <=
7149 btrfs_root_last_snapshot(&root->root_item)))
7152 backref_offset = btrfs_file_extent_offset(leaf, fi);
7155 *orig_start = key.offset - backref_offset;
7156 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7157 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7160 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7163 num_bytes = min(offset + *len, extent_end) - offset;
7164 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7167 range_end = round_up(offset + num_bytes,
7168 root->fs_info->sectorsize) - 1;
7169 ret = test_range_bit(io_tree, offset, range_end,
7170 EXTENT_DELALLOC, 0, NULL);
7177 btrfs_release_path(path);
7180 * look for other files referencing this extent, if we
7181 * find any we must cow
7184 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7185 key.offset - backref_offset, disk_bytenr,
7193 * adjust disk_bytenr and num_bytes to cover just the bytes
7194 * in this extent we are about to write. If there
7195 * are any csums in that range we have to cow in order
7196 * to keep the csums correct
7198 disk_bytenr += backref_offset;
7199 disk_bytenr += offset - key.offset;
7200 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7203 * all of the above have passed, it is safe to overwrite this extent
7209 btrfs_free_path(path);
7213 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7214 struct extent_state **cached_state, bool writing)
7216 struct btrfs_ordered_extent *ordered;
7220 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7223 * We're concerned with the entire range that we're going to be
7224 * doing DIO to, so we need to make sure there's no ordered
7225 * extents in this range.
7227 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7228 lockend - lockstart + 1);
7231 * We need to make sure there are no buffered pages in this
7232 * range either, we could have raced between the invalidate in
7233 * generic_file_direct_write and locking the extent. The
7234 * invalidate needs to happen so that reads after a write do not
7238 (!writing || !filemap_range_has_page(inode->i_mapping,
7239 lockstart, lockend)))
7242 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7247 * If we are doing a DIO read and the ordered extent we
7248 * found is for a buffered write, we can not wait for it
7249 * to complete and retry, because if we do so we can
7250 * deadlock with concurrent buffered writes on page
7251 * locks. This happens only if our DIO read covers more
7252 * than one extent map, if at this point has already
7253 * created an ordered extent for a previous extent map
7254 * and locked its range in the inode's io tree, and a
7255 * concurrent write against that previous extent map's
7256 * range and this range started (we unlock the ranges
7257 * in the io tree only when the bios complete and
7258 * buffered writes always lock pages before attempting
7259 * to lock range in the io tree).
7262 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7263 btrfs_start_ordered_extent(ordered, 1);
7266 btrfs_put_ordered_extent(ordered);
7269 * We could trigger writeback for this range (and wait
7270 * for it to complete) and then invalidate the pages for
7271 * this range (through invalidate_inode_pages2_range()),
7272 * but that can lead us to a deadlock with a concurrent
7273 * call to readahead (a buffered read or a defrag call
7274 * triggered a readahead) on a page lock due to an
7275 * ordered dio extent we created before but did not have
7276 * yet a corresponding bio submitted (whence it can not
7277 * complete), which makes readahead wait for that
7278 * ordered extent to complete while holding a lock on
7293 /* The callers of this must take lock_extent() */
7294 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7295 u64 len, u64 orig_start, u64 block_start,
7296 u64 block_len, u64 orig_block_len,
7297 u64 ram_bytes, int compress_type,
7300 struct extent_map_tree *em_tree;
7301 struct extent_map *em;
7304 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7305 type == BTRFS_ORDERED_COMPRESSED ||
7306 type == BTRFS_ORDERED_NOCOW ||
7307 type == BTRFS_ORDERED_REGULAR);
7309 em_tree = &inode->extent_tree;
7310 em = alloc_extent_map();
7312 return ERR_PTR(-ENOMEM);
7315 em->orig_start = orig_start;
7317 em->block_len = block_len;
7318 em->block_start = block_start;
7319 em->orig_block_len = orig_block_len;
7320 em->ram_bytes = ram_bytes;
7321 em->generation = -1;
7322 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7323 if (type == BTRFS_ORDERED_PREALLOC) {
7324 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7325 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7326 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7327 em->compress_type = compress_type;
7331 btrfs_drop_extent_cache(inode, em->start,
7332 em->start + em->len - 1, 0);
7333 write_lock(&em_tree->lock);
7334 ret = add_extent_mapping(em_tree, em, 1);
7335 write_unlock(&em_tree->lock);
7337 * The caller has taken lock_extent(), who could race with us
7340 } while (ret == -EEXIST);
7343 free_extent_map(em);
7344 return ERR_PTR(ret);
7347 /* em got 2 refs now, callers needs to do free_extent_map once. */
7352 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7353 struct inode *inode,
7354 struct btrfs_dio_data *dio_data,
7357 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7358 struct extent_map *em = *map;
7362 * We don't allocate a new extent in the following cases
7364 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7366 * 2) The extent is marked as PREALLOC. We're good to go here and can
7367 * just use the extent.
7370 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7371 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7372 em->block_start != EXTENT_MAP_HOLE)) {
7374 u64 block_start, orig_start, orig_block_len, ram_bytes;
7376 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7377 type = BTRFS_ORDERED_PREALLOC;
7379 type = BTRFS_ORDERED_NOCOW;
7380 len = min(len, em->len - (start - em->start));
7381 block_start = em->block_start + (start - em->start);
7383 if (can_nocow_extent(inode, start, &len, &orig_start,
7384 &orig_block_len, &ram_bytes, false) == 1 &&
7385 btrfs_inc_nocow_writers(fs_info, block_start)) {
7386 struct extent_map *em2;
7388 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7389 orig_start, block_start,
7390 len, orig_block_len,
7392 btrfs_dec_nocow_writers(fs_info, block_start);
7393 if (type == BTRFS_ORDERED_PREALLOC) {
7394 free_extent_map(em);
7398 if (em2 && IS_ERR(em2)) {
7403 * For inode marked NODATACOW or extent marked PREALLOC,
7404 * use the existing or preallocated extent, so does not
7405 * need to adjust btrfs_space_info's bytes_may_use.
7407 btrfs_free_reserved_data_space_noquota(fs_info, len);
7412 /* this will cow the extent */
7413 free_extent_map(em);
7414 *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7420 len = min(len, em->len - (start - em->start));
7424 * Need to update the i_size under the extent lock so buffered
7425 * readers will get the updated i_size when we unlock.
7427 if (start + len > i_size_read(inode))
7428 i_size_write(inode, start + len);
7430 dio_data->reserve -= len;
7435 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7436 loff_t length, unsigned int flags, struct iomap *iomap,
7437 struct iomap *srcmap)
7439 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7440 struct extent_map *em;
7441 struct extent_state *cached_state = NULL;
7442 struct btrfs_dio_data *dio_data = NULL;
7443 u64 lockstart, lockend;
7444 const bool write = !!(flags & IOMAP_WRITE);
7447 bool unlock_extents = false;
7450 len = min_t(u64, len, fs_info->sectorsize);
7453 lockend = start + len - 1;
7456 * The generic stuff only does filemap_write_and_wait_range, which
7457 * isn't enough if we've written compressed pages to this area, so we
7458 * need to flush the dirty pages again to make absolutely sure that any
7459 * outstanding dirty pages are on disk.
7461 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7462 &BTRFS_I(inode)->runtime_flags)) {
7463 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7464 start + length - 1);
7469 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7473 dio_data->length = length;
7475 dio_data->reserve = round_up(length, fs_info->sectorsize);
7476 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7477 &dio_data->data_reserved,
7478 start, dio_data->reserve);
7480 extent_changeset_free(dio_data->data_reserved);
7485 iomap->private = dio_data;
7489 * If this errors out it's because we couldn't invalidate pagecache for
7490 * this range and we need to fallback to buffered.
7492 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7497 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7504 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7505 * io. INLINE is special, and we could probably kludge it in here, but
7506 * it's still buffered so for safety lets just fall back to the generic
7509 * For COMPRESSED we _have_ to read the entire extent in so we can
7510 * decompress it, so there will be buffering required no matter what we
7511 * do, so go ahead and fallback to buffered.
7513 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7514 * to buffered IO. Don't blame me, this is the price we pay for using
7517 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7518 em->block_start == EXTENT_MAP_INLINE) {
7519 free_extent_map(em);
7524 len = min(len, em->len - (start - em->start));
7526 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7530 unlock_extents = true;
7531 /* Recalc len in case the new em is smaller than requested */
7532 len = min(len, em->len - (start - em->start));
7535 * We need to unlock only the end area that we aren't using.
7536 * The rest is going to be unlocked by the endio routine.
7538 lockstart = start + len;
7539 if (lockstart < lockend)
7540 unlock_extents = true;
7544 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7545 lockstart, lockend, &cached_state);
7547 free_extent_state(cached_state);
7550 * Translate extent map information to iomap.
7551 * We trim the extents (and move the addr) even though iomap code does
7552 * that, since we have locked only the parts we are performing I/O in.
7554 if ((em->block_start == EXTENT_MAP_HOLE) ||
7555 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7556 iomap->addr = IOMAP_NULL_ADDR;
7557 iomap->type = IOMAP_HOLE;
7559 iomap->addr = em->block_start + (start - em->start);
7560 iomap->type = IOMAP_MAPPED;
7562 iomap->offset = start;
7563 iomap->bdev = fs_info->fs_devices->latest_bdev;
7564 iomap->length = len;
7566 free_extent_map(em);
7571 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7575 btrfs_delalloc_release_space(BTRFS_I(inode),
7576 dio_data->data_reserved, start,
7577 dio_data->reserve, true);
7578 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7579 extent_changeset_free(dio_data->data_reserved);
7585 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7586 ssize_t written, unsigned int flags, struct iomap *iomap)
7589 struct btrfs_dio_data *dio_data = iomap->private;
7590 size_t submitted = dio_data->submitted;
7591 const bool write = !!(flags & IOMAP_WRITE);
7593 if (!write && (iomap->type == IOMAP_HOLE)) {
7594 /* If reading from a hole, unlock and return */
7595 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7599 if (submitted < length) {
7601 length -= submitted;
7603 __endio_write_update_ordered(BTRFS_I(inode), pos,
7606 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7612 if (dio_data->reserve)
7613 btrfs_delalloc_release_space(BTRFS_I(inode),
7614 dio_data->data_reserved, pos,
7615 dio_data->reserve, true);
7616 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7617 extent_changeset_free(dio_data->data_reserved);
7621 iomap->private = NULL;
7626 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7629 * This implies a barrier so that stores to dio_bio->bi_status before
7630 * this and loads of dio_bio->bi_status after this are fully ordered.
7632 if (!refcount_dec_and_test(&dip->refs))
7635 if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7636 __endio_write_update_ordered(BTRFS_I(dip->inode),
7637 dip->logical_offset,
7639 !dip->dio_bio->bi_status);
7641 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7642 dip->logical_offset,
7643 dip->logical_offset + dip->bytes - 1);
7646 bio_endio(dip->dio_bio);
7650 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7652 unsigned long bio_flags)
7654 struct btrfs_dio_private *dip = bio->bi_private;
7655 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7658 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7660 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7664 refcount_inc(&dip->refs);
7665 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7667 refcount_dec(&dip->refs);
7671 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7672 struct btrfs_io_bio *io_bio,
7673 const bool uptodate)
7675 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7676 const u32 sectorsize = fs_info->sectorsize;
7677 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7678 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7679 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7680 struct bio_vec bvec;
7681 struct bvec_iter iter;
7682 u64 start = io_bio->logical;
7684 blk_status_t err = BLK_STS_OK;
7686 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7687 unsigned int i, nr_sectors, pgoff;
7689 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7690 pgoff = bvec.bv_offset;
7691 for (i = 0; i < nr_sectors; i++) {
7692 ASSERT(pgoff < PAGE_SIZE);
7694 (!csum || !check_data_csum(inode, io_bio, icsum,
7695 bvec.bv_page, pgoff))) {
7696 clean_io_failure(fs_info, failure_tree, io_tree,
7697 start, bvec.bv_page,
7698 btrfs_ino(BTRFS_I(inode)),
7701 blk_status_t status;
7703 status = btrfs_submit_read_repair(inode,
7705 start - io_bio->logical,
7706 bvec.bv_page, pgoff,
7708 start + sectorsize - 1,
7710 submit_dio_repair_bio);
7714 start += sectorsize;
7716 pgoff += sectorsize;
7722 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7723 const u64 offset, const u64 bytes,
7724 const bool uptodate)
7726 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7727 struct btrfs_ordered_extent *ordered = NULL;
7728 struct btrfs_workqueue *wq;
7729 u64 ordered_offset = offset;
7730 u64 ordered_bytes = bytes;
7733 if (btrfs_is_free_space_inode(inode))
7734 wq = fs_info->endio_freespace_worker;
7736 wq = fs_info->endio_write_workers;
7738 while (ordered_offset < offset + bytes) {
7739 last_offset = ordered_offset;
7740 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7744 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7746 btrfs_queue_work(wq, &ordered->work);
7749 * If btrfs_dec_test_ordered_pending does not find any ordered
7750 * extent in the range, we can exit.
7752 if (ordered_offset == last_offset)
7755 * Our bio might span multiple ordered extents. In this case
7756 * we keep going until we have accounted the whole dio.
7758 if (ordered_offset < offset + bytes) {
7759 ordered_bytes = offset + bytes - ordered_offset;
7765 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7766 struct bio *bio, u64 offset)
7768 return btrfs_csum_one_bio(BTRFS_I(inode), bio, offset, 1);
7771 static void btrfs_end_dio_bio(struct bio *bio)
7773 struct btrfs_dio_private *dip = bio->bi_private;
7774 blk_status_t err = bio->bi_status;
7777 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7778 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7779 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7781 (unsigned long long)bio->bi_iter.bi_sector,
7782 bio->bi_iter.bi_size, err);
7784 if (bio_op(bio) == REQ_OP_READ) {
7785 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7790 dip->dio_bio->bi_status = err;
7793 btrfs_dio_private_put(dip);
7796 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7797 struct inode *inode, u64 file_offset, int async_submit)
7799 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7800 struct btrfs_dio_private *dip = bio->bi_private;
7801 bool write = bio_op(bio) == REQ_OP_WRITE;
7804 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7806 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7809 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7814 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7817 if (write && async_submit) {
7818 ret = btrfs_wq_submit_bio(inode, bio, 0, 0,
7820 btrfs_submit_bio_start_direct_io);
7824 * If we aren't doing async submit, calculate the csum of the
7827 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
7833 csum_offset = file_offset - dip->logical_offset;
7834 csum_offset >>= fs_info->sectorsize_bits;
7835 csum_offset *= fs_info->csum_size;
7836 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
7839 ret = btrfs_map_bio(fs_info, bio, 0);
7845 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7846 * or ordered extents whether or not we submit any bios.
7848 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7849 struct inode *inode,
7852 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7853 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7855 struct btrfs_dio_private *dip;
7857 dip_size = sizeof(*dip);
7858 if (!write && csum) {
7859 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7862 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
7863 dip_size += fs_info->csum_size * nblocks;
7866 dip = kzalloc(dip_size, GFP_NOFS);
7871 dip->logical_offset = file_offset;
7872 dip->bytes = dio_bio->bi_iter.bi_size;
7873 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7874 dip->dio_bio = dio_bio;
7875 refcount_set(&dip->refs, 1);
7879 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
7880 struct bio *dio_bio, loff_t file_offset)
7882 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7883 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7884 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7885 BTRFS_BLOCK_GROUP_RAID56_MASK);
7886 struct btrfs_dio_private *dip;
7889 int async_submit = 0;
7891 int clone_offset = 0;
7894 blk_status_t status;
7895 struct btrfs_io_geometry geom;
7896 struct btrfs_dio_data *dio_data = iomap->private;
7898 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7901 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7902 file_offset + dio_bio->bi_iter.bi_size - 1);
7904 dio_bio->bi_status = BLK_STS_RESOURCE;
7906 return BLK_QC_T_NONE;
7911 * Load the csums up front to reduce csum tree searches and
7912 * contention when submitting bios.
7914 * If we have csums disabled this will do nothing.
7916 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7918 if (status != BLK_STS_OK)
7922 start_sector = dio_bio->bi_iter.bi_sector;
7923 submit_len = dio_bio->bi_iter.bi_size;
7926 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7927 start_sector << 9, submit_len,
7930 status = errno_to_blk_status(ret);
7933 ASSERT(geom.len <= INT_MAX);
7935 clone_len = min_t(int, submit_len, geom.len);
7938 * This will never fail as it's passing GPF_NOFS and
7939 * the allocation is backed by btrfs_bioset.
7941 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
7942 bio->bi_private = dip;
7943 bio->bi_end_io = btrfs_end_dio_bio;
7944 btrfs_io_bio(bio)->logical = file_offset;
7946 ASSERT(submit_len >= clone_len);
7947 submit_len -= clone_len;
7950 * Increase the count before we submit the bio so we know
7951 * the end IO handler won't happen before we increase the
7952 * count. Otherwise, the dip might get freed before we're
7953 * done setting it up.
7955 * We transfer the initial reference to the last bio, so we
7956 * don't need to increment the reference count for the last one.
7958 if (submit_len > 0) {
7959 refcount_inc(&dip->refs);
7961 * If we are submitting more than one bio, submit them
7962 * all asynchronously. The exception is RAID 5 or 6, as
7963 * asynchronous checksums make it difficult to collect
7964 * full stripe writes.
7970 status = btrfs_submit_dio_bio(bio, inode, file_offset,
7975 refcount_dec(&dip->refs);
7979 dio_data->submitted += clone_len;
7980 clone_offset += clone_len;
7981 start_sector += clone_len >> 9;
7982 file_offset += clone_len;
7983 } while (submit_len > 0);
7984 return BLK_QC_T_NONE;
7987 dip->dio_bio->bi_status = status;
7988 btrfs_dio_private_put(dip);
7989 return BLK_QC_T_NONE;
7992 const struct iomap_ops btrfs_dio_iomap_ops = {
7993 .iomap_begin = btrfs_dio_iomap_begin,
7994 .iomap_end = btrfs_dio_iomap_end,
7997 const struct iomap_dio_ops btrfs_dio_ops = {
7998 .submit_io = btrfs_submit_direct,
8001 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8006 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8010 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8013 int btrfs_readpage(struct file *file, struct page *page)
8015 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8016 u64 start = page_offset(page);
8017 u64 end = start + PAGE_SIZE - 1;
8018 unsigned long bio_flags = 0;
8019 struct bio *bio = NULL;
8022 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8024 ret = btrfs_do_readpage(page, NULL, &bio, &bio_flags, 0, NULL);
8026 ret = submit_one_bio(bio, 0, bio_flags);
8030 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8032 struct inode *inode = page->mapping->host;
8035 if (current->flags & PF_MEMALLOC) {
8036 redirty_page_for_writepage(wbc, page);
8042 * If we are under memory pressure we will call this directly from the
8043 * VM, we need to make sure we have the inode referenced for the ordered
8044 * extent. If not just return like we didn't do anything.
8046 if (!igrab(inode)) {
8047 redirty_page_for_writepage(wbc, page);
8048 return AOP_WRITEPAGE_ACTIVATE;
8050 ret = extent_write_full_page(page, wbc);
8051 btrfs_add_delayed_iput(inode);
8055 static int btrfs_writepages(struct address_space *mapping,
8056 struct writeback_control *wbc)
8058 return extent_writepages(mapping, wbc);
8061 static void btrfs_readahead(struct readahead_control *rac)
8063 extent_readahead(rac);
8066 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8068 int ret = try_release_extent_mapping(page, gfp_flags);
8070 detach_page_private(page);
8074 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8076 if (PageWriteback(page) || PageDirty(page))
8078 return __btrfs_releasepage(page, gfp_flags);
8081 #ifdef CONFIG_MIGRATION
8082 static int btrfs_migratepage(struct address_space *mapping,
8083 struct page *newpage, struct page *page,
8084 enum migrate_mode mode)
8088 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8089 if (ret != MIGRATEPAGE_SUCCESS)
8092 if (page_has_private(page))
8093 attach_page_private(newpage, detach_page_private(page));
8095 if (PagePrivate2(page)) {
8096 ClearPagePrivate2(page);
8097 SetPagePrivate2(newpage);
8100 if (mode != MIGRATE_SYNC_NO_COPY)
8101 migrate_page_copy(newpage, page);
8103 migrate_page_states(newpage, page);
8104 return MIGRATEPAGE_SUCCESS;
8108 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8109 unsigned int length)
8111 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8112 struct extent_io_tree *tree = &inode->io_tree;
8113 struct btrfs_ordered_extent *ordered;
8114 struct extent_state *cached_state = NULL;
8115 u64 page_start = page_offset(page);
8116 u64 page_end = page_start + PAGE_SIZE - 1;
8119 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8122 * we have the page locked, so new writeback can't start,
8123 * and the dirty bit won't be cleared while we are here.
8125 * Wait for IO on this page so that we can safely clear
8126 * the PagePrivate2 bit and do ordered accounting
8128 wait_on_page_writeback(page);
8131 btrfs_releasepage(page, GFP_NOFS);
8135 if (!inode_evicting)
8136 lock_extent_bits(tree, page_start, page_end, &cached_state);
8139 ordered = btrfs_lookup_ordered_range(inode, start, page_end - start + 1);
8142 ordered->file_offset + ordered->num_bytes - 1);
8144 * IO on this page will never be started, so we need
8145 * to account for any ordered extents now
8147 if (!inode_evicting)
8148 clear_extent_bit(tree, start, end,
8149 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8150 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8151 EXTENT_DEFRAG, 1, 0, &cached_state);
8153 * whoever cleared the private bit is responsible
8154 * for the finish_ordered_io
8156 if (TestClearPagePrivate2(page)) {
8157 struct btrfs_ordered_inode_tree *tree;
8160 tree = &inode->ordered_tree;
8162 spin_lock_irq(&tree->lock);
8163 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8164 new_len = start - ordered->file_offset;
8165 if (new_len < ordered->truncated_len)
8166 ordered->truncated_len = new_len;
8167 spin_unlock_irq(&tree->lock);
8169 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8171 end - start + 1, 1))
8172 btrfs_finish_ordered_io(ordered);
8174 btrfs_put_ordered_extent(ordered);
8175 if (!inode_evicting) {
8176 cached_state = NULL;
8177 lock_extent_bits(tree, start, end,
8182 if (start < page_end)
8187 * Qgroup reserved space handler
8188 * Page here will be either
8189 * 1) Already written to disk or ordered extent already submitted
8190 * Then its QGROUP_RESERVED bit in io_tree is already cleaned.
8191 * Qgroup will be handled by its qgroup_record then.
8192 * btrfs_qgroup_free_data() call will do nothing here.
8194 * 2) Not written to disk yet
8195 * Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED
8196 * bit of its io_tree, and free the qgroup reserved data space.
8197 * Since the IO will never happen for this page.
8199 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8200 if (!inode_evicting) {
8201 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8202 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8203 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8206 __btrfs_releasepage(page, GFP_NOFS);
8209 ClearPageChecked(page);
8210 detach_page_private(page);
8214 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8215 * called from a page fault handler when a page is first dirtied. Hence we must
8216 * be careful to check for EOF conditions here. We set the page up correctly
8217 * for a written page which means we get ENOSPC checking when writing into
8218 * holes and correct delalloc and unwritten extent mapping on filesystems that
8219 * support these features.
8221 * We are not allowed to take the i_mutex here so we have to play games to
8222 * protect against truncate races as the page could now be beyond EOF. Because
8223 * truncate_setsize() writes the inode size before removing pages, once we have
8224 * the page lock we can determine safely if the page is beyond EOF. If it is not
8225 * beyond EOF, then the page is guaranteed safe against truncation until we
8228 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8230 struct page *page = vmf->page;
8231 struct inode *inode = file_inode(vmf->vma->vm_file);
8232 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8233 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8234 struct btrfs_ordered_extent *ordered;
8235 struct extent_state *cached_state = NULL;
8236 struct extent_changeset *data_reserved = NULL;
8238 unsigned long zero_start;
8248 reserved_space = PAGE_SIZE;
8250 sb_start_pagefault(inode->i_sb);
8251 page_start = page_offset(page);
8252 page_end = page_start + PAGE_SIZE - 1;
8256 * Reserving delalloc space after obtaining the page lock can lead to
8257 * deadlock. For example, if a dirty page is locked by this function
8258 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8259 * dirty page write out, then the btrfs_writepage() function could
8260 * end up waiting indefinitely to get a lock on the page currently
8261 * being processed by btrfs_page_mkwrite() function.
8263 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8264 page_start, reserved_space);
8266 ret2 = file_update_time(vmf->vma->vm_file);
8270 ret = vmf_error(ret2);
8276 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8279 size = i_size_read(inode);
8281 if ((page->mapping != inode->i_mapping) ||
8282 (page_start >= size)) {
8283 /* page got truncated out from underneath us */
8286 wait_on_page_writeback(page);
8288 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8289 set_page_extent_mapped(page);
8292 * we can't set the delalloc bits if there are pending ordered
8293 * extents. Drop our locks and wait for them to finish
8295 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8298 unlock_extent_cached(io_tree, page_start, page_end,
8301 btrfs_start_ordered_extent(ordered, 1);
8302 btrfs_put_ordered_extent(ordered);
8306 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8307 reserved_space = round_up(size - page_start,
8308 fs_info->sectorsize);
8309 if (reserved_space < PAGE_SIZE) {
8310 end = page_start + reserved_space - 1;
8311 btrfs_delalloc_release_space(BTRFS_I(inode),
8312 data_reserved, page_start,
8313 PAGE_SIZE - reserved_space, true);
8318 * page_mkwrite gets called when the page is firstly dirtied after it's
8319 * faulted in, but write(2) could also dirty a page and set delalloc
8320 * bits, thus in this case for space account reason, we still need to
8321 * clear any delalloc bits within this page range since we have to
8322 * reserve data&meta space before lock_page() (see above comments).
8324 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8325 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8326 EXTENT_DEFRAG, 0, 0, &cached_state);
8328 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8331 unlock_extent_cached(io_tree, page_start, page_end,
8333 ret = VM_FAULT_SIGBUS;
8337 /* page is wholly or partially inside EOF */
8338 if (page_start + PAGE_SIZE > size)
8339 zero_start = offset_in_page(size);
8341 zero_start = PAGE_SIZE;
8343 if (zero_start != PAGE_SIZE) {
8345 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8346 flush_dcache_page(page);
8349 ClearPageChecked(page);
8350 set_page_dirty(page);
8351 SetPageUptodate(page);
8353 BTRFS_I(inode)->last_trans = fs_info->generation;
8354 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8355 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8357 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8359 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8360 sb_end_pagefault(inode->i_sb);
8361 extent_changeset_free(data_reserved);
8362 return VM_FAULT_LOCKED;
8367 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8368 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8369 reserved_space, (ret != 0));
8371 sb_end_pagefault(inode->i_sb);
8372 extent_changeset_free(data_reserved);
8376 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8378 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8379 struct btrfs_root *root = BTRFS_I(inode)->root;
8380 struct btrfs_block_rsv *rsv;
8382 struct btrfs_trans_handle *trans;
8383 u64 mask = fs_info->sectorsize - 1;
8384 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8386 if (!skip_writeback) {
8387 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8394 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8395 * things going on here:
8397 * 1) We need to reserve space to update our inode.
8399 * 2) We need to have something to cache all the space that is going to
8400 * be free'd up by the truncate operation, but also have some slack
8401 * space reserved in case it uses space during the truncate (thank you
8402 * very much snapshotting).
8404 * And we need these to be separate. The fact is we can use a lot of
8405 * space doing the truncate, and we have no earthly idea how much space
8406 * we will use, so we need the truncate reservation to be separate so it
8407 * doesn't end up using space reserved for updating the inode. We also
8408 * need to be able to stop the transaction and start a new one, which
8409 * means we need to be able to update the inode several times, and we
8410 * have no idea of knowing how many times that will be, so we can't just
8411 * reserve 1 item for the entirety of the operation, so that has to be
8412 * done separately as well.
8414 * So that leaves us with
8416 * 1) rsv - for the truncate reservation, which we will steal from the
8417 * transaction reservation.
8418 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8419 * updating the inode.
8421 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8424 rsv->size = min_size;
8428 * 1 for the truncate slack space
8429 * 1 for updating the inode.
8431 trans = btrfs_start_transaction(root, 2);
8432 if (IS_ERR(trans)) {
8433 ret = PTR_ERR(trans);
8437 /* Migrate the slack space for the truncate to our reserve */
8438 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8443 * So if we truncate and then write and fsync we normally would just
8444 * write the extents that changed, which is a problem if we need to
8445 * first truncate that entire inode. So set this flag so we write out
8446 * all of the extents in the inode to the sync log so we're completely
8449 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8450 trans->block_rsv = rsv;
8453 ret = btrfs_truncate_inode_items(trans, root, inode,
8455 BTRFS_EXTENT_DATA_KEY);
8456 trans->block_rsv = &fs_info->trans_block_rsv;
8457 if (ret != -ENOSPC && ret != -EAGAIN)
8460 ret = btrfs_update_inode(trans, root, inode);
8464 btrfs_end_transaction(trans);
8465 btrfs_btree_balance_dirty(fs_info);
8467 trans = btrfs_start_transaction(root, 2);
8468 if (IS_ERR(trans)) {
8469 ret = PTR_ERR(trans);
8474 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8475 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8476 rsv, min_size, false);
8477 BUG_ON(ret); /* shouldn't happen */
8478 trans->block_rsv = rsv;
8482 * We can't call btrfs_truncate_block inside a trans handle as we could
8483 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8484 * we've truncated everything except the last little bit, and can do
8485 * btrfs_truncate_block and then update the disk_i_size.
8487 if (ret == NEED_TRUNCATE_BLOCK) {
8488 btrfs_end_transaction(trans);
8489 btrfs_btree_balance_dirty(fs_info);
8491 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8494 trans = btrfs_start_transaction(root, 1);
8495 if (IS_ERR(trans)) {
8496 ret = PTR_ERR(trans);
8499 btrfs_inode_safe_disk_i_size_write(inode, 0);
8505 trans->block_rsv = &fs_info->trans_block_rsv;
8506 ret2 = btrfs_update_inode(trans, root, inode);
8510 ret2 = btrfs_end_transaction(trans);
8513 btrfs_btree_balance_dirty(fs_info);
8516 btrfs_free_block_rsv(fs_info, rsv);
8522 * create a new subvolume directory/inode (helper for the ioctl).
8524 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8525 struct btrfs_root *new_root,
8526 struct btrfs_root *parent_root,
8529 struct inode *inode;
8533 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8534 new_dirid, new_dirid,
8535 S_IFDIR | (~current_umask() & S_IRWXUGO),
8538 return PTR_ERR(inode);
8539 inode->i_op = &btrfs_dir_inode_operations;
8540 inode->i_fop = &btrfs_dir_file_operations;
8542 set_nlink(inode, 1);
8543 btrfs_i_size_write(BTRFS_I(inode), 0);
8544 unlock_new_inode(inode);
8546 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8548 btrfs_err(new_root->fs_info,
8549 "error inheriting subvolume %llu properties: %d",
8550 new_root->root_key.objectid, err);
8552 err = btrfs_update_inode(trans, new_root, inode);
8558 struct inode *btrfs_alloc_inode(struct super_block *sb)
8560 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8561 struct btrfs_inode *ei;
8562 struct inode *inode;
8564 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8571 ei->last_sub_trans = 0;
8572 ei->logged_trans = 0;
8573 ei->delalloc_bytes = 0;
8574 ei->new_delalloc_bytes = 0;
8575 ei->defrag_bytes = 0;
8576 ei->disk_i_size = 0;
8579 ei->index_cnt = (u64)-1;
8581 ei->last_unlink_trans = 0;
8582 ei->last_reflink_trans = 0;
8583 ei->last_log_commit = 0;
8585 spin_lock_init(&ei->lock);
8586 ei->outstanding_extents = 0;
8587 if (sb->s_magic != BTRFS_TEST_MAGIC)
8588 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8589 BTRFS_BLOCK_RSV_DELALLOC);
8590 ei->runtime_flags = 0;
8591 ei->prop_compress = BTRFS_COMPRESS_NONE;
8592 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8594 ei->delayed_node = NULL;
8596 ei->i_otime.tv_sec = 0;
8597 ei->i_otime.tv_nsec = 0;
8599 inode = &ei->vfs_inode;
8600 extent_map_tree_init(&ei->extent_tree);
8601 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8602 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8603 IO_TREE_INODE_IO_FAILURE, inode);
8604 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8605 IO_TREE_INODE_FILE_EXTENT, inode);
8606 ei->io_tree.track_uptodate = true;
8607 ei->io_failure_tree.track_uptodate = true;
8608 atomic_set(&ei->sync_writers, 0);
8609 mutex_init(&ei->log_mutex);
8610 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8611 INIT_LIST_HEAD(&ei->delalloc_inodes);
8612 INIT_LIST_HEAD(&ei->delayed_iput);
8613 RB_CLEAR_NODE(&ei->rb_node);
8618 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8619 void btrfs_test_destroy_inode(struct inode *inode)
8621 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8622 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8626 void btrfs_free_inode(struct inode *inode)
8628 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8631 void btrfs_destroy_inode(struct inode *vfs_inode)
8633 struct btrfs_ordered_extent *ordered;
8634 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8635 struct btrfs_root *root = inode->root;
8637 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8638 WARN_ON(vfs_inode->i_data.nrpages);
8639 WARN_ON(inode->block_rsv.reserved);
8640 WARN_ON(inode->block_rsv.size);
8641 WARN_ON(inode->outstanding_extents);
8642 WARN_ON(inode->delalloc_bytes);
8643 WARN_ON(inode->new_delalloc_bytes);
8644 WARN_ON(inode->csum_bytes);
8645 WARN_ON(inode->defrag_bytes);
8648 * This can happen where we create an inode, but somebody else also
8649 * created the same inode and we need to destroy the one we already
8656 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8660 btrfs_err(root->fs_info,
8661 "found ordered extent %llu %llu on inode cleanup",
8662 ordered->file_offset, ordered->num_bytes);
8663 btrfs_remove_ordered_extent(inode, ordered);
8664 btrfs_put_ordered_extent(ordered);
8665 btrfs_put_ordered_extent(ordered);
8668 btrfs_qgroup_check_reserved_leak(inode);
8669 inode_tree_del(inode);
8670 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8671 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8672 btrfs_put_root(inode->root);
8675 int btrfs_drop_inode(struct inode *inode)
8677 struct btrfs_root *root = BTRFS_I(inode)->root;
8682 /* the snap/subvol tree is on deleting */
8683 if (btrfs_root_refs(&root->root_item) == 0)
8686 return generic_drop_inode(inode);
8689 static void init_once(void *foo)
8691 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8693 inode_init_once(&ei->vfs_inode);
8696 void __cold btrfs_destroy_cachep(void)
8699 * Make sure all delayed rcu free inodes are flushed before we
8703 kmem_cache_destroy(btrfs_inode_cachep);
8704 kmem_cache_destroy(btrfs_trans_handle_cachep);
8705 kmem_cache_destroy(btrfs_path_cachep);
8706 kmem_cache_destroy(btrfs_free_space_cachep);
8707 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8710 int __init btrfs_init_cachep(void)
8712 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8713 sizeof(struct btrfs_inode), 0,
8714 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8716 if (!btrfs_inode_cachep)
8719 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8720 sizeof(struct btrfs_trans_handle), 0,
8721 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8722 if (!btrfs_trans_handle_cachep)
8725 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8726 sizeof(struct btrfs_path), 0,
8727 SLAB_MEM_SPREAD, NULL);
8728 if (!btrfs_path_cachep)
8731 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8732 sizeof(struct btrfs_free_space), 0,
8733 SLAB_MEM_SPREAD, NULL);
8734 if (!btrfs_free_space_cachep)
8737 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8738 PAGE_SIZE, PAGE_SIZE,
8739 SLAB_RED_ZONE, NULL);
8740 if (!btrfs_free_space_bitmap_cachep)
8745 btrfs_destroy_cachep();
8749 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8750 u32 request_mask, unsigned int flags)
8753 struct inode *inode = d_inode(path->dentry);
8754 u32 blocksize = inode->i_sb->s_blocksize;
8755 u32 bi_flags = BTRFS_I(inode)->flags;
8757 stat->result_mask |= STATX_BTIME;
8758 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8759 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8760 if (bi_flags & BTRFS_INODE_APPEND)
8761 stat->attributes |= STATX_ATTR_APPEND;
8762 if (bi_flags & BTRFS_INODE_COMPRESS)
8763 stat->attributes |= STATX_ATTR_COMPRESSED;
8764 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8765 stat->attributes |= STATX_ATTR_IMMUTABLE;
8766 if (bi_flags & BTRFS_INODE_NODUMP)
8767 stat->attributes |= STATX_ATTR_NODUMP;
8769 stat->attributes_mask |= (STATX_ATTR_APPEND |
8770 STATX_ATTR_COMPRESSED |
8771 STATX_ATTR_IMMUTABLE |
8774 generic_fillattr(inode, stat);
8775 stat->dev = BTRFS_I(inode)->root->anon_dev;
8777 spin_lock(&BTRFS_I(inode)->lock);
8778 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8779 spin_unlock(&BTRFS_I(inode)->lock);
8780 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8781 ALIGN(delalloc_bytes, blocksize)) >> 9;
8785 static int btrfs_rename_exchange(struct inode *old_dir,
8786 struct dentry *old_dentry,
8787 struct inode *new_dir,
8788 struct dentry *new_dentry)
8790 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8791 struct btrfs_trans_handle *trans;
8792 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8793 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8794 struct inode *new_inode = new_dentry->d_inode;
8795 struct inode *old_inode = old_dentry->d_inode;
8796 struct timespec64 ctime = current_time(old_inode);
8797 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8798 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8803 bool root_log_pinned = false;
8804 bool dest_log_pinned = false;
8806 /* we only allow rename subvolume link between subvolumes */
8807 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8810 /* close the race window with snapshot create/destroy ioctl */
8811 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8812 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8813 down_read(&fs_info->subvol_sem);
8816 * We want to reserve the absolute worst case amount of items. So if
8817 * both inodes are subvols and we need to unlink them then that would
8818 * require 4 item modifications, but if they are both normal inodes it
8819 * would require 5 item modifications, so we'll assume their normal
8820 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8821 * should cover the worst case number of items we'll modify.
8823 trans = btrfs_start_transaction(root, 12);
8824 if (IS_ERR(trans)) {
8825 ret = PTR_ERR(trans);
8830 btrfs_record_root_in_trans(trans, dest);
8833 * We need to find a free sequence number both in the source and
8834 * in the destination directory for the exchange.
8836 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8839 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8843 BTRFS_I(old_inode)->dir_index = 0ULL;
8844 BTRFS_I(new_inode)->dir_index = 0ULL;
8846 /* Reference for the source. */
8847 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8848 /* force full log commit if subvolume involved. */
8849 btrfs_set_log_full_commit(trans);
8851 btrfs_pin_log_trans(root);
8852 root_log_pinned = true;
8853 ret = btrfs_insert_inode_ref(trans, dest,
8854 new_dentry->d_name.name,
8855 new_dentry->d_name.len,
8857 btrfs_ino(BTRFS_I(new_dir)),
8863 /* And now for the dest. */
8864 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8865 /* force full log commit if subvolume involved. */
8866 btrfs_set_log_full_commit(trans);
8868 btrfs_pin_log_trans(dest);
8869 dest_log_pinned = true;
8870 ret = btrfs_insert_inode_ref(trans, root,
8871 old_dentry->d_name.name,
8872 old_dentry->d_name.len,
8874 btrfs_ino(BTRFS_I(old_dir)),
8880 /* Update inode version and ctime/mtime. */
8881 inode_inc_iversion(old_dir);
8882 inode_inc_iversion(new_dir);
8883 inode_inc_iversion(old_inode);
8884 inode_inc_iversion(new_inode);
8885 old_dir->i_ctime = old_dir->i_mtime = ctime;
8886 new_dir->i_ctime = new_dir->i_mtime = ctime;
8887 old_inode->i_ctime = ctime;
8888 new_inode->i_ctime = ctime;
8890 if (old_dentry->d_parent != new_dentry->d_parent) {
8891 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8892 BTRFS_I(old_inode), 1);
8893 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8894 BTRFS_I(new_inode), 1);
8897 /* src is a subvolume */
8898 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8899 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
8900 } else { /* src is an inode */
8901 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
8902 BTRFS_I(old_dentry->d_inode),
8903 old_dentry->d_name.name,
8904 old_dentry->d_name.len);
8906 ret = btrfs_update_inode(trans, root, old_inode);
8909 btrfs_abort_transaction(trans, ret);
8913 /* dest is a subvolume */
8914 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8915 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
8916 } else { /* dest is an inode */
8917 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
8918 BTRFS_I(new_dentry->d_inode),
8919 new_dentry->d_name.name,
8920 new_dentry->d_name.len);
8922 ret = btrfs_update_inode(trans, dest, new_inode);
8925 btrfs_abort_transaction(trans, ret);
8929 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8930 new_dentry->d_name.name,
8931 new_dentry->d_name.len, 0, old_idx);
8933 btrfs_abort_transaction(trans, ret);
8937 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8938 old_dentry->d_name.name,
8939 old_dentry->d_name.len, 0, new_idx);
8941 btrfs_abort_transaction(trans, ret);
8945 if (old_inode->i_nlink == 1)
8946 BTRFS_I(old_inode)->dir_index = old_idx;
8947 if (new_inode->i_nlink == 1)
8948 BTRFS_I(new_inode)->dir_index = new_idx;
8950 if (root_log_pinned) {
8951 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
8952 new_dentry->d_parent);
8953 btrfs_end_log_trans(root);
8954 root_log_pinned = false;
8956 if (dest_log_pinned) {
8957 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
8958 old_dentry->d_parent);
8959 btrfs_end_log_trans(dest);
8960 dest_log_pinned = false;
8964 * If we have pinned a log and an error happened, we unpin tasks
8965 * trying to sync the log and force them to fallback to a transaction
8966 * commit if the log currently contains any of the inodes involved in
8967 * this rename operation (to ensure we do not persist a log with an
8968 * inconsistent state for any of these inodes or leading to any
8969 * inconsistencies when replayed). If the transaction was aborted, the
8970 * abortion reason is propagated to userspace when attempting to commit
8971 * the transaction. If the log does not contain any of these inodes, we
8972 * allow the tasks to sync it.
8974 if (ret && (root_log_pinned || dest_log_pinned)) {
8975 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
8976 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
8977 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
8979 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
8980 btrfs_set_log_full_commit(trans);
8982 if (root_log_pinned) {
8983 btrfs_end_log_trans(root);
8984 root_log_pinned = false;
8986 if (dest_log_pinned) {
8987 btrfs_end_log_trans(dest);
8988 dest_log_pinned = false;
8991 ret2 = btrfs_end_transaction(trans);
8992 ret = ret ? ret : ret2;
8994 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8995 old_ino == BTRFS_FIRST_FREE_OBJECTID)
8996 up_read(&fs_info->subvol_sem);
9001 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9002 struct btrfs_root *root,
9004 struct dentry *dentry)
9007 struct inode *inode;
9011 ret = btrfs_find_free_ino(root, &objectid);
9015 inode = btrfs_new_inode(trans, root, dir,
9016 dentry->d_name.name,
9018 btrfs_ino(BTRFS_I(dir)),
9020 S_IFCHR | WHITEOUT_MODE,
9023 if (IS_ERR(inode)) {
9024 ret = PTR_ERR(inode);
9028 inode->i_op = &btrfs_special_inode_operations;
9029 init_special_inode(inode, inode->i_mode,
9032 ret = btrfs_init_inode_security(trans, inode, dir,
9037 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9038 BTRFS_I(inode), 0, index);
9042 ret = btrfs_update_inode(trans, root, inode);
9044 unlock_new_inode(inode);
9046 inode_dec_link_count(inode);
9052 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9053 struct inode *new_dir, struct dentry *new_dentry,
9056 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9057 struct btrfs_trans_handle *trans;
9058 unsigned int trans_num_items;
9059 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9060 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9061 struct inode *new_inode = d_inode(new_dentry);
9062 struct inode *old_inode = d_inode(old_dentry);
9066 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9067 bool log_pinned = false;
9069 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9072 /* we only allow rename subvolume link between subvolumes */
9073 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9076 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9077 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9080 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9081 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9085 /* check for collisions, even if the name isn't there */
9086 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9087 new_dentry->d_name.name,
9088 new_dentry->d_name.len);
9091 if (ret == -EEXIST) {
9093 * eexist without a new_inode */
9094 if (WARN_ON(!new_inode)) {
9098 /* maybe -EOVERFLOW */
9105 * we're using rename to replace one file with another. Start IO on it
9106 * now so we don't add too much work to the end of the transaction
9108 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9109 filemap_flush(old_inode->i_mapping);
9111 /* close the racy window with snapshot create/destroy ioctl */
9112 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9113 down_read(&fs_info->subvol_sem);
9115 * We want to reserve the absolute worst case amount of items. So if
9116 * both inodes are subvols and we need to unlink them then that would
9117 * require 4 item modifications, but if they are both normal inodes it
9118 * would require 5 item modifications, so we'll assume they are normal
9119 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9120 * should cover the worst case number of items we'll modify.
9121 * If our rename has the whiteout flag, we need more 5 units for the
9122 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9123 * when selinux is enabled).
9125 trans_num_items = 11;
9126 if (flags & RENAME_WHITEOUT)
9127 trans_num_items += 5;
9128 trans = btrfs_start_transaction(root, trans_num_items);
9129 if (IS_ERR(trans)) {
9130 ret = PTR_ERR(trans);
9135 btrfs_record_root_in_trans(trans, dest);
9137 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9141 BTRFS_I(old_inode)->dir_index = 0ULL;
9142 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9143 /* force full log commit if subvolume involved. */
9144 btrfs_set_log_full_commit(trans);
9146 btrfs_pin_log_trans(root);
9148 ret = btrfs_insert_inode_ref(trans, dest,
9149 new_dentry->d_name.name,
9150 new_dentry->d_name.len,
9152 btrfs_ino(BTRFS_I(new_dir)), index);
9157 inode_inc_iversion(old_dir);
9158 inode_inc_iversion(new_dir);
9159 inode_inc_iversion(old_inode);
9160 old_dir->i_ctime = old_dir->i_mtime =
9161 new_dir->i_ctime = new_dir->i_mtime =
9162 old_inode->i_ctime = current_time(old_dir);
9164 if (old_dentry->d_parent != new_dentry->d_parent)
9165 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9166 BTRFS_I(old_inode), 1);
9168 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9169 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9171 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9172 BTRFS_I(d_inode(old_dentry)),
9173 old_dentry->d_name.name,
9174 old_dentry->d_name.len);
9176 ret = btrfs_update_inode(trans, root, old_inode);
9179 btrfs_abort_transaction(trans, ret);
9184 inode_inc_iversion(new_inode);
9185 new_inode->i_ctime = current_time(new_inode);
9186 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9187 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9188 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9189 BUG_ON(new_inode->i_nlink == 0);
9191 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9192 BTRFS_I(d_inode(new_dentry)),
9193 new_dentry->d_name.name,
9194 new_dentry->d_name.len);
9196 if (!ret && new_inode->i_nlink == 0)
9197 ret = btrfs_orphan_add(trans,
9198 BTRFS_I(d_inode(new_dentry)));
9200 btrfs_abort_transaction(trans, ret);
9205 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9206 new_dentry->d_name.name,
9207 new_dentry->d_name.len, 0, index);
9209 btrfs_abort_transaction(trans, ret);
9213 if (old_inode->i_nlink == 1)
9214 BTRFS_I(old_inode)->dir_index = index;
9217 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9218 new_dentry->d_parent);
9219 btrfs_end_log_trans(root);
9223 if (flags & RENAME_WHITEOUT) {
9224 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9228 btrfs_abort_transaction(trans, ret);
9234 * If we have pinned the log and an error happened, we unpin tasks
9235 * trying to sync the log and force them to fallback to a transaction
9236 * commit if the log currently contains any of the inodes involved in
9237 * this rename operation (to ensure we do not persist a log with an
9238 * inconsistent state for any of these inodes or leading to any
9239 * inconsistencies when replayed). If the transaction was aborted, the
9240 * abortion reason is propagated to userspace when attempting to commit
9241 * the transaction. If the log does not contain any of these inodes, we
9242 * allow the tasks to sync it.
9244 if (ret && log_pinned) {
9245 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9246 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9247 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9249 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9250 btrfs_set_log_full_commit(trans);
9252 btrfs_end_log_trans(root);
9255 ret2 = btrfs_end_transaction(trans);
9256 ret = ret ? ret : ret2;
9258 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9259 up_read(&fs_info->subvol_sem);
9264 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9265 struct inode *new_dir, struct dentry *new_dentry,
9268 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9271 if (flags & RENAME_EXCHANGE)
9272 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9275 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9278 struct btrfs_delalloc_work {
9279 struct inode *inode;
9280 struct completion completion;
9281 struct list_head list;
9282 struct btrfs_work work;
9285 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9287 struct btrfs_delalloc_work *delalloc_work;
9288 struct inode *inode;
9290 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9292 inode = delalloc_work->inode;
9293 filemap_flush(inode->i_mapping);
9294 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9295 &BTRFS_I(inode)->runtime_flags))
9296 filemap_flush(inode->i_mapping);
9299 complete(&delalloc_work->completion);
9302 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9304 struct btrfs_delalloc_work *work;
9306 work = kmalloc(sizeof(*work), GFP_NOFS);
9310 init_completion(&work->completion);
9311 INIT_LIST_HEAD(&work->list);
9312 work->inode = inode;
9313 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9319 * some fairly slow code that needs optimization. This walks the list
9320 * of all the inodes with pending delalloc and forces them to disk.
9322 static int start_delalloc_inodes(struct btrfs_root *root, u64 *nr, bool snapshot)
9324 struct btrfs_inode *binode;
9325 struct inode *inode;
9326 struct btrfs_delalloc_work *work, *next;
9327 struct list_head works;
9328 struct list_head splice;
9331 INIT_LIST_HEAD(&works);
9332 INIT_LIST_HEAD(&splice);
9334 mutex_lock(&root->delalloc_mutex);
9335 spin_lock(&root->delalloc_lock);
9336 list_splice_init(&root->delalloc_inodes, &splice);
9337 while (!list_empty(&splice)) {
9338 binode = list_entry(splice.next, struct btrfs_inode,
9341 list_move_tail(&binode->delalloc_inodes,
9342 &root->delalloc_inodes);
9343 inode = igrab(&binode->vfs_inode);
9345 cond_resched_lock(&root->delalloc_lock);
9348 spin_unlock(&root->delalloc_lock);
9351 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9352 &binode->runtime_flags);
9353 work = btrfs_alloc_delalloc_work(inode);
9359 list_add_tail(&work->list, &works);
9360 btrfs_queue_work(root->fs_info->flush_workers,
9362 if (*nr != U64_MAX) {
9368 spin_lock(&root->delalloc_lock);
9370 spin_unlock(&root->delalloc_lock);
9373 list_for_each_entry_safe(work, next, &works, list) {
9374 list_del_init(&work->list);
9375 wait_for_completion(&work->completion);
9379 if (!list_empty(&splice)) {
9380 spin_lock(&root->delalloc_lock);
9381 list_splice_tail(&splice, &root->delalloc_inodes);
9382 spin_unlock(&root->delalloc_lock);
9384 mutex_unlock(&root->delalloc_mutex);
9388 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9390 struct btrfs_fs_info *fs_info = root->fs_info;
9393 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9396 return start_delalloc_inodes(root, &nr, true);
9399 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, u64 nr)
9401 struct btrfs_root *root;
9402 struct list_head splice;
9405 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9408 INIT_LIST_HEAD(&splice);
9410 mutex_lock(&fs_info->delalloc_root_mutex);
9411 spin_lock(&fs_info->delalloc_root_lock);
9412 list_splice_init(&fs_info->delalloc_roots, &splice);
9413 while (!list_empty(&splice) && nr) {
9414 root = list_first_entry(&splice, struct btrfs_root,
9416 root = btrfs_grab_root(root);
9418 list_move_tail(&root->delalloc_root,
9419 &fs_info->delalloc_roots);
9420 spin_unlock(&fs_info->delalloc_root_lock);
9422 ret = start_delalloc_inodes(root, &nr, false);
9423 btrfs_put_root(root);
9426 spin_lock(&fs_info->delalloc_root_lock);
9428 spin_unlock(&fs_info->delalloc_root_lock);
9432 if (!list_empty(&splice)) {
9433 spin_lock(&fs_info->delalloc_root_lock);
9434 list_splice_tail(&splice, &fs_info->delalloc_roots);
9435 spin_unlock(&fs_info->delalloc_root_lock);
9437 mutex_unlock(&fs_info->delalloc_root_mutex);
9441 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9442 const char *symname)
9444 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9445 struct btrfs_trans_handle *trans;
9446 struct btrfs_root *root = BTRFS_I(dir)->root;
9447 struct btrfs_path *path;
9448 struct btrfs_key key;
9449 struct inode *inode = NULL;
9456 struct btrfs_file_extent_item *ei;
9457 struct extent_buffer *leaf;
9459 name_len = strlen(symname);
9460 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9461 return -ENAMETOOLONG;
9464 * 2 items for inode item and ref
9465 * 2 items for dir items
9466 * 1 item for updating parent inode item
9467 * 1 item for the inline extent item
9468 * 1 item for xattr if selinux is on
9470 trans = btrfs_start_transaction(root, 7);
9472 return PTR_ERR(trans);
9474 err = btrfs_find_free_ino(root, &objectid);
9478 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9479 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9480 objectid, S_IFLNK|S_IRWXUGO, &index);
9481 if (IS_ERR(inode)) {
9482 err = PTR_ERR(inode);
9488 * If the active LSM wants to access the inode during
9489 * d_instantiate it needs these. Smack checks to see
9490 * if the filesystem supports xattrs by looking at the
9493 inode->i_fop = &btrfs_file_operations;
9494 inode->i_op = &btrfs_file_inode_operations;
9495 inode->i_mapping->a_ops = &btrfs_aops;
9497 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9501 path = btrfs_alloc_path();
9506 key.objectid = btrfs_ino(BTRFS_I(inode));
9508 key.type = BTRFS_EXTENT_DATA_KEY;
9509 datasize = btrfs_file_extent_calc_inline_size(name_len);
9510 err = btrfs_insert_empty_item(trans, root, path, &key,
9513 btrfs_free_path(path);
9516 leaf = path->nodes[0];
9517 ei = btrfs_item_ptr(leaf, path->slots[0],
9518 struct btrfs_file_extent_item);
9519 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9520 btrfs_set_file_extent_type(leaf, ei,
9521 BTRFS_FILE_EXTENT_INLINE);
9522 btrfs_set_file_extent_encryption(leaf, ei, 0);
9523 btrfs_set_file_extent_compression(leaf, ei, 0);
9524 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9525 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9527 ptr = btrfs_file_extent_inline_start(ei);
9528 write_extent_buffer(leaf, symname, ptr, name_len);
9529 btrfs_mark_buffer_dirty(leaf);
9530 btrfs_free_path(path);
9532 inode->i_op = &btrfs_symlink_inode_operations;
9533 inode_nohighmem(inode);
9534 inode_set_bytes(inode, name_len);
9535 btrfs_i_size_write(BTRFS_I(inode), name_len);
9536 err = btrfs_update_inode(trans, root, inode);
9538 * Last step, add directory indexes for our symlink inode. This is the
9539 * last step to avoid extra cleanup of these indexes if an error happens
9543 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9544 BTRFS_I(inode), 0, index);
9548 d_instantiate_new(dentry, inode);
9551 btrfs_end_transaction(trans);
9553 inode_dec_link_count(inode);
9554 discard_new_inode(inode);
9556 btrfs_btree_balance_dirty(fs_info);
9560 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9561 struct btrfs_trans_handle *trans_in,
9562 struct inode *inode, struct btrfs_key *ins,
9565 struct btrfs_file_extent_item stack_fi;
9566 struct btrfs_replace_extent_info extent_info;
9567 struct btrfs_trans_handle *trans = trans_in;
9568 struct btrfs_path *path;
9569 u64 start = ins->objectid;
9570 u64 len = ins->offset;
9573 memset(&stack_fi, 0, sizeof(stack_fi));
9575 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9576 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9577 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9578 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9579 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9580 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9581 /* Encryption and other encoding is reserved and all 0 */
9583 ret = btrfs_qgroup_release_data(BTRFS_I(inode), file_offset, len);
9585 return ERR_PTR(ret);
9588 ret = insert_reserved_file_extent(trans, BTRFS_I(inode),
9589 file_offset, &stack_fi, ret);
9591 return ERR_PTR(ret);
9595 extent_info.disk_offset = start;
9596 extent_info.disk_len = len;
9597 extent_info.data_offset = 0;
9598 extent_info.data_len = len;
9599 extent_info.file_offset = file_offset;
9600 extent_info.extent_buf = (char *)&stack_fi;
9601 extent_info.is_new_extent = true;
9602 extent_info.qgroup_reserved = ret;
9603 extent_info.insertions = 0;
9605 path = btrfs_alloc_path();
9607 return ERR_PTR(-ENOMEM);
9609 ret = btrfs_replace_file_extents(inode, path, file_offset,
9610 file_offset + len - 1, &extent_info,
9612 btrfs_free_path(path);
9614 return ERR_PTR(ret);
9619 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9620 u64 start, u64 num_bytes, u64 min_size,
9621 loff_t actual_len, u64 *alloc_hint,
9622 struct btrfs_trans_handle *trans)
9624 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9625 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9626 struct extent_map *em;
9627 struct btrfs_root *root = BTRFS_I(inode)->root;
9628 struct btrfs_key ins;
9629 u64 cur_offset = start;
9630 u64 clear_offset = start;
9633 u64 last_alloc = (u64)-1;
9635 bool own_trans = true;
9636 u64 end = start + num_bytes - 1;
9640 while (num_bytes > 0) {
9641 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9642 cur_bytes = max(cur_bytes, min_size);
9644 * If we are severely fragmented we could end up with really
9645 * small allocations, so if the allocator is returning small
9646 * chunks lets make its job easier by only searching for those
9649 cur_bytes = min(cur_bytes, last_alloc);
9650 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9651 min_size, 0, *alloc_hint, &ins, 1, 0);
9656 * We've reserved this space, and thus converted it from
9657 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9658 * from here on out we will only need to clear our reservation
9659 * for the remaining unreserved area, so advance our
9660 * clear_offset by our extent size.
9662 clear_offset += ins.offset;
9664 last_alloc = ins.offset;
9665 trans = insert_prealloc_file_extent(trans, inode, &ins, cur_offset);
9667 * Now that we inserted the prealloc extent we can finally
9668 * decrement the number of reservations in the block group.
9669 * If we did it before, we could race with relocation and have
9670 * relocation miss the reserved extent, making it fail later.
9672 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9673 if (IS_ERR(trans)) {
9674 ret = PTR_ERR(trans);
9675 btrfs_free_reserved_extent(fs_info, ins.objectid,
9680 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9681 cur_offset + ins.offset -1, 0);
9683 em = alloc_extent_map();
9685 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9686 &BTRFS_I(inode)->runtime_flags);
9690 em->start = cur_offset;
9691 em->orig_start = cur_offset;
9692 em->len = ins.offset;
9693 em->block_start = ins.objectid;
9694 em->block_len = ins.offset;
9695 em->orig_block_len = ins.offset;
9696 em->ram_bytes = ins.offset;
9697 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9698 em->generation = trans->transid;
9701 write_lock(&em_tree->lock);
9702 ret = add_extent_mapping(em_tree, em, 1);
9703 write_unlock(&em_tree->lock);
9706 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9707 cur_offset + ins.offset - 1,
9710 free_extent_map(em);
9712 num_bytes -= ins.offset;
9713 cur_offset += ins.offset;
9714 *alloc_hint = ins.objectid + ins.offset;
9716 inode_inc_iversion(inode);
9717 inode->i_ctime = current_time(inode);
9718 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9719 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9720 (actual_len > inode->i_size) &&
9721 (cur_offset > inode->i_size)) {
9722 if (cur_offset > actual_len)
9723 i_size = actual_len;
9725 i_size = cur_offset;
9726 i_size_write(inode, i_size);
9727 btrfs_inode_safe_disk_i_size_write(inode, 0);
9730 ret = btrfs_update_inode(trans, root, inode);
9733 btrfs_abort_transaction(trans, ret);
9735 btrfs_end_transaction(trans);
9740 btrfs_end_transaction(trans);
9744 if (clear_offset < end)
9745 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9746 end - clear_offset + 1);
9750 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9751 u64 start, u64 num_bytes, u64 min_size,
9752 loff_t actual_len, u64 *alloc_hint)
9754 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9755 min_size, actual_len, alloc_hint,
9759 int btrfs_prealloc_file_range_trans(struct inode *inode,
9760 struct btrfs_trans_handle *trans, int mode,
9761 u64 start, u64 num_bytes, u64 min_size,
9762 loff_t actual_len, u64 *alloc_hint)
9764 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9765 min_size, actual_len, alloc_hint, trans);
9768 static int btrfs_set_page_dirty(struct page *page)
9770 return __set_page_dirty_nobuffers(page);
9773 static int btrfs_permission(struct inode *inode, int mask)
9775 struct btrfs_root *root = BTRFS_I(inode)->root;
9776 umode_t mode = inode->i_mode;
9778 if (mask & MAY_WRITE &&
9779 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9780 if (btrfs_root_readonly(root))
9782 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9785 return generic_permission(inode, mask);
9788 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9790 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9791 struct btrfs_trans_handle *trans;
9792 struct btrfs_root *root = BTRFS_I(dir)->root;
9793 struct inode *inode = NULL;
9799 * 5 units required for adding orphan entry
9801 trans = btrfs_start_transaction(root, 5);
9803 return PTR_ERR(trans);
9805 ret = btrfs_find_free_ino(root, &objectid);
9809 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9810 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
9811 if (IS_ERR(inode)) {
9812 ret = PTR_ERR(inode);
9817 inode->i_fop = &btrfs_file_operations;
9818 inode->i_op = &btrfs_file_inode_operations;
9820 inode->i_mapping->a_ops = &btrfs_aops;
9822 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9826 ret = btrfs_update_inode(trans, root, inode);
9829 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9834 * We set number of links to 0 in btrfs_new_inode(), and here we set
9835 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9838 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9840 set_nlink(inode, 1);
9841 d_tmpfile(dentry, inode);
9842 unlock_new_inode(inode);
9843 mark_inode_dirty(inode);
9845 btrfs_end_transaction(trans);
9847 discard_new_inode(inode);
9848 btrfs_btree_balance_dirty(fs_info);
9852 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
9854 struct inode *inode = tree->private_data;
9855 unsigned long index = start >> PAGE_SHIFT;
9856 unsigned long end_index = end >> PAGE_SHIFT;
9859 while (index <= end_index) {
9860 page = find_get_page(inode->i_mapping, index);
9861 ASSERT(page); /* Pages should be in the extent_io_tree */
9862 set_page_writeback(page);
9870 * Add an entry indicating a block group or device which is pinned by a
9871 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9872 * negative errno on failure.
9874 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9875 bool is_block_group)
9877 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9878 struct btrfs_swapfile_pin *sp, *entry;
9880 struct rb_node *parent = NULL;
9882 sp = kmalloc(sizeof(*sp), GFP_NOFS);
9887 sp->is_block_group = is_block_group;
9889 spin_lock(&fs_info->swapfile_pins_lock);
9890 p = &fs_info->swapfile_pins.rb_node;
9893 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9894 if (sp->ptr < entry->ptr ||
9895 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9897 } else if (sp->ptr > entry->ptr ||
9898 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9899 p = &(*p)->rb_right;
9901 spin_unlock(&fs_info->swapfile_pins_lock);
9906 rb_link_node(&sp->node, parent, p);
9907 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9908 spin_unlock(&fs_info->swapfile_pins_lock);
9912 /* Free all of the entries pinned by this swapfile. */
9913 static void btrfs_free_swapfile_pins(struct inode *inode)
9915 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9916 struct btrfs_swapfile_pin *sp;
9917 struct rb_node *node, *next;
9919 spin_lock(&fs_info->swapfile_pins_lock);
9920 node = rb_first(&fs_info->swapfile_pins);
9922 next = rb_next(node);
9923 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9924 if (sp->inode == inode) {
9925 rb_erase(&sp->node, &fs_info->swapfile_pins);
9926 if (sp->is_block_group)
9927 btrfs_put_block_group(sp->ptr);
9932 spin_unlock(&fs_info->swapfile_pins_lock);
9935 struct btrfs_swap_info {
9941 unsigned long nr_pages;
9945 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9946 struct btrfs_swap_info *bsi)
9948 unsigned long nr_pages;
9949 u64 first_ppage, first_ppage_reported, next_ppage;
9952 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
9953 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
9954 PAGE_SIZE) >> PAGE_SHIFT;
9956 if (first_ppage >= next_ppage)
9958 nr_pages = next_ppage - first_ppage;
9960 first_ppage_reported = first_ppage;
9961 if (bsi->start == 0)
9962 first_ppage_reported++;
9963 if (bsi->lowest_ppage > first_ppage_reported)
9964 bsi->lowest_ppage = first_ppage_reported;
9965 if (bsi->highest_ppage < (next_ppage - 1))
9966 bsi->highest_ppage = next_ppage - 1;
9968 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
9971 bsi->nr_extents += ret;
9972 bsi->nr_pages += nr_pages;
9976 static void btrfs_swap_deactivate(struct file *file)
9978 struct inode *inode = file_inode(file);
9980 btrfs_free_swapfile_pins(inode);
9981 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
9984 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
9987 struct inode *inode = file_inode(file);
9988 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9989 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9990 struct extent_state *cached_state = NULL;
9991 struct extent_map *em = NULL;
9992 struct btrfs_device *device = NULL;
9993 struct btrfs_swap_info bsi = {
9994 .lowest_ppage = (sector_t)-1ULL,
10001 * If the swap file was just created, make sure delalloc is done. If the
10002 * file changes again after this, the user is doing something stupid and
10003 * we don't really care.
10005 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10010 * The inode is locked, so these flags won't change after we check them.
10012 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10013 btrfs_warn(fs_info, "swapfile must not be compressed");
10016 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10017 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10020 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10021 btrfs_warn(fs_info, "swapfile must not be checksummed");
10026 * Balance or device remove/replace/resize can move stuff around from
10027 * under us. The exclop protection makes sure they aren't running/won't
10028 * run concurrently while we are mapping the swap extents, and
10029 * fs_info->swapfile_pins prevents them from running while the swap
10030 * file is active and moving the extents. Note that this also prevents
10031 * a concurrent device add which isn't actually necessary, but it's not
10032 * really worth the trouble to allow it.
10034 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10035 btrfs_warn(fs_info,
10036 "cannot activate swapfile while exclusive operation is running");
10040 * Snapshots can create extents which require COW even if NODATACOW is
10041 * set. We use this counter to prevent snapshots. We must increment it
10042 * before walking the extents because we don't want a concurrent
10043 * snapshot to run after we've already checked the extents.
10045 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10047 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10049 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10051 while (start < isize) {
10052 u64 logical_block_start, physical_block_start;
10053 struct btrfs_block_group *bg;
10054 u64 len = isize - start;
10056 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10062 if (em->block_start == EXTENT_MAP_HOLE) {
10063 btrfs_warn(fs_info, "swapfile must not have holes");
10067 if (em->block_start == EXTENT_MAP_INLINE) {
10069 * It's unlikely we'll ever actually find ourselves
10070 * here, as a file small enough to fit inline won't be
10071 * big enough to store more than the swap header, but in
10072 * case something changes in the future, let's catch it
10073 * here rather than later.
10075 btrfs_warn(fs_info, "swapfile must not be inline");
10079 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10080 btrfs_warn(fs_info, "swapfile must not be compressed");
10085 logical_block_start = em->block_start + (start - em->start);
10086 len = min(len, em->len - (start - em->start));
10087 free_extent_map(em);
10090 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10096 btrfs_warn(fs_info,
10097 "swapfile must not be copy-on-write");
10102 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10108 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10109 btrfs_warn(fs_info,
10110 "swapfile must have single data profile");
10115 if (device == NULL) {
10116 device = em->map_lookup->stripes[0].dev;
10117 ret = btrfs_add_swapfile_pin(inode, device, false);
10122 } else if (device != em->map_lookup->stripes[0].dev) {
10123 btrfs_warn(fs_info, "swapfile must be on one device");
10128 physical_block_start = (em->map_lookup->stripes[0].physical +
10129 (logical_block_start - em->start));
10130 len = min(len, em->len - (logical_block_start - em->start));
10131 free_extent_map(em);
10134 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10136 btrfs_warn(fs_info,
10137 "could not find block group containing swapfile");
10142 ret = btrfs_add_swapfile_pin(inode, bg, true);
10144 btrfs_put_block_group(bg);
10151 if (bsi.block_len &&
10152 bsi.block_start + bsi.block_len == physical_block_start) {
10153 bsi.block_len += len;
10155 if (bsi.block_len) {
10156 ret = btrfs_add_swap_extent(sis, &bsi);
10161 bsi.block_start = physical_block_start;
10162 bsi.block_len = len;
10169 ret = btrfs_add_swap_extent(sis, &bsi);
10172 if (!IS_ERR_OR_NULL(em))
10173 free_extent_map(em);
10175 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10178 btrfs_swap_deactivate(file);
10180 btrfs_exclop_finish(fs_info);
10186 sis->bdev = device->bdev;
10187 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10188 sis->max = bsi.nr_pages;
10189 sis->pages = bsi.nr_pages - 1;
10190 sis->highest_bit = bsi.nr_pages - 1;
10191 return bsi.nr_extents;
10194 static void btrfs_swap_deactivate(struct file *file)
10198 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10201 return -EOPNOTSUPP;
10205 static const struct inode_operations btrfs_dir_inode_operations = {
10206 .getattr = btrfs_getattr,
10207 .lookup = btrfs_lookup,
10208 .create = btrfs_create,
10209 .unlink = btrfs_unlink,
10210 .link = btrfs_link,
10211 .mkdir = btrfs_mkdir,
10212 .rmdir = btrfs_rmdir,
10213 .rename = btrfs_rename2,
10214 .symlink = btrfs_symlink,
10215 .setattr = btrfs_setattr,
10216 .mknod = btrfs_mknod,
10217 .listxattr = btrfs_listxattr,
10218 .permission = btrfs_permission,
10219 .get_acl = btrfs_get_acl,
10220 .set_acl = btrfs_set_acl,
10221 .update_time = btrfs_update_time,
10222 .tmpfile = btrfs_tmpfile,
10225 static const struct file_operations btrfs_dir_file_operations = {
10226 .llseek = generic_file_llseek,
10227 .read = generic_read_dir,
10228 .iterate_shared = btrfs_real_readdir,
10229 .open = btrfs_opendir,
10230 .unlocked_ioctl = btrfs_ioctl,
10231 #ifdef CONFIG_COMPAT
10232 .compat_ioctl = btrfs_compat_ioctl,
10234 .release = btrfs_release_file,
10235 .fsync = btrfs_sync_file,
10239 * btrfs doesn't support the bmap operation because swapfiles
10240 * use bmap to make a mapping of extents in the file. They assume
10241 * these extents won't change over the life of the file and they
10242 * use the bmap result to do IO directly to the drive.
10244 * the btrfs bmap call would return logical addresses that aren't
10245 * suitable for IO and they also will change frequently as COW
10246 * operations happen. So, swapfile + btrfs == corruption.
10248 * For now we're avoiding this by dropping bmap.
10250 static const struct address_space_operations btrfs_aops = {
10251 .readpage = btrfs_readpage,
10252 .writepage = btrfs_writepage,
10253 .writepages = btrfs_writepages,
10254 .readahead = btrfs_readahead,
10255 .direct_IO = noop_direct_IO,
10256 .invalidatepage = btrfs_invalidatepage,
10257 .releasepage = btrfs_releasepage,
10258 #ifdef CONFIG_MIGRATION
10259 .migratepage = btrfs_migratepage,
10261 .set_page_dirty = btrfs_set_page_dirty,
10262 .error_remove_page = generic_error_remove_page,
10263 .swap_activate = btrfs_swap_activate,
10264 .swap_deactivate = btrfs_swap_deactivate,
10267 static const struct inode_operations btrfs_file_inode_operations = {
10268 .getattr = btrfs_getattr,
10269 .setattr = btrfs_setattr,
10270 .listxattr = btrfs_listxattr,
10271 .permission = btrfs_permission,
10272 .fiemap = btrfs_fiemap,
10273 .get_acl = btrfs_get_acl,
10274 .set_acl = btrfs_set_acl,
10275 .update_time = btrfs_update_time,
10277 static const struct inode_operations btrfs_special_inode_operations = {
10278 .getattr = btrfs_getattr,
10279 .setattr = btrfs_setattr,
10280 .permission = btrfs_permission,
10281 .listxattr = btrfs_listxattr,
10282 .get_acl = btrfs_get_acl,
10283 .set_acl = btrfs_set_acl,
10284 .update_time = btrfs_update_time,
10286 static const struct inode_operations btrfs_symlink_inode_operations = {
10287 .get_link = page_get_link,
10288 .getattr = btrfs_getattr,
10289 .setattr = btrfs_setattr,
10290 .permission = btrfs_permission,
10291 .listxattr = btrfs_listxattr,
10292 .update_time = btrfs_update_time,
10295 const struct dentry_operations btrfs_dentry_operations = {
10296 .d_delete = btrfs_dentry_delete,