1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.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/sched/mm.h>
32 #include <asm/unaligned.h>
36 #include "transaction.h"
37 #include "btrfs_inode.h"
38 #include "print-tree.h"
39 #include "ordered-data.h"
43 #include "compression.h"
45 #include "free-space-cache.h"
46 #include "inode-map.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
53 struct btrfs_iget_args {
54 struct btrfs_key *location;
55 struct btrfs_root *root;
58 struct btrfs_dio_data {
60 u64 unsubmitted_oe_range_start;
61 u64 unsubmitted_oe_range_end;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct file_operations btrfs_dir_file_operations;
72 static const struct extent_io_ops btrfs_extent_io_ops;
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 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 inode *inode, u64 start, u64 len,
88 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 inode *inode,
94 const u64 offset, const u64 bytes,
98 * Cleanup all submitted ordered extents in specified range to handle errors
99 * from the btrfs_run_delalloc_range() callback.
101 * NOTE: caller must ensure that when an error happens, it can not call
102 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
103 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
104 * to be released, which we want to happen only when finishing the ordered
105 * extent (btrfs_finish_ordered_io()).
107 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
108 struct page *locked_page,
109 u64 offset, u64 bytes)
111 unsigned long index = offset >> PAGE_SHIFT;
112 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
113 u64 page_start = page_offset(locked_page);
114 u64 page_end = page_start + PAGE_SIZE - 1;
118 while (index <= end_index) {
119 page = find_get_page(inode->i_mapping, index);
123 ClearPagePrivate2(page);
128 * In case this page belongs to the delalloc range being instantiated
129 * then skip it, since the first page of a range is going to be
130 * properly cleaned up by the caller of run_delalloc_range
132 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
137 return __endio_write_update_ordered(inode, offset, bytes, false);
140 static int btrfs_dirty_inode(struct inode *inode);
142 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
143 void btrfs_test_inode_set_ops(struct inode *inode)
145 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
149 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
150 struct inode *inode, struct inode *dir,
151 const struct qstr *qstr)
155 err = btrfs_init_acl(trans, inode, dir);
157 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
162 * this does all the hard work for inserting an inline extent into
163 * the btree. The caller should have done a btrfs_drop_extents so that
164 * no overlapping inline items exist in the btree
166 static int insert_inline_extent(struct btrfs_trans_handle *trans,
167 struct btrfs_path *path, int extent_inserted,
168 struct btrfs_root *root, struct inode *inode,
169 u64 start, size_t size, size_t compressed_size,
171 struct page **compressed_pages)
173 struct extent_buffer *leaf;
174 struct page *page = NULL;
177 struct btrfs_file_extent_item *ei;
179 size_t cur_size = size;
180 unsigned long offset;
182 ASSERT((compressed_size > 0 && compressed_pages) ||
183 (compressed_size == 0 && !compressed_pages));
185 if (compressed_size && compressed_pages)
186 cur_size = compressed_size;
188 inode_add_bytes(inode, size);
190 if (!extent_inserted) {
191 struct btrfs_key key;
194 key.objectid = btrfs_ino(BTRFS_I(inode));
196 key.type = BTRFS_EXTENT_DATA_KEY;
198 datasize = btrfs_file_extent_calc_inline_size(cur_size);
199 path->leave_spinning = 1;
200 ret = btrfs_insert_empty_item(trans, root, path, &key,
205 leaf = path->nodes[0];
206 ei = btrfs_item_ptr(leaf, path->slots[0],
207 struct btrfs_file_extent_item);
208 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
209 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
210 btrfs_set_file_extent_encryption(leaf, ei, 0);
211 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
212 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
213 ptr = btrfs_file_extent_inline_start(ei);
215 if (compress_type != BTRFS_COMPRESS_NONE) {
218 while (compressed_size > 0) {
219 cpage = compressed_pages[i];
220 cur_size = min_t(unsigned long, compressed_size,
223 kaddr = kmap_atomic(cpage);
224 write_extent_buffer(leaf, kaddr, ptr, cur_size);
225 kunmap_atomic(kaddr);
229 compressed_size -= cur_size;
231 btrfs_set_file_extent_compression(leaf, ei,
234 page = find_get_page(inode->i_mapping,
235 start >> PAGE_SHIFT);
236 btrfs_set_file_extent_compression(leaf, ei, 0);
237 kaddr = kmap_atomic(page);
238 offset = offset_in_page(start);
239 write_extent_buffer(leaf, kaddr + offset, ptr, size);
240 kunmap_atomic(kaddr);
243 btrfs_mark_buffer_dirty(leaf);
244 btrfs_release_path(path);
247 * we're an inline extent, so nobody can
248 * extend the file past i_size without locking
249 * a page we already have locked.
251 * We must do any isize and inode updates
252 * before we unlock the pages. Otherwise we
253 * could end up racing with unlink.
255 BTRFS_I(inode)->disk_i_size = inode->i_size;
256 ret = btrfs_update_inode(trans, root, inode);
264 * conditionally insert an inline extent into the file. This
265 * does the checks required to make sure the data is small enough
266 * to fit as an inline extent.
268 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
269 u64 end, size_t compressed_size,
271 struct page **compressed_pages)
273 struct btrfs_root *root = BTRFS_I(inode)->root;
274 struct btrfs_fs_info *fs_info = root->fs_info;
275 struct btrfs_trans_handle *trans;
276 u64 isize = i_size_read(inode);
277 u64 actual_end = min(end + 1, isize);
278 u64 inline_len = actual_end - start;
279 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
280 u64 data_len = inline_len;
282 struct btrfs_path *path;
283 int extent_inserted = 0;
284 u32 extent_item_size;
287 data_len = compressed_size;
290 actual_end > fs_info->sectorsize ||
291 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
293 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
295 data_len > fs_info->max_inline) {
299 path = btrfs_alloc_path();
303 trans = btrfs_join_transaction(root);
305 btrfs_free_path(path);
306 return PTR_ERR(trans);
308 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
310 if (compressed_size && compressed_pages)
311 extent_item_size = btrfs_file_extent_calc_inline_size(
314 extent_item_size = btrfs_file_extent_calc_inline_size(
317 ret = __btrfs_drop_extents(trans, root, inode, path,
318 start, aligned_end, NULL,
319 1, 1, extent_item_size, &extent_inserted);
321 btrfs_abort_transaction(trans, ret);
325 if (isize > actual_end)
326 inline_len = min_t(u64, isize, actual_end);
327 ret = insert_inline_extent(trans, path, extent_inserted,
329 inline_len, compressed_size,
330 compress_type, compressed_pages);
331 if (ret && ret != -ENOSPC) {
332 btrfs_abort_transaction(trans, ret);
334 } else if (ret == -ENOSPC) {
339 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
340 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
343 * Don't forget to free the reserved space, as for inlined extent
344 * it won't count as data extent, free them directly here.
345 * And at reserve time, it's always aligned to page size, so
346 * just free one page here.
348 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
349 btrfs_free_path(path);
350 btrfs_end_transaction(trans);
354 struct async_extent {
359 unsigned long nr_pages;
361 struct list_head list;
366 struct page *locked_page;
369 unsigned int write_flags;
370 struct list_head extents;
371 struct btrfs_work work;
376 /* Number of chunks in flight; must be first in the structure */
378 struct async_chunk chunks[];
381 static noinline int add_async_extent(struct async_chunk *cow,
382 u64 start, u64 ram_size,
385 unsigned long nr_pages,
388 struct async_extent *async_extent;
390 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
391 BUG_ON(!async_extent); /* -ENOMEM */
392 async_extent->start = start;
393 async_extent->ram_size = ram_size;
394 async_extent->compressed_size = compressed_size;
395 async_extent->pages = pages;
396 async_extent->nr_pages = nr_pages;
397 async_extent->compress_type = compress_type;
398 list_add_tail(&async_extent->list, &cow->extents);
403 * Check if the inode has flags compatible with compression
405 static inline bool inode_can_compress(struct inode *inode)
407 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
408 BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
414 * Check if the inode needs to be submitted to compression, based on mount
415 * options, defragmentation, properties or heuristics.
417 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
419 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
421 if (!inode_can_compress(inode)) {
422 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
423 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
424 btrfs_ino(BTRFS_I(inode)));
428 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
431 if (BTRFS_I(inode)->defrag_compress)
433 /* bad compression ratios */
434 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
436 if (btrfs_test_opt(fs_info, COMPRESS) ||
437 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
438 BTRFS_I(inode)->prop_compress)
439 return btrfs_compress_heuristic(inode, start, end);
443 static inline void inode_should_defrag(struct btrfs_inode *inode,
444 u64 start, u64 end, u64 num_bytes, u64 small_write)
446 /* If this is a small write inside eof, kick off a defrag */
447 if (num_bytes < small_write &&
448 (start > 0 || end + 1 < inode->disk_i_size))
449 btrfs_add_inode_defrag(NULL, inode);
453 * we create compressed extents in two phases. The first
454 * phase compresses a range of pages that have already been
455 * locked (both pages and state bits are locked).
457 * This is done inside an ordered work queue, and the compression
458 * is spread across many cpus. The actual IO submission is step
459 * two, and the ordered work queue takes care of making sure that
460 * happens in the same order things were put onto the queue by
461 * writepages and friends.
463 * If this code finds it can't get good compression, it puts an
464 * entry onto the work queue to write the uncompressed bytes. This
465 * makes sure that both compressed inodes and uncompressed inodes
466 * are written in the same order that the flusher thread sent them
469 static noinline int compress_file_range(struct async_chunk *async_chunk)
471 struct inode *inode = async_chunk->inode;
472 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
473 u64 blocksize = fs_info->sectorsize;
474 u64 start = async_chunk->start;
475 u64 end = async_chunk->end;
479 struct page **pages = NULL;
480 unsigned long nr_pages;
481 unsigned long total_compressed = 0;
482 unsigned long total_in = 0;
485 int compress_type = fs_info->compress_type;
486 int compressed_extents = 0;
489 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
493 * We need to save i_size before now because it could change in between
494 * us evaluating the size and assigning it. This is because we lock and
495 * unlock the page in truncate and fallocate, and then modify the i_size
498 * The barriers are to emulate READ_ONCE, remove that once i_size_read
502 i_size = i_size_read(inode);
504 actual_end = min_t(u64, i_size, end + 1);
507 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
508 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
509 nr_pages = min_t(unsigned long, nr_pages,
510 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
513 * we don't want to send crud past the end of i_size through
514 * compression, that's just a waste of CPU time. So, if the
515 * end of the file is before the start of our current
516 * requested range of bytes, we bail out to the uncompressed
517 * cleanup code that can deal with all of this.
519 * It isn't really the fastest way to fix things, but this is a
520 * very uncommon corner.
522 if (actual_end <= start)
523 goto cleanup_and_bail_uncompressed;
525 total_compressed = actual_end - start;
528 * skip compression for a small file range(<=blocksize) that
529 * isn't an inline extent, since it doesn't save disk space at all.
531 if (total_compressed <= blocksize &&
532 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
533 goto cleanup_and_bail_uncompressed;
535 total_compressed = min_t(unsigned long, total_compressed,
536 BTRFS_MAX_UNCOMPRESSED);
541 * we do compression for mount -o compress and when the
542 * inode has not been flagged as nocompress. This flag can
543 * change at any time if we discover bad compression ratios.
545 if (inode_need_compress(inode, start, end)) {
547 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
549 /* just bail out to the uncompressed code */
554 if (BTRFS_I(inode)->defrag_compress)
555 compress_type = BTRFS_I(inode)->defrag_compress;
556 else if (BTRFS_I(inode)->prop_compress)
557 compress_type = BTRFS_I(inode)->prop_compress;
560 * we need to call clear_page_dirty_for_io on each
561 * page in the range. Otherwise applications with the file
562 * mmap'd can wander in and change the page contents while
563 * we are compressing them.
565 * If the compression fails for any reason, we set the pages
566 * dirty again later on.
568 * Note that the remaining part is redirtied, the start pointer
569 * has moved, the end is the original one.
572 extent_range_clear_dirty_for_io(inode, start, end);
576 /* Compression level is applied here and only here */
577 ret = btrfs_compress_pages(
578 compress_type | (fs_info->compress_level << 4),
579 inode->i_mapping, start,
586 unsigned long offset = offset_in_page(total_compressed);
587 struct page *page = pages[nr_pages - 1];
590 /* zero the tail end of the last page, we might be
591 * sending it down to disk
594 kaddr = kmap_atomic(page);
595 memset(kaddr + offset, 0,
597 kunmap_atomic(kaddr);
604 /* lets try to make an inline extent */
605 if (ret || total_in < actual_end) {
606 /* we didn't compress the entire range, try
607 * to make an uncompressed inline extent.
609 ret = cow_file_range_inline(inode, start, end, 0,
610 BTRFS_COMPRESS_NONE, NULL);
612 /* try making a compressed inline extent */
613 ret = cow_file_range_inline(inode, start, end,
615 compress_type, pages);
618 unsigned long clear_flags = EXTENT_DELALLOC |
619 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
620 EXTENT_DO_ACCOUNTING;
621 unsigned long page_error_op;
623 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
626 * inline extent creation worked or returned error,
627 * we don't need to create any more async work items.
628 * Unlock and free up our temp pages.
630 * We use DO_ACCOUNTING here because we need the
631 * delalloc_release_metadata to be done _after_ we drop
632 * our outstanding extent for clearing delalloc for this
635 extent_clear_unlock_delalloc(inode, start, end, NULL,
643 for (i = 0; i < nr_pages; i++) {
644 WARN_ON(pages[i]->mapping);
655 * we aren't doing an inline extent round the compressed size
656 * up to a block size boundary so the allocator does sane
659 total_compressed = ALIGN(total_compressed, blocksize);
662 * one last check to make sure the compression is really a
663 * win, compare the page count read with the blocks on disk,
664 * compression must free at least one sector size
666 total_in = ALIGN(total_in, PAGE_SIZE);
667 if (total_compressed + blocksize <= total_in) {
668 compressed_extents++;
671 * The async work queues will take care of doing actual
672 * allocation on disk for these compressed pages, and
673 * will submit them to the elevator.
675 add_async_extent(async_chunk, start, total_in,
676 total_compressed, pages, nr_pages,
679 if (start + total_in < end) {
685 return compressed_extents;
690 * the compression code ran but failed to make things smaller,
691 * free any pages it allocated and our page pointer array
693 for (i = 0; i < nr_pages; i++) {
694 WARN_ON(pages[i]->mapping);
699 total_compressed = 0;
702 /* flag the file so we don't compress in the future */
703 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
704 !(BTRFS_I(inode)->prop_compress)) {
705 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
708 cleanup_and_bail_uncompressed:
710 * No compression, but we still need to write the pages in the file
711 * we've been given so far. redirty the locked page if it corresponds
712 * to our extent and set things up for the async work queue to run
713 * cow_file_range to do the normal delalloc dance.
715 if (page_offset(async_chunk->locked_page) >= start &&
716 page_offset(async_chunk->locked_page) <= end)
717 __set_page_dirty_nobuffers(async_chunk->locked_page);
718 /* unlocked later on in the async handlers */
721 extent_range_redirty_for_io(inode, start, end);
722 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
723 BTRFS_COMPRESS_NONE);
724 compressed_extents++;
726 return compressed_extents;
729 static void free_async_extent_pages(struct async_extent *async_extent)
733 if (!async_extent->pages)
736 for (i = 0; i < async_extent->nr_pages; i++) {
737 WARN_ON(async_extent->pages[i]->mapping);
738 put_page(async_extent->pages[i]);
740 kfree(async_extent->pages);
741 async_extent->nr_pages = 0;
742 async_extent->pages = NULL;
746 * phase two of compressed writeback. This is the ordered portion
747 * of the code, which only gets called in the order the work was
748 * queued. We walk all the async extents created by compress_file_range
749 * and send them down to the disk.
751 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
753 struct inode *inode = async_chunk->inode;
754 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
755 struct async_extent *async_extent;
757 struct btrfs_key ins;
758 struct extent_map *em;
759 struct btrfs_root *root = BTRFS_I(inode)->root;
760 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
764 while (!list_empty(&async_chunk->extents)) {
765 async_extent = list_entry(async_chunk->extents.next,
766 struct async_extent, list);
767 list_del(&async_extent->list);
770 lock_extent(io_tree, async_extent->start,
771 async_extent->start + async_extent->ram_size - 1);
772 /* did the compression code fall back to uncompressed IO? */
773 if (!async_extent->pages) {
774 int page_started = 0;
775 unsigned long nr_written = 0;
777 /* allocate blocks */
778 ret = cow_file_range(inode, async_chunk->locked_page,
780 async_extent->start +
781 async_extent->ram_size - 1,
782 &page_started, &nr_written, 0);
787 * if page_started, cow_file_range inserted an
788 * inline extent and took care of all the unlocking
789 * and IO for us. Otherwise, we need to submit
790 * all those pages down to the drive.
792 if (!page_started && !ret)
793 extent_write_locked_range(inode,
795 async_extent->start +
796 async_extent->ram_size - 1,
799 unlock_page(async_chunk->locked_page);
805 ret = btrfs_reserve_extent(root, async_extent->ram_size,
806 async_extent->compressed_size,
807 async_extent->compressed_size,
808 0, alloc_hint, &ins, 1, 1);
810 free_async_extent_pages(async_extent);
812 if (ret == -ENOSPC) {
813 unlock_extent(io_tree, async_extent->start,
814 async_extent->start +
815 async_extent->ram_size - 1);
818 * we need to redirty the pages if we decide to
819 * fallback to uncompressed IO, otherwise we
820 * will not submit these pages down to lower
823 extent_range_redirty_for_io(inode,
825 async_extent->start +
826 async_extent->ram_size - 1);
833 * here we're doing allocation and writeback of the
836 em = create_io_em(inode, async_extent->start,
837 async_extent->ram_size, /* len */
838 async_extent->start, /* orig_start */
839 ins.objectid, /* block_start */
840 ins.offset, /* block_len */
841 ins.offset, /* orig_block_len */
842 async_extent->ram_size, /* ram_bytes */
843 async_extent->compress_type,
844 BTRFS_ORDERED_COMPRESSED);
846 /* ret value is not necessary due to void function */
847 goto out_free_reserve;
850 ret = btrfs_add_ordered_extent_compress(inode,
853 async_extent->ram_size,
855 BTRFS_ORDERED_COMPRESSED,
856 async_extent->compress_type);
858 btrfs_drop_extent_cache(BTRFS_I(inode),
860 async_extent->start +
861 async_extent->ram_size - 1, 0);
862 goto out_free_reserve;
864 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
867 * clear dirty, set writeback and unlock the pages.
869 extent_clear_unlock_delalloc(inode, async_extent->start,
870 async_extent->start +
871 async_extent->ram_size - 1,
872 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
873 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
875 if (btrfs_submit_compressed_write(inode,
877 async_extent->ram_size,
879 ins.offset, async_extent->pages,
880 async_extent->nr_pages,
881 async_chunk->write_flags)) {
882 struct page *p = async_extent->pages[0];
883 const u64 start = async_extent->start;
884 const u64 end = start + async_extent->ram_size - 1;
886 p->mapping = inode->i_mapping;
887 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
890 extent_clear_unlock_delalloc(inode, start, end,
894 free_async_extent_pages(async_extent);
896 alloc_hint = ins.objectid + ins.offset;
902 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
903 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
905 extent_clear_unlock_delalloc(inode, async_extent->start,
906 async_extent->start +
907 async_extent->ram_size - 1,
908 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
909 EXTENT_DELALLOC_NEW |
910 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
911 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
912 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
914 free_async_extent_pages(async_extent);
919 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
922 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
923 struct extent_map *em;
926 read_lock(&em_tree->lock);
927 em = search_extent_mapping(em_tree, start, num_bytes);
930 * if block start isn't an actual block number then find the
931 * first block in this inode and use that as a hint. If that
932 * block is also bogus then just don't worry about it.
934 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
936 em = search_extent_mapping(em_tree, 0, 0);
937 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
938 alloc_hint = em->block_start;
942 alloc_hint = em->block_start;
946 read_unlock(&em_tree->lock);
952 * when extent_io.c finds a delayed allocation range in the file,
953 * the call backs end up in this code. The basic idea is to
954 * allocate extents on disk for the range, and create ordered data structs
955 * in ram to track those extents.
957 * locked_page is the page that writepage had locked already. We use
958 * it to make sure we don't do extra locks or unlocks.
960 * *page_started is set to one if we unlock locked_page and do everything
961 * required to start IO on it. It may be clean and already done with
964 static noinline int cow_file_range(struct inode *inode,
965 struct page *locked_page,
966 u64 start, u64 end, int *page_started,
967 unsigned long *nr_written, int unlock)
969 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
970 struct btrfs_root *root = BTRFS_I(inode)->root;
973 unsigned long ram_size;
974 u64 cur_alloc_size = 0;
975 u64 blocksize = fs_info->sectorsize;
976 struct btrfs_key ins;
977 struct extent_map *em;
979 unsigned long page_ops;
980 bool extent_reserved = false;
983 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
989 num_bytes = ALIGN(end - start + 1, blocksize);
990 num_bytes = max(blocksize, num_bytes);
991 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
993 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
996 /* lets try to make an inline extent */
997 ret = cow_file_range_inline(inode, start, end, 0,
998 BTRFS_COMPRESS_NONE, NULL);
1001 * We use DO_ACCOUNTING here because we need the
1002 * delalloc_release_metadata to be run _after_ we drop
1003 * our outstanding extent for clearing delalloc for this
1006 extent_clear_unlock_delalloc(inode, start, end, NULL,
1007 EXTENT_LOCKED | EXTENT_DELALLOC |
1008 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1009 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1010 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1011 PAGE_END_WRITEBACK);
1012 *nr_written = *nr_written +
1013 (end - start + PAGE_SIZE) / PAGE_SIZE;
1016 } else if (ret < 0) {
1021 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1022 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1023 start + num_bytes - 1, 0);
1025 while (num_bytes > 0) {
1026 cur_alloc_size = num_bytes;
1027 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1028 fs_info->sectorsize, 0, alloc_hint,
1032 cur_alloc_size = ins.offset;
1033 extent_reserved = true;
1035 ram_size = ins.offset;
1036 em = create_io_em(inode, start, ins.offset, /* len */
1037 start, /* orig_start */
1038 ins.objectid, /* block_start */
1039 ins.offset, /* block_len */
1040 ins.offset, /* orig_block_len */
1041 ram_size, /* ram_bytes */
1042 BTRFS_COMPRESS_NONE, /* compress_type */
1043 BTRFS_ORDERED_REGULAR /* type */);
1048 free_extent_map(em);
1050 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1051 ram_size, cur_alloc_size, 0);
1053 goto out_drop_extent_cache;
1055 if (root->root_key.objectid ==
1056 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1057 ret = btrfs_reloc_clone_csums(inode, start,
1060 * Only drop cache here, and process as normal.
1062 * We must not allow extent_clear_unlock_delalloc()
1063 * at out_unlock label to free meta of this ordered
1064 * extent, as its meta should be freed by
1065 * btrfs_finish_ordered_io().
1067 * So we must continue until @start is increased to
1068 * skip current ordered extent.
1071 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1072 start + ram_size - 1, 0);
1075 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1077 /* we're not doing compressed IO, don't unlock the first
1078 * page (which the caller expects to stay locked), don't
1079 * clear any dirty bits and don't set any writeback bits
1081 * Do set the Private2 bit so we know this page was properly
1082 * setup for writepage
1084 page_ops = unlock ? PAGE_UNLOCK : 0;
1085 page_ops |= PAGE_SET_PRIVATE2;
1087 extent_clear_unlock_delalloc(inode, start,
1088 start + ram_size - 1,
1090 EXTENT_LOCKED | EXTENT_DELALLOC,
1092 if (num_bytes < cur_alloc_size)
1095 num_bytes -= cur_alloc_size;
1096 alloc_hint = ins.objectid + ins.offset;
1097 start += cur_alloc_size;
1098 extent_reserved = false;
1101 * btrfs_reloc_clone_csums() error, since start is increased
1102 * extent_clear_unlock_delalloc() at out_unlock label won't
1103 * free metadata of current ordered extent, we're OK to exit.
1111 out_drop_extent_cache:
1112 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1114 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1115 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1117 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1118 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1119 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1122 * If we reserved an extent for our delalloc range (or a subrange) and
1123 * failed to create the respective ordered extent, then it means that
1124 * when we reserved the extent we decremented the extent's size from
1125 * the data space_info's bytes_may_use counter and incremented the
1126 * space_info's bytes_reserved counter by the same amount. We must make
1127 * sure extent_clear_unlock_delalloc() does not try to decrement again
1128 * the data space_info's bytes_may_use counter, therefore we do not pass
1129 * it the flag EXTENT_CLEAR_DATA_RESV.
1131 if (extent_reserved) {
1132 extent_clear_unlock_delalloc(inode, start,
1133 start + cur_alloc_size,
1137 start += cur_alloc_size;
1141 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1142 clear_bits | EXTENT_CLEAR_DATA_RESV,
1148 * work queue call back to started compression on a file and pages
1150 static noinline void async_cow_start(struct btrfs_work *work)
1152 struct async_chunk *async_chunk;
1153 int compressed_extents;
1155 async_chunk = container_of(work, struct async_chunk, work);
1157 compressed_extents = compress_file_range(async_chunk);
1158 if (compressed_extents == 0) {
1159 btrfs_add_delayed_iput(async_chunk->inode);
1160 async_chunk->inode = NULL;
1165 * work queue call back to submit previously compressed pages
1167 static noinline void async_cow_submit(struct btrfs_work *work)
1169 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1171 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1172 unsigned long nr_pages;
1174 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1177 /* atomic_sub_return implies a barrier */
1178 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1180 cond_wake_up_nomb(&fs_info->async_submit_wait);
1183 * ->inode could be NULL if async_chunk_start has failed to compress,
1184 * in which case we don't have anything to submit, yet we need to
1185 * always adjust ->async_delalloc_pages as its paired with the init
1186 * happening in cow_file_range_async
1188 if (async_chunk->inode)
1189 submit_compressed_extents(async_chunk);
1192 static noinline void async_cow_free(struct btrfs_work *work)
1194 struct async_chunk *async_chunk;
1196 async_chunk = container_of(work, struct async_chunk, work);
1197 if (async_chunk->inode)
1198 btrfs_add_delayed_iput(async_chunk->inode);
1200 * Since the pointer to 'pending' is at the beginning of the array of
1201 * async_chunk's, freeing it ensures the whole array has been freed.
1203 if (atomic_dec_and_test(async_chunk->pending))
1204 kvfree(async_chunk->pending);
1207 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1208 u64 start, u64 end, int *page_started,
1209 unsigned long *nr_written,
1210 unsigned int write_flags)
1212 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1213 struct async_cow *ctx;
1214 struct async_chunk *async_chunk;
1215 unsigned long nr_pages;
1217 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1219 bool should_compress;
1222 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1224 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1225 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1227 should_compress = false;
1229 should_compress = true;
1232 nofs_flag = memalloc_nofs_save();
1233 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1234 memalloc_nofs_restore(nofs_flag);
1237 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1238 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1239 EXTENT_DO_ACCOUNTING;
1240 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1241 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1244 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1245 clear_bits, page_ops);
1249 async_chunk = ctx->chunks;
1250 atomic_set(&ctx->num_chunks, num_chunks);
1252 for (i = 0; i < num_chunks; i++) {
1253 if (should_compress)
1254 cur_end = min(end, start + SZ_512K - 1);
1259 * igrab is called higher up in the call chain, take only the
1260 * lightweight reference for the callback lifetime
1263 async_chunk[i].pending = &ctx->num_chunks;
1264 async_chunk[i].inode = inode;
1265 async_chunk[i].start = start;
1266 async_chunk[i].end = cur_end;
1267 async_chunk[i].locked_page = locked_page;
1268 async_chunk[i].write_flags = write_flags;
1269 INIT_LIST_HEAD(&async_chunk[i].extents);
1271 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1272 async_cow_submit, async_cow_free);
1274 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1275 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1277 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1279 *nr_written += nr_pages;
1280 start = cur_end + 1;
1286 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1287 u64 bytenr, u64 num_bytes)
1290 struct btrfs_ordered_sum *sums;
1293 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1294 bytenr + num_bytes - 1, &list, 0);
1295 if (ret == 0 && list_empty(&list))
1298 while (!list_empty(&list)) {
1299 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1300 list_del(&sums->list);
1309 * when nowcow writeback call back. This checks for snapshots or COW copies
1310 * of the extents that exist in the file, and COWs the file as required.
1312 * If no cow copies or snapshots exist, we write directly to the existing
1315 static noinline int run_delalloc_nocow(struct inode *inode,
1316 struct page *locked_page,
1317 const u64 start, const u64 end,
1318 int *page_started, int force,
1319 unsigned long *nr_written)
1321 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1322 struct btrfs_root *root = BTRFS_I(inode)->root;
1323 struct btrfs_path *path;
1324 u64 cow_start = (u64)-1;
1325 u64 cur_offset = start;
1327 bool check_prev = true;
1328 const bool freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
1329 u64 ino = btrfs_ino(BTRFS_I(inode));
1331 u64 disk_bytenr = 0;
1333 path = btrfs_alloc_path();
1335 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1336 EXTENT_LOCKED | EXTENT_DELALLOC |
1337 EXTENT_DO_ACCOUNTING |
1338 EXTENT_DEFRAG, PAGE_UNLOCK |
1340 PAGE_SET_WRITEBACK |
1341 PAGE_END_WRITEBACK);
1346 struct btrfs_key found_key;
1347 struct btrfs_file_extent_item *fi;
1348 struct extent_buffer *leaf;
1358 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1364 * If there is no extent for our range when doing the initial
1365 * search, then go back to the previous slot as it will be the
1366 * one containing the search offset
1368 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1369 leaf = path->nodes[0];
1370 btrfs_item_key_to_cpu(leaf, &found_key,
1371 path->slots[0] - 1);
1372 if (found_key.objectid == ino &&
1373 found_key.type == BTRFS_EXTENT_DATA_KEY)
1378 /* Go to next leaf if we have exhausted the current one */
1379 leaf = path->nodes[0];
1380 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1381 ret = btrfs_next_leaf(root, path);
1383 if (cow_start != (u64)-1)
1384 cur_offset = cow_start;
1389 leaf = path->nodes[0];
1392 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1394 /* Didn't find anything for our INO */
1395 if (found_key.objectid > ino)
1398 * Keep searching until we find an EXTENT_ITEM or there are no
1399 * more extents for this inode
1401 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1402 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1407 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1408 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1409 found_key.offset > end)
1413 * If the found extent starts after requested offset, then
1414 * adjust extent_end to be right before this extent begins
1416 if (found_key.offset > cur_offset) {
1417 extent_end = found_key.offset;
1423 * Found extent which begins before our range and potentially
1426 fi = btrfs_item_ptr(leaf, path->slots[0],
1427 struct btrfs_file_extent_item);
1428 extent_type = btrfs_file_extent_type(leaf, fi);
1430 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1431 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1432 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1433 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1434 extent_offset = btrfs_file_extent_offset(leaf, fi);
1435 extent_end = found_key.offset +
1436 btrfs_file_extent_num_bytes(leaf, fi);
1438 btrfs_file_extent_disk_num_bytes(leaf, fi);
1440 * If extent we got ends before our range starts, skip
1443 if (extent_end <= start) {
1448 if (disk_bytenr == 0)
1450 /* Skip compressed/encrypted/encoded extents */
1451 if (btrfs_file_extent_compression(leaf, fi) ||
1452 btrfs_file_extent_encryption(leaf, fi) ||
1453 btrfs_file_extent_other_encoding(leaf, fi))
1456 * If extent is created before the last volume's snapshot
1457 * this implies the extent is shared, hence we can't do
1458 * nocow. This is the same check as in
1459 * btrfs_cross_ref_exist but without calling
1460 * btrfs_search_slot.
1462 if (!freespace_inode &&
1463 btrfs_file_extent_generation(leaf, fi) <=
1464 btrfs_root_last_snapshot(&root->root_item))
1466 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1468 /* If extent is RO, we must COW it */
1469 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1471 ret = btrfs_cross_ref_exist(root, ino,
1473 extent_offset, disk_bytenr);
1476 * ret could be -EIO if the above fails to read
1480 if (cow_start != (u64)-1)
1481 cur_offset = cow_start;
1485 WARN_ON_ONCE(freespace_inode);
1488 disk_bytenr += extent_offset;
1489 disk_bytenr += cur_offset - found_key.offset;
1490 num_bytes = min(end + 1, extent_end) - cur_offset;
1492 * If there are pending snapshots for this root, we
1493 * fall into common COW way
1495 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1498 * force cow if csum exists in the range.
1499 * this ensure that csum for a given extent are
1500 * either valid or do not exist.
1502 ret = csum_exist_in_range(fs_info, disk_bytenr,
1506 * ret could be -EIO if the above fails to read
1510 if (cow_start != (u64)-1)
1511 cur_offset = cow_start;
1514 WARN_ON_ONCE(freespace_inode);
1517 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1520 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1521 extent_end = found_key.offset + ram_bytes;
1522 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1523 /* Skip extents outside of our requested range */
1524 if (extent_end <= start) {
1529 /* If this triggers then we have a memory corruption */
1534 * If nocow is false then record the beginning of the range
1535 * that needs to be COWed
1538 if (cow_start == (u64)-1)
1539 cow_start = cur_offset;
1540 cur_offset = extent_end;
1541 if (cur_offset > end)
1547 btrfs_release_path(path);
1550 * COW range from cow_start to found_key.offset - 1. As the key
1551 * will contain the beginning of the first extent that can be
1552 * NOCOW, following one which needs to be COW'ed
1554 if (cow_start != (u64)-1) {
1555 ret = cow_file_range(inode, locked_page,
1556 cow_start, found_key.offset - 1,
1557 page_started, nr_written, 1);
1560 btrfs_dec_nocow_writers(fs_info,
1564 cow_start = (u64)-1;
1567 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1568 u64 orig_start = found_key.offset - extent_offset;
1569 struct extent_map *em;
1571 em = create_io_em(inode, cur_offset, num_bytes,
1573 disk_bytenr, /* block_start */
1574 num_bytes, /* block_len */
1575 disk_num_bytes, /* orig_block_len */
1576 ram_bytes, BTRFS_COMPRESS_NONE,
1577 BTRFS_ORDERED_PREALLOC);
1580 btrfs_dec_nocow_writers(fs_info,
1585 free_extent_map(em);
1586 ret = btrfs_add_ordered_extent(inode, cur_offset,
1587 disk_bytenr, num_bytes,
1589 BTRFS_ORDERED_PREALLOC);
1591 btrfs_drop_extent_cache(BTRFS_I(inode),
1593 cur_offset + num_bytes - 1,
1598 ret = btrfs_add_ordered_extent(inode, cur_offset,
1599 disk_bytenr, num_bytes,
1601 BTRFS_ORDERED_NOCOW);
1607 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1610 if (root->root_key.objectid ==
1611 BTRFS_DATA_RELOC_TREE_OBJECTID)
1613 * Error handled later, as we must prevent
1614 * extent_clear_unlock_delalloc() in error handler
1615 * from freeing metadata of created ordered extent.
1617 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1620 extent_clear_unlock_delalloc(inode, cur_offset,
1621 cur_offset + num_bytes - 1,
1622 locked_page, EXTENT_LOCKED |
1624 EXTENT_CLEAR_DATA_RESV,
1625 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1627 cur_offset = extent_end;
1630 * btrfs_reloc_clone_csums() error, now we're OK to call error
1631 * handler, as metadata for created ordered extent will only
1632 * be freed by btrfs_finish_ordered_io().
1636 if (cur_offset > end)
1639 btrfs_release_path(path);
1641 if (cur_offset <= end && cow_start == (u64)-1)
1642 cow_start = cur_offset;
1644 if (cow_start != (u64)-1) {
1646 ret = cow_file_range(inode, locked_page, cow_start, end,
1647 page_started, nr_written, 1);
1654 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1656 if (ret && cur_offset < end)
1657 extent_clear_unlock_delalloc(inode, cur_offset, end,
1658 locked_page, EXTENT_LOCKED |
1659 EXTENT_DELALLOC | EXTENT_DEFRAG |
1660 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1662 PAGE_SET_WRITEBACK |
1663 PAGE_END_WRITEBACK);
1664 btrfs_free_path(path);
1668 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1671 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1672 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1676 * @defrag_bytes is a hint value, no spinlock held here,
1677 * if is not zero, it means the file is defragging.
1678 * Force cow if given extent needs to be defragged.
1680 if (BTRFS_I(inode)->defrag_bytes &&
1681 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1682 EXTENT_DEFRAG, 0, NULL))
1689 * Function to process delayed allocation (create CoW) for ranges which are
1690 * being touched for the first time.
1692 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1693 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1694 struct writeback_control *wbc)
1697 int force_cow = need_force_cow(inode, start, end);
1698 unsigned int write_flags = wbc_to_write_flags(wbc);
1700 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1701 ret = run_delalloc_nocow(inode, locked_page, start, end,
1702 page_started, 1, nr_written);
1703 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1704 ret = run_delalloc_nocow(inode, locked_page, start, end,
1705 page_started, 0, nr_written);
1706 } else if (!inode_can_compress(inode) ||
1707 !inode_need_compress(inode, start, end)) {
1708 ret = cow_file_range(inode, locked_page, start, end,
1709 page_started, nr_written, 1);
1711 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1712 &BTRFS_I(inode)->runtime_flags);
1713 ret = cow_file_range_async(inode, locked_page, start, end,
1714 page_started, nr_written,
1718 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1723 void btrfs_split_delalloc_extent(struct inode *inode,
1724 struct extent_state *orig, u64 split)
1728 /* not delalloc, ignore it */
1729 if (!(orig->state & EXTENT_DELALLOC))
1732 size = orig->end - orig->start + 1;
1733 if (size > BTRFS_MAX_EXTENT_SIZE) {
1738 * See the explanation in btrfs_merge_delalloc_extent, the same
1739 * applies here, just in reverse.
1741 new_size = orig->end - split + 1;
1742 num_extents = count_max_extents(new_size);
1743 new_size = split - orig->start;
1744 num_extents += count_max_extents(new_size);
1745 if (count_max_extents(size) >= num_extents)
1749 spin_lock(&BTRFS_I(inode)->lock);
1750 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1751 spin_unlock(&BTRFS_I(inode)->lock);
1755 * Handle merged delayed allocation extents so we can keep track of new extents
1756 * that are just merged onto old extents, such as when we are doing sequential
1757 * writes, so we can properly account for the metadata space we'll need.
1759 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1760 struct extent_state *other)
1762 u64 new_size, old_size;
1765 /* not delalloc, ignore it */
1766 if (!(other->state & EXTENT_DELALLOC))
1769 if (new->start > other->start)
1770 new_size = new->end - other->start + 1;
1772 new_size = other->end - new->start + 1;
1774 /* we're not bigger than the max, unreserve the space and go */
1775 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1776 spin_lock(&BTRFS_I(inode)->lock);
1777 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1778 spin_unlock(&BTRFS_I(inode)->lock);
1783 * We have to add up either side to figure out how many extents were
1784 * accounted for before we merged into one big extent. If the number of
1785 * extents we accounted for is <= the amount we need for the new range
1786 * then we can return, otherwise drop. Think of it like this
1790 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1791 * need 2 outstanding extents, on one side we have 1 and the other side
1792 * we have 1 so they are == and we can return. But in this case
1794 * [MAX_SIZE+4k][MAX_SIZE+4k]
1796 * Each range on their own accounts for 2 extents, but merged together
1797 * they are only 3 extents worth of accounting, so we need to drop in
1800 old_size = other->end - other->start + 1;
1801 num_extents = count_max_extents(old_size);
1802 old_size = new->end - new->start + 1;
1803 num_extents += count_max_extents(old_size);
1804 if (count_max_extents(new_size) >= num_extents)
1807 spin_lock(&BTRFS_I(inode)->lock);
1808 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1809 spin_unlock(&BTRFS_I(inode)->lock);
1812 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1813 struct inode *inode)
1815 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1817 spin_lock(&root->delalloc_lock);
1818 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1819 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1820 &root->delalloc_inodes);
1821 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1822 &BTRFS_I(inode)->runtime_flags);
1823 root->nr_delalloc_inodes++;
1824 if (root->nr_delalloc_inodes == 1) {
1825 spin_lock(&fs_info->delalloc_root_lock);
1826 BUG_ON(!list_empty(&root->delalloc_root));
1827 list_add_tail(&root->delalloc_root,
1828 &fs_info->delalloc_roots);
1829 spin_unlock(&fs_info->delalloc_root_lock);
1832 spin_unlock(&root->delalloc_lock);
1836 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1837 struct btrfs_inode *inode)
1839 struct btrfs_fs_info *fs_info = root->fs_info;
1841 if (!list_empty(&inode->delalloc_inodes)) {
1842 list_del_init(&inode->delalloc_inodes);
1843 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1844 &inode->runtime_flags);
1845 root->nr_delalloc_inodes--;
1846 if (!root->nr_delalloc_inodes) {
1847 ASSERT(list_empty(&root->delalloc_inodes));
1848 spin_lock(&fs_info->delalloc_root_lock);
1849 BUG_ON(list_empty(&root->delalloc_root));
1850 list_del_init(&root->delalloc_root);
1851 spin_unlock(&fs_info->delalloc_root_lock);
1856 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1857 struct btrfs_inode *inode)
1859 spin_lock(&root->delalloc_lock);
1860 __btrfs_del_delalloc_inode(root, inode);
1861 spin_unlock(&root->delalloc_lock);
1865 * Properly track delayed allocation bytes in the inode and to maintain the
1866 * list of inodes that have pending delalloc work to be done.
1868 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1871 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1873 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1876 * set_bit and clear bit hooks normally require _irqsave/restore
1877 * but in this case, we are only testing for the DELALLOC
1878 * bit, which is only set or cleared with irqs on
1880 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1881 struct btrfs_root *root = BTRFS_I(inode)->root;
1882 u64 len = state->end + 1 - state->start;
1883 u32 num_extents = count_max_extents(len);
1884 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1886 spin_lock(&BTRFS_I(inode)->lock);
1887 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1888 spin_unlock(&BTRFS_I(inode)->lock);
1890 /* For sanity tests */
1891 if (btrfs_is_testing(fs_info))
1894 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1895 fs_info->delalloc_batch);
1896 spin_lock(&BTRFS_I(inode)->lock);
1897 BTRFS_I(inode)->delalloc_bytes += len;
1898 if (*bits & EXTENT_DEFRAG)
1899 BTRFS_I(inode)->defrag_bytes += len;
1900 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1901 &BTRFS_I(inode)->runtime_flags))
1902 btrfs_add_delalloc_inodes(root, inode);
1903 spin_unlock(&BTRFS_I(inode)->lock);
1906 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1907 (*bits & EXTENT_DELALLOC_NEW)) {
1908 spin_lock(&BTRFS_I(inode)->lock);
1909 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1911 spin_unlock(&BTRFS_I(inode)->lock);
1916 * Once a range is no longer delalloc this function ensures that proper
1917 * accounting happens.
1919 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1920 struct extent_state *state, unsigned *bits)
1922 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1923 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1924 u64 len = state->end + 1 - state->start;
1925 u32 num_extents = count_max_extents(len);
1927 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1928 spin_lock(&inode->lock);
1929 inode->defrag_bytes -= len;
1930 spin_unlock(&inode->lock);
1934 * set_bit and clear bit hooks normally require _irqsave/restore
1935 * but in this case, we are only testing for the DELALLOC
1936 * bit, which is only set or cleared with irqs on
1938 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1939 struct btrfs_root *root = inode->root;
1940 bool do_list = !btrfs_is_free_space_inode(inode);
1942 spin_lock(&inode->lock);
1943 btrfs_mod_outstanding_extents(inode, -num_extents);
1944 spin_unlock(&inode->lock);
1947 * We don't reserve metadata space for space cache inodes so we
1948 * don't need to call delalloc_release_metadata if there is an
1951 if (*bits & EXTENT_CLEAR_META_RESV &&
1952 root != fs_info->tree_root)
1953 btrfs_delalloc_release_metadata(inode, len, false);
1955 /* For sanity tests. */
1956 if (btrfs_is_testing(fs_info))
1959 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1960 do_list && !(state->state & EXTENT_NORESERVE) &&
1961 (*bits & EXTENT_CLEAR_DATA_RESV))
1962 btrfs_free_reserved_data_space_noquota(
1966 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1967 fs_info->delalloc_batch);
1968 spin_lock(&inode->lock);
1969 inode->delalloc_bytes -= len;
1970 if (do_list && inode->delalloc_bytes == 0 &&
1971 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1972 &inode->runtime_flags))
1973 btrfs_del_delalloc_inode(root, inode);
1974 spin_unlock(&inode->lock);
1977 if ((state->state & EXTENT_DELALLOC_NEW) &&
1978 (*bits & EXTENT_DELALLOC_NEW)) {
1979 spin_lock(&inode->lock);
1980 ASSERT(inode->new_delalloc_bytes >= len);
1981 inode->new_delalloc_bytes -= len;
1982 spin_unlock(&inode->lock);
1987 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1988 * in a chunk's stripe. This function ensures that bios do not span a
1991 * @page - The page we are about to add to the bio
1992 * @size - size we want to add to the bio
1993 * @bio - bio we want to ensure is smaller than a stripe
1994 * @bio_flags - flags of the bio
1996 * return 1 if page cannot be added to the bio
1997 * return 0 if page can be added to the bio
1998 * return error otherwise
2000 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2001 unsigned long bio_flags)
2003 struct inode *inode = page->mapping->host;
2004 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2005 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2009 struct btrfs_io_geometry geom;
2011 if (bio_flags & EXTENT_BIO_COMPRESSED)
2014 length = bio->bi_iter.bi_size;
2015 map_length = length;
2016 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2021 if (geom.len < length + size)
2027 * in order to insert checksums into the metadata in large chunks,
2028 * we wait until bio submission time. All the pages in the bio are
2029 * checksummed and sums are attached onto the ordered extent record.
2031 * At IO completion time the cums attached on the ordered extent record
2032 * are inserted into the btree
2034 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2037 struct inode *inode = private_data;
2038 blk_status_t ret = 0;
2040 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2041 BUG_ON(ret); /* -ENOMEM */
2046 * extent_io.c submission hook. This does the right thing for csum calculation
2047 * on write, or reading the csums from the tree before a read.
2049 * Rules about async/sync submit,
2050 * a) read: sync submit
2052 * b) write without checksum: sync submit
2054 * c) write with checksum:
2055 * c-1) if bio is issued by fsync: sync submit
2056 * (sync_writers != 0)
2058 * c-2) if root is reloc root: sync submit
2059 * (only in case of buffered IO)
2061 * c-3) otherwise: async submit
2063 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2065 unsigned long bio_flags)
2068 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2069 struct btrfs_root *root = BTRFS_I(inode)->root;
2070 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2071 blk_status_t ret = 0;
2073 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2075 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2077 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2078 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2080 if (bio_op(bio) != REQ_OP_WRITE) {
2081 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2085 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2086 ret = btrfs_submit_compressed_read(inode, bio,
2090 } else if (!skip_sum) {
2091 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2096 } else if (async && !skip_sum) {
2097 /* csum items have already been cloned */
2098 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2100 /* we're doing a write, do the async checksumming */
2101 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2102 0, inode, btrfs_submit_bio_start);
2104 } else if (!skip_sum) {
2105 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2111 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2115 bio->bi_status = ret;
2122 * given a list of ordered sums record them in the inode. This happens
2123 * at IO completion time based on sums calculated at bio submission time.
2125 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2126 struct inode *inode, struct list_head *list)
2128 struct btrfs_ordered_sum *sum;
2131 list_for_each_entry(sum, list, list) {
2132 trans->adding_csums = true;
2133 ret = btrfs_csum_file_blocks(trans,
2134 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2135 trans->adding_csums = false;
2142 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2143 unsigned int extra_bits,
2144 struct extent_state **cached_state)
2146 WARN_ON(PAGE_ALIGNED(end));
2147 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2148 extra_bits, cached_state);
2151 /* see btrfs_writepage_start_hook for details on why this is required */
2152 struct btrfs_writepage_fixup {
2154 struct btrfs_work work;
2157 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2159 struct btrfs_writepage_fixup *fixup;
2160 struct btrfs_ordered_extent *ordered;
2161 struct extent_state *cached_state = NULL;
2162 struct extent_changeset *data_reserved = NULL;
2164 struct inode *inode;
2169 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2173 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2174 ClearPageChecked(page);
2178 inode = page->mapping->host;
2179 page_start = page_offset(page);
2180 page_end = page_offset(page) + PAGE_SIZE - 1;
2182 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2185 /* already ordered? We're done */
2186 if (PagePrivate2(page))
2189 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2192 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2193 page_end, &cached_state);
2195 btrfs_start_ordered_extent(inode, ordered, 1);
2196 btrfs_put_ordered_extent(ordered);
2200 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2203 mapping_set_error(page->mapping, ret);
2204 end_extent_writepage(page, ret, page_start, page_end);
2205 ClearPageChecked(page);
2209 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2212 mapping_set_error(page->mapping, ret);
2213 end_extent_writepage(page, ret, page_start, page_end);
2214 ClearPageChecked(page);
2218 ClearPageChecked(page);
2219 set_page_dirty(page);
2220 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2222 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2228 extent_changeset_free(data_reserved);
2232 * There are a few paths in the higher layers of the kernel that directly
2233 * set the page dirty bit without asking the filesystem if it is a
2234 * good idea. This causes problems because we want to make sure COW
2235 * properly happens and the data=ordered rules are followed.
2237 * In our case any range that doesn't have the ORDERED bit set
2238 * hasn't been properly setup for IO. We kick off an async process
2239 * to fix it up. The async helper will wait for ordered extents, set
2240 * the delalloc bit and make it safe to write the page.
2242 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2244 struct inode *inode = page->mapping->host;
2245 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2246 struct btrfs_writepage_fixup *fixup;
2248 /* this page is properly in the ordered list */
2249 if (TestClearPagePrivate2(page))
2252 if (PageChecked(page))
2255 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2259 SetPageChecked(page);
2261 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2263 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2267 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2268 struct inode *inode, u64 file_pos,
2269 u64 disk_bytenr, u64 disk_num_bytes,
2270 u64 num_bytes, u64 ram_bytes,
2271 u8 compression, u8 encryption,
2272 u16 other_encoding, int extent_type)
2274 struct btrfs_root *root = BTRFS_I(inode)->root;
2275 struct btrfs_file_extent_item *fi;
2276 struct btrfs_path *path;
2277 struct extent_buffer *leaf;
2278 struct btrfs_key ins;
2280 int extent_inserted = 0;
2283 path = btrfs_alloc_path();
2288 * we may be replacing one extent in the tree with another.
2289 * The new extent is pinned in the extent map, and we don't want
2290 * to drop it from the cache until it is completely in the btree.
2292 * So, tell btrfs_drop_extents to leave this extent in the cache.
2293 * the caller is expected to unpin it and allow it to be merged
2296 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2297 file_pos + num_bytes, NULL, 0,
2298 1, sizeof(*fi), &extent_inserted);
2302 if (!extent_inserted) {
2303 ins.objectid = btrfs_ino(BTRFS_I(inode));
2304 ins.offset = file_pos;
2305 ins.type = BTRFS_EXTENT_DATA_KEY;
2307 path->leave_spinning = 1;
2308 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2313 leaf = path->nodes[0];
2314 fi = btrfs_item_ptr(leaf, path->slots[0],
2315 struct btrfs_file_extent_item);
2316 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2317 btrfs_set_file_extent_type(leaf, fi, extent_type);
2318 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2319 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2320 btrfs_set_file_extent_offset(leaf, fi, 0);
2321 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2322 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2323 btrfs_set_file_extent_compression(leaf, fi, compression);
2324 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2325 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2327 btrfs_mark_buffer_dirty(leaf);
2328 btrfs_release_path(path);
2330 inode_add_bytes(inode, num_bytes);
2332 ins.objectid = disk_bytenr;
2333 ins.offset = disk_num_bytes;
2334 ins.type = BTRFS_EXTENT_ITEM_KEY;
2337 * Release the reserved range from inode dirty range map, as it is
2338 * already moved into delayed_ref_head
2340 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2344 ret = btrfs_alloc_reserved_file_extent(trans, root,
2345 btrfs_ino(BTRFS_I(inode)),
2346 file_pos, qg_released, &ins);
2348 btrfs_free_path(path);
2353 /* snapshot-aware defrag */
2354 struct sa_defrag_extent_backref {
2355 struct rb_node node;
2356 struct old_sa_defrag_extent *old;
2365 struct old_sa_defrag_extent {
2366 struct list_head list;
2367 struct new_sa_defrag_extent *new;
2376 struct new_sa_defrag_extent {
2377 struct rb_root root;
2378 struct list_head head;
2379 struct btrfs_path *path;
2380 struct inode *inode;
2388 static int backref_comp(struct sa_defrag_extent_backref *b1,
2389 struct sa_defrag_extent_backref *b2)
2391 if (b1->root_id < b2->root_id)
2393 else if (b1->root_id > b2->root_id)
2396 if (b1->inum < b2->inum)
2398 else if (b1->inum > b2->inum)
2401 if (b1->file_pos < b2->file_pos)
2403 else if (b1->file_pos > b2->file_pos)
2407 * [------------------------------] ===> (a range of space)
2408 * |<--->| |<---->| =============> (fs/file tree A)
2409 * |<---------------------------->| ===> (fs/file tree B)
2411 * A range of space can refer to two file extents in one tree while
2412 * refer to only one file extent in another tree.
2414 * So we may process a disk offset more than one time(two extents in A)
2415 * and locate at the same extent(one extent in B), then insert two same
2416 * backrefs(both refer to the extent in B).
2421 static void backref_insert(struct rb_root *root,
2422 struct sa_defrag_extent_backref *backref)
2424 struct rb_node **p = &root->rb_node;
2425 struct rb_node *parent = NULL;
2426 struct sa_defrag_extent_backref *entry;
2431 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2433 ret = backref_comp(backref, entry);
2437 p = &(*p)->rb_right;
2440 rb_link_node(&backref->node, parent, p);
2441 rb_insert_color(&backref->node, root);
2445 * Note the backref might has changed, and in this case we just return 0.
2447 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2450 struct btrfs_file_extent_item *extent;
2451 struct old_sa_defrag_extent *old = ctx;
2452 struct new_sa_defrag_extent *new = old->new;
2453 struct btrfs_path *path = new->path;
2454 struct btrfs_key key;
2455 struct btrfs_root *root;
2456 struct sa_defrag_extent_backref *backref;
2457 struct extent_buffer *leaf;
2458 struct inode *inode = new->inode;
2459 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2465 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2466 inum == btrfs_ino(BTRFS_I(inode)))
2469 key.objectid = root_id;
2470 key.type = BTRFS_ROOT_ITEM_KEY;
2471 key.offset = (u64)-1;
2473 root = btrfs_read_fs_root_no_name(fs_info, &key);
2475 if (PTR_ERR(root) == -ENOENT)
2478 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2479 inum, offset, root_id);
2480 return PTR_ERR(root);
2483 key.objectid = inum;
2484 key.type = BTRFS_EXTENT_DATA_KEY;
2485 if (offset > (u64)-1 << 32)
2488 key.offset = offset;
2490 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2491 if (WARN_ON(ret < 0))
2498 leaf = path->nodes[0];
2499 slot = path->slots[0];
2501 if (slot >= btrfs_header_nritems(leaf)) {
2502 ret = btrfs_next_leaf(root, path);
2505 } else if (ret > 0) {
2514 btrfs_item_key_to_cpu(leaf, &key, slot);
2516 if (key.objectid > inum)
2519 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2522 extent = btrfs_item_ptr(leaf, slot,
2523 struct btrfs_file_extent_item);
2525 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2529 * 'offset' refers to the exact key.offset,
2530 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2531 * (key.offset - extent_offset).
2533 if (key.offset != offset)
2536 extent_offset = btrfs_file_extent_offset(leaf, extent);
2537 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2539 if (extent_offset >= old->extent_offset + old->offset +
2540 old->len || extent_offset + num_bytes <=
2541 old->extent_offset + old->offset)
2546 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2552 backref->root_id = root_id;
2553 backref->inum = inum;
2554 backref->file_pos = offset;
2555 backref->num_bytes = num_bytes;
2556 backref->extent_offset = extent_offset;
2557 backref->generation = btrfs_file_extent_generation(leaf, extent);
2559 backref_insert(&new->root, backref);
2562 btrfs_release_path(path);
2567 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2568 struct new_sa_defrag_extent *new)
2570 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2571 struct old_sa_defrag_extent *old, *tmp;
2576 list_for_each_entry_safe(old, tmp, &new->head, list) {
2577 ret = iterate_inodes_from_logical(old->bytenr +
2578 old->extent_offset, fs_info,
2579 path, record_one_backref,
2581 if (ret < 0 && ret != -ENOENT)
2584 /* no backref to be processed for this extent */
2586 list_del(&old->list);
2591 if (list_empty(&new->head))
2597 static int relink_is_mergable(struct extent_buffer *leaf,
2598 struct btrfs_file_extent_item *fi,
2599 struct new_sa_defrag_extent *new)
2601 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2604 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2607 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2610 if (btrfs_file_extent_encryption(leaf, fi) ||
2611 btrfs_file_extent_other_encoding(leaf, fi))
2618 * Note the backref might has changed, and in this case we just return 0.
2620 static noinline int relink_extent_backref(struct btrfs_path *path,
2621 struct sa_defrag_extent_backref *prev,
2622 struct sa_defrag_extent_backref *backref)
2624 struct btrfs_file_extent_item *extent;
2625 struct btrfs_file_extent_item *item;
2626 struct btrfs_ordered_extent *ordered;
2627 struct btrfs_trans_handle *trans;
2628 struct btrfs_ref ref = { 0 };
2629 struct btrfs_root *root;
2630 struct btrfs_key key;
2631 struct extent_buffer *leaf;
2632 struct old_sa_defrag_extent *old = backref->old;
2633 struct new_sa_defrag_extent *new = old->new;
2634 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2635 struct inode *inode;
2636 struct extent_state *cached = NULL;
2645 if (prev && prev->root_id == backref->root_id &&
2646 prev->inum == backref->inum &&
2647 prev->file_pos + prev->num_bytes == backref->file_pos)
2650 /* step 1: get root */
2651 key.objectid = backref->root_id;
2652 key.type = BTRFS_ROOT_ITEM_KEY;
2653 key.offset = (u64)-1;
2655 index = srcu_read_lock(&fs_info->subvol_srcu);
2657 root = btrfs_read_fs_root_no_name(fs_info, &key);
2659 srcu_read_unlock(&fs_info->subvol_srcu, index);
2660 if (PTR_ERR(root) == -ENOENT)
2662 return PTR_ERR(root);
2665 if (btrfs_root_readonly(root)) {
2666 srcu_read_unlock(&fs_info->subvol_srcu, index);
2670 /* step 2: get inode */
2671 key.objectid = backref->inum;
2672 key.type = BTRFS_INODE_ITEM_KEY;
2675 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2676 if (IS_ERR(inode)) {
2677 srcu_read_unlock(&fs_info->subvol_srcu, index);
2681 srcu_read_unlock(&fs_info->subvol_srcu, index);
2683 /* step 3: relink backref */
2684 lock_start = backref->file_pos;
2685 lock_end = backref->file_pos + backref->num_bytes - 1;
2686 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2689 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2691 btrfs_put_ordered_extent(ordered);
2695 trans = btrfs_join_transaction(root);
2696 if (IS_ERR(trans)) {
2697 ret = PTR_ERR(trans);
2701 key.objectid = backref->inum;
2702 key.type = BTRFS_EXTENT_DATA_KEY;
2703 key.offset = backref->file_pos;
2705 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2708 } else if (ret > 0) {
2713 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2714 struct btrfs_file_extent_item);
2716 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2717 backref->generation)
2720 btrfs_release_path(path);
2722 start = backref->file_pos;
2723 if (backref->extent_offset < old->extent_offset + old->offset)
2724 start += old->extent_offset + old->offset -
2725 backref->extent_offset;
2727 len = min(backref->extent_offset + backref->num_bytes,
2728 old->extent_offset + old->offset + old->len);
2729 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2731 ret = btrfs_drop_extents(trans, root, inode, start,
2736 key.objectid = btrfs_ino(BTRFS_I(inode));
2737 key.type = BTRFS_EXTENT_DATA_KEY;
2740 path->leave_spinning = 1;
2742 struct btrfs_file_extent_item *fi;
2744 struct btrfs_key found_key;
2746 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2751 leaf = path->nodes[0];
2752 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2754 fi = btrfs_item_ptr(leaf, path->slots[0],
2755 struct btrfs_file_extent_item);
2756 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2758 if (extent_len + found_key.offset == start &&
2759 relink_is_mergable(leaf, fi, new)) {
2760 btrfs_set_file_extent_num_bytes(leaf, fi,
2762 btrfs_mark_buffer_dirty(leaf);
2763 inode_add_bytes(inode, len);
2769 btrfs_release_path(path);
2774 ret = btrfs_insert_empty_item(trans, root, path, &key,
2777 btrfs_abort_transaction(trans, ret);
2781 leaf = path->nodes[0];
2782 item = btrfs_item_ptr(leaf, path->slots[0],
2783 struct btrfs_file_extent_item);
2784 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2785 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2786 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2787 btrfs_set_file_extent_num_bytes(leaf, item, len);
2788 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2789 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2790 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2791 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2792 btrfs_set_file_extent_encryption(leaf, item, 0);
2793 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2795 btrfs_mark_buffer_dirty(leaf);
2796 inode_add_bytes(inode, len);
2797 btrfs_release_path(path);
2799 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2801 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2802 new->file_pos); /* start - extent_offset */
2803 ret = btrfs_inc_extent_ref(trans, &ref);
2805 btrfs_abort_transaction(trans, ret);
2811 btrfs_release_path(path);
2812 path->leave_spinning = 0;
2813 btrfs_end_transaction(trans);
2815 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2821 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2823 struct old_sa_defrag_extent *old, *tmp;
2828 list_for_each_entry_safe(old, tmp, &new->head, list) {
2834 static void relink_file_extents(struct new_sa_defrag_extent *new)
2836 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2837 struct btrfs_path *path;
2838 struct sa_defrag_extent_backref *backref;
2839 struct sa_defrag_extent_backref *prev = NULL;
2840 struct rb_node *node;
2843 path = btrfs_alloc_path();
2847 if (!record_extent_backrefs(path, new)) {
2848 btrfs_free_path(path);
2851 btrfs_release_path(path);
2854 node = rb_first(&new->root);
2857 rb_erase(node, &new->root);
2859 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2861 ret = relink_extent_backref(path, prev, backref);
2874 btrfs_free_path(path);
2876 free_sa_defrag_extent(new);
2878 atomic_dec(&fs_info->defrag_running);
2879 wake_up(&fs_info->transaction_wait);
2882 static struct new_sa_defrag_extent *
2883 record_old_file_extents(struct inode *inode,
2884 struct btrfs_ordered_extent *ordered)
2886 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2887 struct btrfs_root *root = BTRFS_I(inode)->root;
2888 struct btrfs_path *path;
2889 struct btrfs_key key;
2890 struct old_sa_defrag_extent *old;
2891 struct new_sa_defrag_extent *new;
2894 new = kmalloc(sizeof(*new), GFP_NOFS);
2899 new->file_pos = ordered->file_offset;
2900 new->len = ordered->len;
2901 new->bytenr = ordered->start;
2902 new->disk_len = ordered->disk_len;
2903 new->compress_type = ordered->compress_type;
2904 new->root = RB_ROOT;
2905 INIT_LIST_HEAD(&new->head);
2907 path = btrfs_alloc_path();
2911 key.objectid = btrfs_ino(BTRFS_I(inode));
2912 key.type = BTRFS_EXTENT_DATA_KEY;
2913 key.offset = new->file_pos;
2915 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2918 if (ret > 0 && path->slots[0] > 0)
2921 /* find out all the old extents for the file range */
2923 struct btrfs_file_extent_item *extent;
2924 struct extent_buffer *l;
2933 slot = path->slots[0];
2935 if (slot >= btrfs_header_nritems(l)) {
2936 ret = btrfs_next_leaf(root, path);
2944 btrfs_item_key_to_cpu(l, &key, slot);
2946 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2948 if (key.type != BTRFS_EXTENT_DATA_KEY)
2950 if (key.offset >= new->file_pos + new->len)
2953 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2955 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2956 if (key.offset + num_bytes < new->file_pos)
2959 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2963 extent_offset = btrfs_file_extent_offset(l, extent);
2965 old = kmalloc(sizeof(*old), GFP_NOFS);
2969 offset = max(new->file_pos, key.offset);
2970 end = min(new->file_pos + new->len, key.offset + num_bytes);
2972 old->bytenr = disk_bytenr;
2973 old->extent_offset = extent_offset;
2974 old->offset = offset - key.offset;
2975 old->len = end - offset;
2978 list_add_tail(&old->list, &new->head);
2984 btrfs_free_path(path);
2985 atomic_inc(&fs_info->defrag_running);
2990 btrfs_free_path(path);
2992 free_sa_defrag_extent(new);
2996 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2999 struct btrfs_block_group_cache *cache;
3001 cache = btrfs_lookup_block_group(fs_info, start);
3004 spin_lock(&cache->lock);
3005 cache->delalloc_bytes -= len;
3006 spin_unlock(&cache->lock);
3008 btrfs_put_block_group(cache);
3011 /* as ordered data IO finishes, this gets called so we can finish
3012 * an ordered extent if the range of bytes in the file it covers are
3015 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3017 struct inode *inode = ordered_extent->inode;
3018 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3019 struct btrfs_root *root = BTRFS_I(inode)->root;
3020 struct btrfs_trans_handle *trans = NULL;
3021 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3022 struct extent_state *cached_state = NULL;
3023 struct new_sa_defrag_extent *new = NULL;
3024 int compress_type = 0;
3026 u64 logical_len = ordered_extent->len;
3028 bool truncated = false;
3029 bool range_locked = false;
3030 bool clear_new_delalloc_bytes = false;
3031 bool clear_reserved_extent = true;
3033 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3034 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3035 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
3036 clear_new_delalloc_bytes = true;
3038 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
3040 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3045 btrfs_free_io_failure_record(BTRFS_I(inode),
3046 ordered_extent->file_offset,
3047 ordered_extent->file_offset +
3048 ordered_extent->len - 1);
3050 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3052 logical_len = ordered_extent->truncated_len;
3053 /* Truncated the entire extent, don't bother adding */
3058 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3059 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3062 * For mwrite(mmap + memset to write) case, we still reserve
3063 * space for NOCOW range.
3064 * As NOCOW won't cause a new delayed ref, just free the space
3066 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3067 ordered_extent->len);
3068 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3070 trans = btrfs_join_transaction_nolock(root);
3072 trans = btrfs_join_transaction(root);
3073 if (IS_ERR(trans)) {
3074 ret = PTR_ERR(trans);
3078 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3079 ret = btrfs_update_inode_fallback(trans, root, inode);
3080 if (ret) /* -ENOMEM or corruption */
3081 btrfs_abort_transaction(trans, ret);
3085 range_locked = true;
3086 lock_extent_bits(io_tree, ordered_extent->file_offset,
3087 ordered_extent->file_offset + ordered_extent->len - 1,
3090 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3091 ordered_extent->file_offset + ordered_extent->len - 1,
3092 EXTENT_DEFRAG, 0, cached_state);
3094 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3095 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3096 /* the inode is shared */
3097 new = record_old_file_extents(inode, ordered_extent);
3099 clear_extent_bit(io_tree, ordered_extent->file_offset,
3100 ordered_extent->file_offset + ordered_extent->len - 1,
3101 EXTENT_DEFRAG, 0, 0, &cached_state);
3105 trans = btrfs_join_transaction_nolock(root);
3107 trans = btrfs_join_transaction(root);
3108 if (IS_ERR(trans)) {
3109 ret = PTR_ERR(trans);
3114 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3116 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3117 compress_type = ordered_extent->compress_type;
3118 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3119 BUG_ON(compress_type);
3120 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3121 ordered_extent->len);
3122 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3123 ordered_extent->file_offset,
3124 ordered_extent->file_offset +
3127 BUG_ON(root == fs_info->tree_root);
3128 ret = insert_reserved_file_extent(trans, inode,
3129 ordered_extent->file_offset,
3130 ordered_extent->start,
3131 ordered_extent->disk_len,
3132 logical_len, logical_len,
3133 compress_type, 0, 0,
3134 BTRFS_FILE_EXTENT_REG);
3136 clear_reserved_extent = false;
3137 btrfs_release_delalloc_bytes(fs_info,
3138 ordered_extent->start,
3139 ordered_extent->disk_len);
3142 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3143 ordered_extent->file_offset, ordered_extent->len,
3146 btrfs_abort_transaction(trans, ret);
3150 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3152 btrfs_abort_transaction(trans, ret);
3156 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3157 ret = btrfs_update_inode_fallback(trans, root, inode);
3158 if (ret) { /* -ENOMEM or corruption */
3159 btrfs_abort_transaction(trans, ret);
3164 if (range_locked || clear_new_delalloc_bytes) {
3165 unsigned int clear_bits = 0;
3168 clear_bits |= EXTENT_LOCKED;
3169 if (clear_new_delalloc_bytes)
3170 clear_bits |= EXTENT_DELALLOC_NEW;
3171 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3172 ordered_extent->file_offset,
3173 ordered_extent->file_offset +
3174 ordered_extent->len - 1,
3176 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3181 btrfs_end_transaction(trans);
3183 if (ret || truncated) {
3187 start = ordered_extent->file_offset + logical_len;
3189 start = ordered_extent->file_offset;
3190 end = ordered_extent->file_offset + ordered_extent->len - 1;
3191 clear_extent_uptodate(io_tree, start, end, NULL);
3193 /* Drop the cache for the part of the extent we didn't write. */
3194 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3197 * If the ordered extent had an IOERR or something else went
3198 * wrong we need to return the space for this ordered extent
3199 * back to the allocator. We only free the extent in the
3200 * truncated case if we didn't write out the extent at all.
3202 * If we made it past insert_reserved_file_extent before we
3203 * errored out then we don't need to do this as the accounting
3204 * has already been done.
3206 if ((ret || !logical_len) &&
3207 clear_reserved_extent &&
3208 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3209 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3210 btrfs_free_reserved_extent(fs_info,
3211 ordered_extent->start,
3212 ordered_extent->disk_len, 1);
3217 * This needs to be done to make sure anybody waiting knows we are done
3218 * updating everything for this ordered extent.
3220 btrfs_remove_ordered_extent(inode, ordered_extent);
3222 /* for snapshot-aware defrag */
3225 free_sa_defrag_extent(new);
3226 atomic_dec(&fs_info->defrag_running);
3228 relink_file_extents(new);
3233 btrfs_put_ordered_extent(ordered_extent);
3234 /* once for the tree */
3235 btrfs_put_ordered_extent(ordered_extent);
3240 static void finish_ordered_fn(struct btrfs_work *work)
3242 struct btrfs_ordered_extent *ordered_extent;
3243 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3244 btrfs_finish_ordered_io(ordered_extent);
3247 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3248 u64 end, int uptodate)
3250 struct inode *inode = page->mapping->host;
3251 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3252 struct btrfs_ordered_extent *ordered_extent = NULL;
3253 struct btrfs_workqueue *wq;
3255 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3257 ClearPagePrivate2(page);
3258 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3259 end - start + 1, uptodate))
3262 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
3263 wq = fs_info->endio_freespace_worker;
3265 wq = fs_info->endio_write_workers;
3267 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
3268 btrfs_queue_work(wq, &ordered_extent->work);
3271 static int __readpage_endio_check(struct inode *inode,
3272 struct btrfs_io_bio *io_bio,
3273 int icsum, struct page *page,
3274 int pgoff, u64 start, size_t len)
3276 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3277 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3279 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
3281 u8 csum[BTRFS_CSUM_SIZE];
3283 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
3285 kaddr = kmap_atomic(page);
3286 shash->tfm = fs_info->csum_shash;
3288 crypto_shash_init(shash);
3289 crypto_shash_update(shash, kaddr + pgoff, len);
3290 crypto_shash_final(shash, csum);
3292 if (memcmp(csum, csum_expected, csum_size))
3295 kunmap_atomic(kaddr);
3298 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3299 io_bio->mirror_num);
3300 memset(kaddr + pgoff, 1, len);
3301 flush_dcache_page(page);
3302 kunmap_atomic(kaddr);
3307 * when reads are done, we need to check csums to verify the data is correct
3308 * if there's a match, we allow the bio to finish. If not, the code in
3309 * extent_io.c will try to find good copies for us.
3311 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3312 u64 phy_offset, struct page *page,
3313 u64 start, u64 end, int mirror)
3315 size_t offset = start - page_offset(page);
3316 struct inode *inode = page->mapping->host;
3317 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3318 struct btrfs_root *root = BTRFS_I(inode)->root;
3320 if (PageChecked(page)) {
3321 ClearPageChecked(page);
3325 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3328 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3329 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3330 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3334 phy_offset >>= inode->i_sb->s_blocksize_bits;
3335 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3336 start, (size_t)(end - start + 1));
3340 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3342 * @inode: The inode we want to perform iput on
3344 * This function uses the generic vfs_inode::i_count to track whether we should
3345 * just decrement it (in case it's > 1) or if this is the last iput then link
3346 * the inode to the delayed iput machinery. Delayed iputs are processed at
3347 * transaction commit time/superblock commit/cleaner kthread.
3349 void btrfs_add_delayed_iput(struct inode *inode)
3351 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3352 struct btrfs_inode *binode = BTRFS_I(inode);
3354 if (atomic_add_unless(&inode->i_count, -1, 1))
3357 atomic_inc(&fs_info->nr_delayed_iputs);
3358 spin_lock(&fs_info->delayed_iput_lock);
3359 ASSERT(list_empty(&binode->delayed_iput));
3360 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3361 spin_unlock(&fs_info->delayed_iput_lock);
3362 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3363 wake_up_process(fs_info->cleaner_kthread);
3366 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3367 struct btrfs_inode *inode)
3369 list_del_init(&inode->delayed_iput);
3370 spin_unlock(&fs_info->delayed_iput_lock);
3371 iput(&inode->vfs_inode);
3372 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3373 wake_up(&fs_info->delayed_iputs_wait);
3374 spin_lock(&fs_info->delayed_iput_lock);
3377 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3378 struct btrfs_inode *inode)
3380 if (!list_empty(&inode->delayed_iput)) {
3381 spin_lock(&fs_info->delayed_iput_lock);
3382 if (!list_empty(&inode->delayed_iput))
3383 run_delayed_iput_locked(fs_info, inode);
3384 spin_unlock(&fs_info->delayed_iput_lock);
3388 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3391 spin_lock(&fs_info->delayed_iput_lock);
3392 while (!list_empty(&fs_info->delayed_iputs)) {
3393 struct btrfs_inode *inode;
3395 inode = list_first_entry(&fs_info->delayed_iputs,
3396 struct btrfs_inode, delayed_iput);
3397 run_delayed_iput_locked(fs_info, inode);
3399 spin_unlock(&fs_info->delayed_iput_lock);
3403 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3404 * @fs_info - the fs_info for this fs
3405 * @return - EINTR if we were killed, 0 if nothing's pending
3407 * This will wait on any delayed iputs that are currently running with KILLABLE
3408 * set. Once they are all done running we will return, unless we are killed in
3409 * which case we return EINTR. This helps in user operations like fallocate etc
3410 * that might get blocked on the iputs.
3412 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3414 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3415 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3422 * This creates an orphan entry for the given inode in case something goes wrong
3423 * in the middle of an unlink.
3425 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3426 struct btrfs_inode *inode)
3430 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3431 if (ret && ret != -EEXIST) {
3432 btrfs_abort_transaction(trans, ret);
3440 * We have done the delete so we can go ahead and remove the orphan item for
3441 * this particular inode.
3443 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3444 struct btrfs_inode *inode)
3446 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3450 * this cleans up any orphans that may be left on the list from the last use
3453 int btrfs_orphan_cleanup(struct btrfs_root *root)
3455 struct btrfs_fs_info *fs_info = root->fs_info;
3456 struct btrfs_path *path;
3457 struct extent_buffer *leaf;
3458 struct btrfs_key key, found_key;
3459 struct btrfs_trans_handle *trans;
3460 struct inode *inode;
3461 u64 last_objectid = 0;
3462 int ret = 0, nr_unlink = 0;
3464 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3467 path = btrfs_alloc_path();
3472 path->reada = READA_BACK;
3474 key.objectid = BTRFS_ORPHAN_OBJECTID;
3475 key.type = BTRFS_ORPHAN_ITEM_KEY;
3476 key.offset = (u64)-1;
3479 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3484 * if ret == 0 means we found what we were searching for, which
3485 * is weird, but possible, so only screw with path if we didn't
3486 * find the key and see if we have stuff that matches
3490 if (path->slots[0] == 0)
3495 /* pull out the item */
3496 leaf = path->nodes[0];
3497 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3499 /* make sure the item matches what we want */
3500 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3502 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3505 /* release the path since we're done with it */
3506 btrfs_release_path(path);
3509 * this is where we are basically btrfs_lookup, without the
3510 * crossing root thing. we store the inode number in the
3511 * offset of the orphan item.
3514 if (found_key.offset == last_objectid) {
3516 "Error removing orphan entry, stopping orphan cleanup");
3521 last_objectid = found_key.offset;
3523 found_key.objectid = found_key.offset;
3524 found_key.type = BTRFS_INODE_ITEM_KEY;
3525 found_key.offset = 0;
3526 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3527 ret = PTR_ERR_OR_ZERO(inode);
3528 if (ret && ret != -ENOENT)
3531 if (ret == -ENOENT && root == fs_info->tree_root) {
3532 struct btrfs_root *dead_root;
3533 struct btrfs_fs_info *fs_info = root->fs_info;
3534 int is_dead_root = 0;
3537 * this is an orphan in the tree root. Currently these
3538 * could come from 2 sources:
3539 * a) a snapshot deletion in progress
3540 * b) a free space cache inode
3541 * We need to distinguish those two, as the snapshot
3542 * orphan must not get deleted.
3543 * find_dead_roots already ran before us, so if this
3544 * is a snapshot deletion, we should find the root
3545 * in the dead_roots list
3547 spin_lock(&fs_info->trans_lock);
3548 list_for_each_entry(dead_root, &fs_info->dead_roots,
3550 if (dead_root->root_key.objectid ==
3551 found_key.objectid) {
3556 spin_unlock(&fs_info->trans_lock);
3558 /* prevent this orphan from being found again */
3559 key.offset = found_key.objectid - 1;
3566 * If we have an inode with links, there are a couple of
3567 * possibilities. Old kernels (before v3.12) used to create an
3568 * orphan item for truncate indicating that there were possibly
3569 * extent items past i_size that needed to be deleted. In v3.12,
3570 * truncate was changed to update i_size in sync with the extent
3571 * items, but the (useless) orphan item was still created. Since
3572 * v4.18, we don't create the orphan item for truncate at all.
3574 * So, this item could mean that we need to do a truncate, but
3575 * only if this filesystem was last used on a pre-v3.12 kernel
3576 * and was not cleanly unmounted. The odds of that are quite
3577 * slim, and it's a pain to do the truncate now, so just delete
3580 * It's also possible that this orphan item was supposed to be
3581 * deleted but wasn't. The inode number may have been reused,
3582 * but either way, we can delete the orphan item.
3584 if (ret == -ENOENT || inode->i_nlink) {
3587 trans = btrfs_start_transaction(root, 1);
3588 if (IS_ERR(trans)) {
3589 ret = PTR_ERR(trans);
3592 btrfs_debug(fs_info, "auto deleting %Lu",
3593 found_key.objectid);
3594 ret = btrfs_del_orphan_item(trans, root,
3595 found_key.objectid);
3596 btrfs_end_transaction(trans);
3604 /* this will do delete_inode and everything for us */
3607 /* release the path since we're done with it */
3608 btrfs_release_path(path);
3610 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3612 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3613 trans = btrfs_join_transaction(root);
3615 btrfs_end_transaction(trans);
3619 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3623 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3624 btrfs_free_path(path);
3629 * very simple check to peek ahead in the leaf looking for xattrs. If we
3630 * don't find any xattrs, we know there can't be any acls.
3632 * slot is the slot the inode is in, objectid is the objectid of the inode
3634 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3635 int slot, u64 objectid,
3636 int *first_xattr_slot)
3638 u32 nritems = btrfs_header_nritems(leaf);
3639 struct btrfs_key found_key;
3640 static u64 xattr_access = 0;
3641 static u64 xattr_default = 0;
3644 if (!xattr_access) {
3645 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3646 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3647 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3648 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3652 *first_xattr_slot = -1;
3653 while (slot < nritems) {
3654 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3656 /* we found a different objectid, there must not be acls */
3657 if (found_key.objectid != objectid)
3660 /* we found an xattr, assume we've got an acl */
3661 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3662 if (*first_xattr_slot == -1)
3663 *first_xattr_slot = slot;
3664 if (found_key.offset == xattr_access ||
3665 found_key.offset == xattr_default)
3670 * we found a key greater than an xattr key, there can't
3671 * be any acls later on
3673 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3680 * it goes inode, inode backrefs, xattrs, extents,
3681 * so if there are a ton of hard links to an inode there can
3682 * be a lot of backrefs. Don't waste time searching too hard,
3683 * this is just an optimization
3688 /* we hit the end of the leaf before we found an xattr or
3689 * something larger than an xattr. We have to assume the inode
3692 if (*first_xattr_slot == -1)
3693 *first_xattr_slot = slot;
3698 * read an inode from the btree into the in-memory inode
3700 static int btrfs_read_locked_inode(struct inode *inode,
3701 struct btrfs_path *in_path)
3703 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3704 struct btrfs_path *path = in_path;
3705 struct extent_buffer *leaf;
3706 struct btrfs_inode_item *inode_item;
3707 struct btrfs_root *root = BTRFS_I(inode)->root;
3708 struct btrfs_key location;
3713 bool filled = false;
3714 int first_xattr_slot;
3716 ret = btrfs_fill_inode(inode, &rdev);
3721 path = btrfs_alloc_path();
3726 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3728 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3730 if (path != in_path)
3731 btrfs_free_path(path);
3735 leaf = path->nodes[0];
3740 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3741 struct btrfs_inode_item);
3742 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3743 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3744 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3745 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3746 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3748 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3749 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3751 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3752 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3754 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3755 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3757 BTRFS_I(inode)->i_otime.tv_sec =
3758 btrfs_timespec_sec(leaf, &inode_item->otime);
3759 BTRFS_I(inode)->i_otime.tv_nsec =
3760 btrfs_timespec_nsec(leaf, &inode_item->otime);
3762 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3763 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3764 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3766 inode_set_iversion_queried(inode,
3767 btrfs_inode_sequence(leaf, inode_item));
3768 inode->i_generation = BTRFS_I(inode)->generation;
3770 rdev = btrfs_inode_rdev(leaf, inode_item);
3772 BTRFS_I(inode)->index_cnt = (u64)-1;
3773 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3777 * If we were modified in the current generation and evicted from memory
3778 * and then re-read we need to do a full sync since we don't have any
3779 * idea about which extents were modified before we were evicted from
3782 * This is required for both inode re-read from disk and delayed inode
3783 * in delayed_nodes_tree.
3785 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3786 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3787 &BTRFS_I(inode)->runtime_flags);
3790 * We don't persist the id of the transaction where an unlink operation
3791 * against the inode was last made. So here we assume the inode might
3792 * have been evicted, and therefore the exact value of last_unlink_trans
3793 * lost, and set it to last_trans to avoid metadata inconsistencies
3794 * between the inode and its parent if the inode is fsync'ed and the log
3795 * replayed. For example, in the scenario:
3798 * ln mydir/foo mydir/bar
3801 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3802 * xfs_io -c fsync mydir/foo
3804 * mount fs, triggers fsync log replay
3806 * We must make sure that when we fsync our inode foo we also log its
3807 * parent inode, otherwise after log replay the parent still has the
3808 * dentry with the "bar" name but our inode foo has a link count of 1
3809 * and doesn't have an inode ref with the name "bar" anymore.
3811 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3812 * but it guarantees correctness at the expense of occasional full
3813 * transaction commits on fsync if our inode is a directory, or if our
3814 * inode is not a directory, logging its parent unnecessarily.
3816 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3819 if (inode->i_nlink != 1 ||
3820 path->slots[0] >= btrfs_header_nritems(leaf))
3823 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3824 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3827 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3828 if (location.type == BTRFS_INODE_REF_KEY) {
3829 struct btrfs_inode_ref *ref;
3831 ref = (struct btrfs_inode_ref *)ptr;
3832 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3833 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3834 struct btrfs_inode_extref *extref;
3836 extref = (struct btrfs_inode_extref *)ptr;
3837 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3842 * try to precache a NULL acl entry for files that don't have
3843 * any xattrs or acls
3845 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3846 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3847 if (first_xattr_slot != -1) {
3848 path->slots[0] = first_xattr_slot;
3849 ret = btrfs_load_inode_props(inode, path);
3852 "error loading props for ino %llu (root %llu): %d",
3853 btrfs_ino(BTRFS_I(inode)),
3854 root->root_key.objectid, ret);
3856 if (path != in_path)
3857 btrfs_free_path(path);
3860 cache_no_acl(inode);
3862 switch (inode->i_mode & S_IFMT) {
3864 inode->i_mapping->a_ops = &btrfs_aops;
3865 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3866 inode->i_fop = &btrfs_file_operations;
3867 inode->i_op = &btrfs_file_inode_operations;
3870 inode->i_fop = &btrfs_dir_file_operations;
3871 inode->i_op = &btrfs_dir_inode_operations;
3874 inode->i_op = &btrfs_symlink_inode_operations;
3875 inode_nohighmem(inode);
3876 inode->i_mapping->a_ops = &btrfs_aops;
3879 inode->i_op = &btrfs_special_inode_operations;
3880 init_special_inode(inode, inode->i_mode, rdev);
3884 btrfs_sync_inode_flags_to_i_flags(inode);
3889 * given a leaf and an inode, copy the inode fields into the leaf
3891 static void fill_inode_item(struct btrfs_trans_handle *trans,
3892 struct extent_buffer *leaf,
3893 struct btrfs_inode_item *item,
3894 struct inode *inode)
3896 struct btrfs_map_token token;
3898 btrfs_init_map_token(&token, leaf);
3900 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3901 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3902 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3904 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3905 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3907 btrfs_set_token_timespec_sec(leaf, &item->atime,
3908 inode->i_atime.tv_sec, &token);
3909 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3910 inode->i_atime.tv_nsec, &token);
3912 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3913 inode->i_mtime.tv_sec, &token);
3914 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3915 inode->i_mtime.tv_nsec, &token);
3917 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3918 inode->i_ctime.tv_sec, &token);
3919 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3920 inode->i_ctime.tv_nsec, &token);
3922 btrfs_set_token_timespec_sec(leaf, &item->otime,
3923 BTRFS_I(inode)->i_otime.tv_sec, &token);
3924 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3925 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3927 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3929 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3931 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3933 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3934 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3935 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3936 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3940 * copy everything in the in-memory inode into the btree.
3942 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3943 struct btrfs_root *root, struct inode *inode)
3945 struct btrfs_inode_item *inode_item;
3946 struct btrfs_path *path;
3947 struct extent_buffer *leaf;
3950 path = btrfs_alloc_path();
3954 path->leave_spinning = 1;
3955 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3963 leaf = path->nodes[0];
3964 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3965 struct btrfs_inode_item);
3967 fill_inode_item(trans, leaf, inode_item, inode);
3968 btrfs_mark_buffer_dirty(leaf);
3969 btrfs_set_inode_last_trans(trans, inode);
3972 btrfs_free_path(path);
3977 * copy everything in the in-memory inode into the btree.
3979 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3980 struct btrfs_root *root, struct inode *inode)
3982 struct btrfs_fs_info *fs_info = root->fs_info;
3986 * If the inode is a free space inode, we can deadlock during commit
3987 * if we put it into the delayed code.
3989 * The data relocation inode should also be directly updated
3992 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3993 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3994 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3995 btrfs_update_root_times(trans, root);
3997 ret = btrfs_delayed_update_inode(trans, root, inode);
3999 btrfs_set_inode_last_trans(trans, inode);
4003 return btrfs_update_inode_item(trans, root, inode);
4006 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4007 struct btrfs_root *root,
4008 struct inode *inode)
4012 ret = btrfs_update_inode(trans, root, inode);
4014 return btrfs_update_inode_item(trans, root, inode);
4019 * unlink helper that gets used here in inode.c and in the tree logging
4020 * recovery code. It remove a link in a directory with a given name, and
4021 * also drops the back refs in the inode to the directory
4023 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4024 struct btrfs_root *root,
4025 struct btrfs_inode *dir,
4026 struct btrfs_inode *inode,
4027 const char *name, int name_len)
4029 struct btrfs_fs_info *fs_info = root->fs_info;
4030 struct btrfs_path *path;
4032 struct btrfs_dir_item *di;
4034 u64 ino = btrfs_ino(inode);
4035 u64 dir_ino = btrfs_ino(dir);
4037 path = btrfs_alloc_path();
4043 path->leave_spinning = 1;
4044 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4045 name, name_len, -1);
4046 if (IS_ERR_OR_NULL(di)) {
4047 ret = di ? PTR_ERR(di) : -ENOENT;
4050 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4053 btrfs_release_path(path);
4056 * If we don't have dir index, we have to get it by looking up
4057 * the inode ref, since we get the inode ref, remove it directly,
4058 * it is unnecessary to do delayed deletion.
4060 * But if we have dir index, needn't search inode ref to get it.
4061 * Since the inode ref is close to the inode item, it is better
4062 * that we delay to delete it, and just do this deletion when
4063 * we update the inode item.
4065 if (inode->dir_index) {
4066 ret = btrfs_delayed_delete_inode_ref(inode);
4068 index = inode->dir_index;
4073 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4077 "failed to delete reference to %.*s, inode %llu parent %llu",
4078 name_len, name, ino, dir_ino);
4079 btrfs_abort_transaction(trans, ret);
4083 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4085 btrfs_abort_transaction(trans, ret);
4089 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4091 if (ret != 0 && ret != -ENOENT) {
4092 btrfs_abort_transaction(trans, ret);
4096 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4101 btrfs_abort_transaction(trans, ret);
4104 * If we have a pending delayed iput we could end up with the final iput
4105 * being run in btrfs-cleaner context. If we have enough of these built
4106 * up we can end up burning a lot of time in btrfs-cleaner without any
4107 * way to throttle the unlinks. Since we're currently holding a ref on
4108 * the inode we can run the delayed iput here without any issues as the
4109 * final iput won't be done until after we drop the ref we're currently
4112 btrfs_run_delayed_iput(fs_info, inode);
4114 btrfs_free_path(path);
4118 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4119 inode_inc_iversion(&inode->vfs_inode);
4120 inode_inc_iversion(&dir->vfs_inode);
4121 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4122 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4123 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4128 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4129 struct btrfs_root *root,
4130 struct btrfs_inode *dir, struct btrfs_inode *inode,
4131 const char *name, int name_len)
4134 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4136 drop_nlink(&inode->vfs_inode);
4137 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4143 * helper to start transaction for unlink and rmdir.
4145 * unlink and rmdir are special in btrfs, they do not always free space, so
4146 * if we cannot make our reservations the normal way try and see if there is
4147 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4148 * allow the unlink to occur.
4150 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4152 struct btrfs_root *root = BTRFS_I(dir)->root;
4155 * 1 for the possible orphan item
4156 * 1 for the dir item
4157 * 1 for the dir index
4158 * 1 for the inode ref
4161 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4164 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4166 struct btrfs_root *root = BTRFS_I(dir)->root;
4167 struct btrfs_trans_handle *trans;
4168 struct inode *inode = d_inode(dentry);
4171 trans = __unlink_start_trans(dir);
4173 return PTR_ERR(trans);
4175 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4178 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4179 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4180 dentry->d_name.len);
4184 if (inode->i_nlink == 0) {
4185 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4191 btrfs_end_transaction(trans);
4192 btrfs_btree_balance_dirty(root->fs_info);
4196 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4197 struct inode *dir, u64 objectid,
4198 const char *name, int name_len)
4200 struct btrfs_root *root = BTRFS_I(dir)->root;
4201 struct btrfs_path *path;
4202 struct extent_buffer *leaf;
4203 struct btrfs_dir_item *di;
4204 struct btrfs_key key;
4207 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4209 path = btrfs_alloc_path();
4213 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4214 name, name_len, -1);
4215 if (IS_ERR_OR_NULL(di)) {
4216 ret = di ? PTR_ERR(di) : -ENOENT;
4220 leaf = path->nodes[0];
4221 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4222 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4223 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4225 btrfs_abort_transaction(trans, ret);
4228 btrfs_release_path(path);
4230 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4231 dir_ino, &index, name, name_len);
4233 if (ret != -ENOENT) {
4234 btrfs_abort_transaction(trans, ret);
4237 di = btrfs_search_dir_index_item(root, path, dir_ino,
4239 if (IS_ERR_OR_NULL(di)) {
4244 btrfs_abort_transaction(trans, ret);
4248 leaf = path->nodes[0];
4249 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4252 btrfs_release_path(path);
4254 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4256 btrfs_abort_transaction(trans, ret);
4260 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4261 inode_inc_iversion(dir);
4262 dir->i_mtime = dir->i_ctime = current_time(dir);
4263 ret = btrfs_update_inode_fallback(trans, root, dir);
4265 btrfs_abort_transaction(trans, ret);
4267 btrfs_free_path(path);
4272 * Helper to check if the subvolume references other subvolumes or if it's
4275 static noinline int may_destroy_subvol(struct btrfs_root *root)
4277 struct btrfs_fs_info *fs_info = root->fs_info;
4278 struct btrfs_path *path;
4279 struct btrfs_dir_item *di;
4280 struct btrfs_key key;
4284 path = btrfs_alloc_path();
4288 /* Make sure this root isn't set as the default subvol */
4289 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4290 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4291 dir_id, "default", 7, 0);
4292 if (di && !IS_ERR(di)) {
4293 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4294 if (key.objectid == root->root_key.objectid) {
4297 "deleting default subvolume %llu is not allowed",
4301 btrfs_release_path(path);
4304 key.objectid = root->root_key.objectid;
4305 key.type = BTRFS_ROOT_REF_KEY;
4306 key.offset = (u64)-1;
4308 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4314 if (path->slots[0] > 0) {
4316 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4317 if (key.objectid == root->root_key.objectid &&
4318 key.type == BTRFS_ROOT_REF_KEY)
4322 btrfs_free_path(path);
4326 /* Delete all dentries for inodes belonging to the root */
4327 static void btrfs_prune_dentries(struct btrfs_root *root)
4329 struct btrfs_fs_info *fs_info = root->fs_info;
4330 struct rb_node *node;
4331 struct rb_node *prev;
4332 struct btrfs_inode *entry;
4333 struct inode *inode;
4336 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4337 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4339 spin_lock(&root->inode_lock);
4341 node = root->inode_tree.rb_node;
4345 entry = rb_entry(node, struct btrfs_inode, rb_node);
4347 if (objectid < btrfs_ino(entry))
4348 node = node->rb_left;
4349 else if (objectid > btrfs_ino(entry))
4350 node = node->rb_right;
4356 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4357 if (objectid <= btrfs_ino(entry)) {
4361 prev = rb_next(prev);
4365 entry = rb_entry(node, struct btrfs_inode, rb_node);
4366 objectid = btrfs_ino(entry) + 1;
4367 inode = igrab(&entry->vfs_inode);
4369 spin_unlock(&root->inode_lock);
4370 if (atomic_read(&inode->i_count) > 1)
4371 d_prune_aliases(inode);
4373 * btrfs_drop_inode will have it removed from the inode
4374 * cache when its usage count hits zero.
4378 spin_lock(&root->inode_lock);
4382 if (cond_resched_lock(&root->inode_lock))
4385 node = rb_next(node);
4387 spin_unlock(&root->inode_lock);
4390 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4392 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4393 struct btrfs_root *root = BTRFS_I(dir)->root;
4394 struct inode *inode = d_inode(dentry);
4395 struct btrfs_root *dest = BTRFS_I(inode)->root;
4396 struct btrfs_trans_handle *trans;
4397 struct btrfs_block_rsv block_rsv;
4403 * Don't allow to delete a subvolume with send in progress. This is
4404 * inside the inode lock so the error handling that has to drop the bit
4405 * again is not run concurrently.
4407 spin_lock(&dest->root_item_lock);
4408 if (dest->send_in_progress) {
4409 spin_unlock(&dest->root_item_lock);
4411 "attempt to delete subvolume %llu during send",
4412 dest->root_key.objectid);
4415 root_flags = btrfs_root_flags(&dest->root_item);
4416 btrfs_set_root_flags(&dest->root_item,
4417 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4418 spin_unlock(&dest->root_item_lock);
4420 down_write(&fs_info->subvol_sem);
4422 err = may_destroy_subvol(dest);
4426 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4428 * One for dir inode,
4429 * two for dir entries,
4430 * two for root ref/backref.
4432 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4436 trans = btrfs_start_transaction(root, 0);
4437 if (IS_ERR(trans)) {
4438 err = PTR_ERR(trans);
4441 trans->block_rsv = &block_rsv;
4442 trans->bytes_reserved = block_rsv.size;
4444 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4446 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4447 dentry->d_name.name, dentry->d_name.len);
4450 btrfs_abort_transaction(trans, ret);
4454 btrfs_record_root_in_trans(trans, dest);
4456 memset(&dest->root_item.drop_progress, 0,
4457 sizeof(dest->root_item.drop_progress));
4458 dest->root_item.drop_level = 0;
4459 btrfs_set_root_refs(&dest->root_item, 0);
4461 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4462 ret = btrfs_insert_orphan_item(trans,
4464 dest->root_key.objectid);
4466 btrfs_abort_transaction(trans, ret);
4472 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4473 BTRFS_UUID_KEY_SUBVOL,
4474 dest->root_key.objectid);
4475 if (ret && ret != -ENOENT) {
4476 btrfs_abort_transaction(trans, ret);
4480 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4481 ret = btrfs_uuid_tree_remove(trans,
4482 dest->root_item.received_uuid,
4483 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4484 dest->root_key.objectid);
4485 if (ret && ret != -ENOENT) {
4486 btrfs_abort_transaction(trans, ret);
4493 trans->block_rsv = NULL;
4494 trans->bytes_reserved = 0;
4495 ret = btrfs_end_transaction(trans);
4498 inode->i_flags |= S_DEAD;
4500 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4502 up_write(&fs_info->subvol_sem);
4504 spin_lock(&dest->root_item_lock);
4505 root_flags = btrfs_root_flags(&dest->root_item);
4506 btrfs_set_root_flags(&dest->root_item,
4507 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4508 spin_unlock(&dest->root_item_lock);
4510 d_invalidate(dentry);
4511 btrfs_prune_dentries(dest);
4512 ASSERT(dest->send_in_progress == 0);
4515 if (dest->ino_cache_inode) {
4516 iput(dest->ino_cache_inode);
4517 dest->ino_cache_inode = NULL;
4524 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4526 struct inode *inode = d_inode(dentry);
4528 struct btrfs_root *root = BTRFS_I(dir)->root;
4529 struct btrfs_trans_handle *trans;
4530 u64 last_unlink_trans;
4532 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4534 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4535 return btrfs_delete_subvolume(dir, dentry);
4537 trans = __unlink_start_trans(dir);
4539 return PTR_ERR(trans);
4541 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4542 err = btrfs_unlink_subvol(trans, dir,
4543 BTRFS_I(inode)->location.objectid,
4544 dentry->d_name.name,
4545 dentry->d_name.len);
4549 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4553 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4555 /* now the directory is empty */
4556 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4557 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4558 dentry->d_name.len);
4560 btrfs_i_size_write(BTRFS_I(inode), 0);
4562 * Propagate the last_unlink_trans value of the deleted dir to
4563 * its parent directory. This is to prevent an unrecoverable
4564 * log tree in the case we do something like this:
4566 * 2) create snapshot under dir foo
4567 * 3) delete the snapshot
4570 * 6) fsync foo or some file inside foo
4572 if (last_unlink_trans >= trans->transid)
4573 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4576 btrfs_end_transaction(trans);
4577 btrfs_btree_balance_dirty(root->fs_info);
4583 * Return this if we need to call truncate_block for the last bit of the
4586 #define NEED_TRUNCATE_BLOCK 1
4589 * this can truncate away extent items, csum items and directory items.
4590 * It starts at a high offset and removes keys until it can't find
4591 * any higher than new_size
4593 * csum items that cross the new i_size are truncated to the new size
4596 * min_type is the minimum key type to truncate down to. If set to 0, this
4597 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4599 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4600 struct btrfs_root *root,
4601 struct inode *inode,
4602 u64 new_size, u32 min_type)
4604 struct btrfs_fs_info *fs_info = root->fs_info;
4605 struct btrfs_path *path;
4606 struct extent_buffer *leaf;
4607 struct btrfs_file_extent_item *fi;
4608 struct btrfs_key key;
4609 struct btrfs_key found_key;
4610 u64 extent_start = 0;
4611 u64 extent_num_bytes = 0;
4612 u64 extent_offset = 0;
4614 u64 last_size = new_size;
4615 u32 found_type = (u8)-1;
4618 int pending_del_nr = 0;
4619 int pending_del_slot = 0;
4620 int extent_type = -1;
4622 u64 ino = btrfs_ino(BTRFS_I(inode));
4623 u64 bytes_deleted = 0;
4624 bool be_nice = false;
4625 bool should_throttle = false;
4627 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4630 * for non-free space inodes and ref cows, we want to back off from
4633 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4634 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4637 path = btrfs_alloc_path();
4640 path->reada = READA_BACK;
4643 * We want to drop from the next block forward in case this new size is
4644 * not block aligned since we will be keeping the last block of the
4645 * extent just the way it is.
4647 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4648 root == fs_info->tree_root)
4649 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4650 fs_info->sectorsize),
4654 * This function is also used to drop the items in the log tree before
4655 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4656 * it is used to drop the logged items. So we shouldn't kill the delayed
4659 if (min_type == 0 && root == BTRFS_I(inode)->root)
4660 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4663 key.offset = (u64)-1;
4668 * with a 16K leaf size and 128MB extents, you can actually queue
4669 * up a huge file in a single leaf. Most of the time that
4670 * bytes_deleted is > 0, it will be huge by the time we get here
4672 if (be_nice && bytes_deleted > SZ_32M &&
4673 btrfs_should_end_transaction(trans)) {
4678 path->leave_spinning = 1;
4679 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4685 /* there are no items in the tree for us to truncate, we're
4688 if (path->slots[0] == 0)
4695 leaf = path->nodes[0];
4696 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4697 found_type = found_key.type;
4699 if (found_key.objectid != ino)
4702 if (found_type < min_type)
4705 item_end = found_key.offset;
4706 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4707 fi = btrfs_item_ptr(leaf, path->slots[0],
4708 struct btrfs_file_extent_item);
4709 extent_type = btrfs_file_extent_type(leaf, fi);
4710 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4712 btrfs_file_extent_num_bytes(leaf, fi);
4714 trace_btrfs_truncate_show_fi_regular(
4715 BTRFS_I(inode), leaf, fi,
4717 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4718 item_end += btrfs_file_extent_ram_bytes(leaf,
4721 trace_btrfs_truncate_show_fi_inline(
4722 BTRFS_I(inode), leaf, fi, path->slots[0],
4727 if (found_type > min_type) {
4730 if (item_end < new_size)
4732 if (found_key.offset >= new_size)
4738 /* FIXME, shrink the extent if the ref count is only 1 */
4739 if (found_type != BTRFS_EXTENT_DATA_KEY)
4742 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4744 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4746 u64 orig_num_bytes =
4747 btrfs_file_extent_num_bytes(leaf, fi);
4748 extent_num_bytes = ALIGN(new_size -
4750 fs_info->sectorsize);
4751 btrfs_set_file_extent_num_bytes(leaf, fi,
4753 num_dec = (orig_num_bytes -
4755 if (test_bit(BTRFS_ROOT_REF_COWS,
4758 inode_sub_bytes(inode, num_dec);
4759 btrfs_mark_buffer_dirty(leaf);
4762 btrfs_file_extent_disk_num_bytes(leaf,
4764 extent_offset = found_key.offset -
4765 btrfs_file_extent_offset(leaf, fi);
4767 /* FIXME blocksize != 4096 */
4768 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4769 if (extent_start != 0) {
4771 if (test_bit(BTRFS_ROOT_REF_COWS,
4773 inode_sub_bytes(inode, num_dec);
4776 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4778 * we can't truncate inline items that have had
4782 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4783 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4784 btrfs_file_extent_compression(leaf, fi) == 0) {
4785 u32 size = (u32)(new_size - found_key.offset);
4787 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4788 size = btrfs_file_extent_calc_inline_size(size);
4789 btrfs_truncate_item(path, size, 1);
4790 } else if (!del_item) {
4792 * We have to bail so the last_size is set to
4793 * just before this extent.
4795 ret = NEED_TRUNCATE_BLOCK;
4799 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4800 inode_sub_bytes(inode, item_end + 1 - new_size);
4804 last_size = found_key.offset;
4806 last_size = new_size;
4808 if (!pending_del_nr) {
4809 /* no pending yet, add ourselves */
4810 pending_del_slot = path->slots[0];
4812 } else if (pending_del_nr &&
4813 path->slots[0] + 1 == pending_del_slot) {
4814 /* hop on the pending chunk */
4816 pending_del_slot = path->slots[0];
4823 should_throttle = false;
4826 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4827 root == fs_info->tree_root)) {
4828 struct btrfs_ref ref = { 0 };
4830 btrfs_set_path_blocking(path);
4831 bytes_deleted += extent_num_bytes;
4833 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4834 extent_start, extent_num_bytes, 0);
4835 ref.real_root = root->root_key.objectid;
4836 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4837 ino, extent_offset);
4838 ret = btrfs_free_extent(trans, &ref);
4840 btrfs_abort_transaction(trans, ret);
4844 if (btrfs_should_throttle_delayed_refs(trans))
4845 should_throttle = true;
4849 if (found_type == BTRFS_INODE_ITEM_KEY)
4852 if (path->slots[0] == 0 ||
4853 path->slots[0] != pending_del_slot ||
4855 if (pending_del_nr) {
4856 ret = btrfs_del_items(trans, root, path,
4860 btrfs_abort_transaction(trans, ret);
4865 btrfs_release_path(path);
4868 * We can generate a lot of delayed refs, so we need to
4869 * throttle every once and a while and make sure we're
4870 * adding enough space to keep up with the work we are
4871 * generating. Since we hold a transaction here we
4872 * can't flush, and we don't want to FLUSH_LIMIT because
4873 * we could have generated too many delayed refs to
4874 * actually allocate, so just bail if we're short and
4875 * let the normal reservation dance happen higher up.
4877 if (should_throttle) {
4878 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4879 BTRFS_RESERVE_NO_FLUSH);
4891 if (ret >= 0 && pending_del_nr) {
4894 err = btrfs_del_items(trans, root, path, pending_del_slot,
4897 btrfs_abort_transaction(trans, err);
4901 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4902 ASSERT(last_size >= new_size);
4903 if (!ret && last_size > new_size)
4904 last_size = new_size;
4905 btrfs_ordered_update_i_size(inode, last_size, NULL);
4908 btrfs_free_path(path);
4913 * btrfs_truncate_block - read, zero a chunk and write a block
4914 * @inode - inode that we're zeroing
4915 * @from - the offset to start zeroing
4916 * @len - the length to zero, 0 to zero the entire range respective to the
4918 * @front - zero up to the offset instead of from the offset on
4920 * This will find the block for the "from" offset and cow the block and zero the
4921 * part we want to zero. This is used with truncate and hole punching.
4923 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4926 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4927 struct address_space *mapping = inode->i_mapping;
4928 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4929 struct btrfs_ordered_extent *ordered;
4930 struct extent_state *cached_state = NULL;
4931 struct extent_changeset *data_reserved = NULL;
4933 u32 blocksize = fs_info->sectorsize;
4934 pgoff_t index = from >> PAGE_SHIFT;
4935 unsigned offset = from & (blocksize - 1);
4937 gfp_t mask = btrfs_alloc_write_mask(mapping);
4942 if (IS_ALIGNED(offset, blocksize) &&
4943 (!len || IS_ALIGNED(len, blocksize)))
4946 block_start = round_down(from, blocksize);
4947 block_end = block_start + blocksize - 1;
4949 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4950 block_start, blocksize);
4955 page = find_or_create_page(mapping, index, mask);
4957 btrfs_delalloc_release_space(inode, data_reserved,
4958 block_start, blocksize, true);
4959 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4964 if (!PageUptodate(page)) {
4965 ret = btrfs_readpage(NULL, page);
4967 if (page->mapping != mapping) {
4972 if (!PageUptodate(page)) {
4977 wait_on_page_writeback(page);
4979 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4980 set_page_extent_mapped(page);
4982 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4984 unlock_extent_cached(io_tree, block_start, block_end,
4988 btrfs_start_ordered_extent(inode, ordered, 1);
4989 btrfs_put_ordered_extent(ordered);
4993 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4994 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4995 0, 0, &cached_state);
4997 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5000 unlock_extent_cached(io_tree, block_start, block_end,
5005 if (offset != blocksize) {
5007 len = blocksize - offset;
5010 memset(kaddr + (block_start - page_offset(page)),
5013 memset(kaddr + (block_start - page_offset(page)) + offset,
5015 flush_dcache_page(page);
5018 ClearPageChecked(page);
5019 set_page_dirty(page);
5020 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
5024 btrfs_delalloc_release_space(inode, data_reserved, block_start,
5026 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
5030 extent_changeset_free(data_reserved);
5034 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
5035 u64 offset, u64 len)
5037 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5038 struct btrfs_trans_handle *trans;
5042 * Still need to make sure the inode looks like it's been updated so
5043 * that any holes get logged if we fsync.
5045 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
5046 BTRFS_I(inode)->last_trans = fs_info->generation;
5047 BTRFS_I(inode)->last_sub_trans = root->log_transid;
5048 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
5053 * 1 - for the one we're dropping
5054 * 1 - for the one we're adding
5055 * 1 - for updating the inode.
5057 trans = btrfs_start_transaction(root, 3);
5059 return PTR_ERR(trans);
5061 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5063 btrfs_abort_transaction(trans, ret);
5064 btrfs_end_transaction(trans);
5068 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5069 offset, 0, 0, len, 0, len, 0, 0, 0);
5071 btrfs_abort_transaction(trans, ret);
5073 btrfs_update_inode(trans, root, inode);
5074 btrfs_end_transaction(trans);
5079 * This function puts in dummy file extents for the area we're creating a hole
5080 * for. So if we are truncating this file to a larger size we need to insert
5081 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5082 * the range between oldsize and size
5084 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5086 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5087 struct btrfs_root *root = BTRFS_I(inode)->root;
5088 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5089 struct extent_map *em = NULL;
5090 struct extent_state *cached_state = NULL;
5091 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5092 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5093 u64 block_end = ALIGN(size, fs_info->sectorsize);
5100 * If our size started in the middle of a block we need to zero out the
5101 * rest of the block before we expand the i_size, otherwise we could
5102 * expose stale data.
5104 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5108 if (size <= hole_start)
5111 btrfs_lock_and_flush_ordered_range(io_tree, BTRFS_I(inode), hole_start,
5112 block_end - 1, &cached_state);
5113 cur_offset = hole_start;
5115 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5116 block_end - cur_offset, 0);
5122 last_byte = min(extent_map_end(em), block_end);
5123 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5124 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5125 struct extent_map *hole_em;
5126 hole_size = last_byte - cur_offset;
5128 err = maybe_insert_hole(root, inode, cur_offset,
5132 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5133 cur_offset + hole_size - 1, 0);
5134 hole_em = alloc_extent_map();
5136 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5137 &BTRFS_I(inode)->runtime_flags);
5140 hole_em->start = cur_offset;
5141 hole_em->len = hole_size;
5142 hole_em->orig_start = cur_offset;
5144 hole_em->block_start = EXTENT_MAP_HOLE;
5145 hole_em->block_len = 0;
5146 hole_em->orig_block_len = 0;
5147 hole_em->ram_bytes = hole_size;
5148 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5149 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5150 hole_em->generation = fs_info->generation;
5153 write_lock(&em_tree->lock);
5154 err = add_extent_mapping(em_tree, hole_em, 1);
5155 write_unlock(&em_tree->lock);
5158 btrfs_drop_extent_cache(BTRFS_I(inode),
5163 free_extent_map(hole_em);
5166 free_extent_map(em);
5168 cur_offset = last_byte;
5169 if (cur_offset >= block_end)
5172 free_extent_map(em);
5173 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5177 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5179 struct btrfs_root *root = BTRFS_I(inode)->root;
5180 struct btrfs_trans_handle *trans;
5181 loff_t oldsize = i_size_read(inode);
5182 loff_t newsize = attr->ia_size;
5183 int mask = attr->ia_valid;
5187 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5188 * special case where we need to update the times despite not having
5189 * these flags set. For all other operations the VFS set these flags
5190 * explicitly if it wants a timestamp update.
5192 if (newsize != oldsize) {
5193 inode_inc_iversion(inode);
5194 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5195 inode->i_ctime = inode->i_mtime =
5196 current_time(inode);
5199 if (newsize > oldsize) {
5201 * Don't do an expanding truncate while snapshotting is ongoing.
5202 * This is to ensure the snapshot captures a fully consistent
5203 * state of this file - if the snapshot captures this expanding
5204 * truncation, it must capture all writes that happened before
5207 btrfs_wait_for_snapshot_creation(root);
5208 ret = btrfs_cont_expand(inode, oldsize, newsize);
5210 btrfs_end_write_no_snapshotting(root);
5214 trans = btrfs_start_transaction(root, 1);
5215 if (IS_ERR(trans)) {
5216 btrfs_end_write_no_snapshotting(root);
5217 return PTR_ERR(trans);
5220 i_size_write(inode, newsize);
5221 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5222 pagecache_isize_extended(inode, oldsize, newsize);
5223 ret = btrfs_update_inode(trans, root, inode);
5224 btrfs_end_write_no_snapshotting(root);
5225 btrfs_end_transaction(trans);
5229 * We're truncating a file that used to have good data down to
5230 * zero. Make sure it gets into the ordered flush list so that
5231 * any new writes get down to disk quickly.
5234 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5235 &BTRFS_I(inode)->runtime_flags);
5237 truncate_setsize(inode, newsize);
5239 /* Disable nonlocked read DIO to avoid the endless truncate */
5240 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5241 inode_dio_wait(inode);
5242 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5244 ret = btrfs_truncate(inode, newsize == oldsize);
5245 if (ret && inode->i_nlink) {
5249 * Truncate failed, so fix up the in-memory size. We
5250 * adjusted disk_i_size down as we removed extents, so
5251 * wait for disk_i_size to be stable and then update the
5252 * in-memory size to match.
5254 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5257 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5264 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5266 struct inode *inode = d_inode(dentry);
5267 struct btrfs_root *root = BTRFS_I(inode)->root;
5270 if (btrfs_root_readonly(root))
5273 err = setattr_prepare(dentry, attr);
5277 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5278 err = btrfs_setsize(inode, attr);
5283 if (attr->ia_valid) {
5284 setattr_copy(inode, attr);
5285 inode_inc_iversion(inode);
5286 err = btrfs_dirty_inode(inode);
5288 if (!err && attr->ia_valid & ATTR_MODE)
5289 err = posix_acl_chmod(inode, inode->i_mode);
5296 * While truncating the inode pages during eviction, we get the VFS calling
5297 * btrfs_invalidatepage() against each page of the inode. This is slow because
5298 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5299 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5300 * extent_state structures over and over, wasting lots of time.
5302 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5303 * those expensive operations on a per page basis and do only the ordered io
5304 * finishing, while we release here the extent_map and extent_state structures,
5305 * without the excessive merging and splitting.
5307 static void evict_inode_truncate_pages(struct inode *inode)
5309 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5310 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5311 struct rb_node *node;
5313 ASSERT(inode->i_state & I_FREEING);
5314 truncate_inode_pages_final(&inode->i_data);
5316 write_lock(&map_tree->lock);
5317 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5318 struct extent_map *em;
5320 node = rb_first_cached(&map_tree->map);
5321 em = rb_entry(node, struct extent_map, rb_node);
5322 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5323 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5324 remove_extent_mapping(map_tree, em);
5325 free_extent_map(em);
5326 if (need_resched()) {
5327 write_unlock(&map_tree->lock);
5329 write_lock(&map_tree->lock);
5332 write_unlock(&map_tree->lock);
5335 * Keep looping until we have no more ranges in the io tree.
5336 * We can have ongoing bios started by readpages (called from readahead)
5337 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5338 * still in progress (unlocked the pages in the bio but did not yet
5339 * unlocked the ranges in the io tree). Therefore this means some
5340 * ranges can still be locked and eviction started because before
5341 * submitting those bios, which are executed by a separate task (work
5342 * queue kthread), inode references (inode->i_count) were not taken
5343 * (which would be dropped in the end io callback of each bio).
5344 * Therefore here we effectively end up waiting for those bios and
5345 * anyone else holding locked ranges without having bumped the inode's
5346 * reference count - if we don't do it, when they access the inode's
5347 * io_tree to unlock a range it may be too late, leading to an
5348 * use-after-free issue.
5350 spin_lock(&io_tree->lock);
5351 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5352 struct extent_state *state;
5353 struct extent_state *cached_state = NULL;
5356 unsigned state_flags;
5358 node = rb_first(&io_tree->state);
5359 state = rb_entry(node, struct extent_state, rb_node);
5360 start = state->start;
5362 state_flags = state->state;
5363 spin_unlock(&io_tree->lock);
5365 lock_extent_bits(io_tree, start, end, &cached_state);
5368 * If still has DELALLOC flag, the extent didn't reach disk,
5369 * and its reserved space won't be freed by delayed_ref.
5370 * So we need to free its reserved space here.
5371 * (Refer to comment in btrfs_invalidatepage, case 2)
5373 * Note, end is the bytenr of last byte, so we need + 1 here.
5375 if (state_flags & EXTENT_DELALLOC)
5376 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5378 clear_extent_bit(io_tree, start, end,
5379 EXTENT_LOCKED | EXTENT_DELALLOC |
5380 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5384 spin_lock(&io_tree->lock);
5386 spin_unlock(&io_tree->lock);
5389 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5390 struct btrfs_block_rsv *rsv)
5392 struct btrfs_fs_info *fs_info = root->fs_info;
5393 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5394 struct btrfs_trans_handle *trans;
5395 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5399 * Eviction should be taking place at some place safe because of our
5400 * delayed iputs. However the normal flushing code will run delayed
5401 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5403 * We reserve the delayed_refs_extra here again because we can't use
5404 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5405 * above. We reserve our extra bit here because we generate a ton of
5406 * delayed refs activity by truncating.
5408 * If we cannot make our reservation we'll attempt to steal from the
5409 * global reserve, because we really want to be able to free up space.
5411 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5412 BTRFS_RESERVE_FLUSH_EVICT);
5415 * Try to steal from the global reserve if there is space for
5418 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5419 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5421 "could not allocate space for delete; will truncate on mount");
5422 return ERR_PTR(-ENOSPC);
5424 delayed_refs_extra = 0;
5427 trans = btrfs_join_transaction(root);
5431 if (delayed_refs_extra) {
5432 trans->block_rsv = &fs_info->trans_block_rsv;
5433 trans->bytes_reserved = delayed_refs_extra;
5434 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5435 delayed_refs_extra, 1);
5440 void btrfs_evict_inode(struct inode *inode)
5442 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5443 struct btrfs_trans_handle *trans;
5444 struct btrfs_root *root = BTRFS_I(inode)->root;
5445 struct btrfs_block_rsv *rsv;
5448 trace_btrfs_inode_evict(inode);
5455 evict_inode_truncate_pages(inode);
5457 if (inode->i_nlink &&
5458 ((btrfs_root_refs(&root->root_item) != 0 &&
5459 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5460 btrfs_is_free_space_inode(BTRFS_I(inode))))
5463 if (is_bad_inode(inode))
5466 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5468 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5471 if (inode->i_nlink > 0) {
5472 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5473 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5477 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5481 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5484 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5487 btrfs_i_size_write(BTRFS_I(inode), 0);
5490 trans = evict_refill_and_join(root, rsv);
5494 trans->block_rsv = rsv;
5496 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5497 trans->block_rsv = &fs_info->trans_block_rsv;
5498 btrfs_end_transaction(trans);
5499 btrfs_btree_balance_dirty(fs_info);
5500 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5507 * Errors here aren't a big deal, it just means we leave orphan items in
5508 * the tree. They will be cleaned up on the next mount. If the inode
5509 * number gets reused, cleanup deletes the orphan item without doing
5510 * anything, and unlink reuses the existing orphan item.
5512 * If it turns out that we are dropping too many of these, we might want
5513 * to add a mechanism for retrying these after a commit.
5515 trans = evict_refill_and_join(root, rsv);
5516 if (!IS_ERR(trans)) {
5517 trans->block_rsv = rsv;
5518 btrfs_orphan_del(trans, BTRFS_I(inode));
5519 trans->block_rsv = &fs_info->trans_block_rsv;
5520 btrfs_end_transaction(trans);
5523 if (!(root == fs_info->tree_root ||
5524 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5525 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5528 btrfs_free_block_rsv(fs_info, rsv);
5531 * If we didn't successfully delete, the orphan item will still be in
5532 * the tree and we'll retry on the next mount. Again, we might also want
5533 * to retry these periodically in the future.
5535 btrfs_remove_delayed_node(BTRFS_I(inode));
5540 * Return the key found in the dir entry in the location pointer, fill @type
5541 * with BTRFS_FT_*, and return 0.
5543 * If no dir entries were found, returns -ENOENT.
5544 * If found a corrupted location in dir entry, returns -EUCLEAN.
5546 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5547 struct btrfs_key *location, u8 *type)
5549 const char *name = dentry->d_name.name;
5550 int namelen = dentry->d_name.len;
5551 struct btrfs_dir_item *di;
5552 struct btrfs_path *path;
5553 struct btrfs_root *root = BTRFS_I(dir)->root;
5556 path = btrfs_alloc_path();
5560 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5562 if (IS_ERR_OR_NULL(di)) {
5563 ret = di ? PTR_ERR(di) : -ENOENT;
5567 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5568 if (location->type != BTRFS_INODE_ITEM_KEY &&
5569 location->type != BTRFS_ROOT_ITEM_KEY) {
5571 btrfs_warn(root->fs_info,
5572 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5573 __func__, name, btrfs_ino(BTRFS_I(dir)),
5574 location->objectid, location->type, location->offset);
5577 *type = btrfs_dir_type(path->nodes[0], di);
5579 btrfs_free_path(path);
5584 * when we hit a tree root in a directory, the btrfs part of the inode
5585 * needs to be changed to reflect the root directory of the tree root. This
5586 * is kind of like crossing a mount point.
5588 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5590 struct dentry *dentry,
5591 struct btrfs_key *location,
5592 struct btrfs_root **sub_root)
5594 struct btrfs_path *path;
5595 struct btrfs_root *new_root;
5596 struct btrfs_root_ref *ref;
5597 struct extent_buffer *leaf;
5598 struct btrfs_key key;
5602 path = btrfs_alloc_path();
5609 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5610 key.type = BTRFS_ROOT_REF_KEY;
5611 key.offset = location->objectid;
5613 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5620 leaf = path->nodes[0];
5621 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5622 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5623 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5626 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5627 (unsigned long)(ref + 1),
5628 dentry->d_name.len);
5632 btrfs_release_path(path);
5634 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5635 if (IS_ERR(new_root)) {
5636 err = PTR_ERR(new_root);
5640 *sub_root = new_root;
5641 location->objectid = btrfs_root_dirid(&new_root->root_item);
5642 location->type = BTRFS_INODE_ITEM_KEY;
5643 location->offset = 0;
5646 btrfs_free_path(path);
5650 static void inode_tree_add(struct inode *inode)
5652 struct btrfs_root *root = BTRFS_I(inode)->root;
5653 struct btrfs_inode *entry;
5655 struct rb_node *parent;
5656 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5657 u64 ino = btrfs_ino(BTRFS_I(inode));
5659 if (inode_unhashed(inode))
5662 spin_lock(&root->inode_lock);
5663 p = &root->inode_tree.rb_node;
5666 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5668 if (ino < btrfs_ino(entry))
5669 p = &parent->rb_left;
5670 else if (ino > btrfs_ino(entry))
5671 p = &parent->rb_right;
5673 WARN_ON(!(entry->vfs_inode.i_state &
5674 (I_WILL_FREE | I_FREEING)));
5675 rb_replace_node(parent, new, &root->inode_tree);
5676 RB_CLEAR_NODE(parent);
5677 spin_unlock(&root->inode_lock);
5681 rb_link_node(new, parent, p);
5682 rb_insert_color(new, &root->inode_tree);
5683 spin_unlock(&root->inode_lock);
5686 static void inode_tree_del(struct inode *inode)
5688 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5689 struct btrfs_root *root = BTRFS_I(inode)->root;
5692 spin_lock(&root->inode_lock);
5693 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5694 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5695 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5696 empty = RB_EMPTY_ROOT(&root->inode_tree);
5698 spin_unlock(&root->inode_lock);
5700 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5701 synchronize_srcu(&fs_info->subvol_srcu);
5702 spin_lock(&root->inode_lock);
5703 empty = RB_EMPTY_ROOT(&root->inode_tree);
5704 spin_unlock(&root->inode_lock);
5706 btrfs_add_dead_root(root);
5711 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5713 struct btrfs_iget_args *args = p;
5714 inode->i_ino = args->location->objectid;
5715 memcpy(&BTRFS_I(inode)->location, args->location,
5716 sizeof(*args->location));
5717 BTRFS_I(inode)->root = args->root;
5721 static int btrfs_find_actor(struct inode *inode, void *opaque)
5723 struct btrfs_iget_args *args = opaque;
5724 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5725 args->root == BTRFS_I(inode)->root;
5728 static struct inode *btrfs_iget_locked(struct super_block *s,
5729 struct btrfs_key *location,
5730 struct btrfs_root *root)
5732 struct inode *inode;
5733 struct btrfs_iget_args args;
5734 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5736 args.location = location;
5739 inode = iget5_locked(s, hashval, btrfs_find_actor,
5740 btrfs_init_locked_inode,
5745 /* Get an inode object given its location and corresponding root.
5746 * Returns in *is_new if the inode was read from disk
5748 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5749 struct btrfs_root *root, int *new,
5750 struct btrfs_path *path)
5752 struct inode *inode;
5754 inode = btrfs_iget_locked(s, location, root);
5756 return ERR_PTR(-ENOMEM);
5758 if (inode->i_state & I_NEW) {
5761 ret = btrfs_read_locked_inode(inode, path);
5763 inode_tree_add(inode);
5764 unlock_new_inode(inode);
5770 * ret > 0 can come from btrfs_search_slot called by
5771 * btrfs_read_locked_inode, this means the inode item
5776 inode = ERR_PTR(ret);
5783 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5784 struct btrfs_root *root, int *new)
5786 return btrfs_iget_path(s, location, root, new, NULL);
5789 static struct inode *new_simple_dir(struct super_block *s,
5790 struct btrfs_key *key,
5791 struct btrfs_root *root)
5793 struct inode *inode = new_inode(s);
5796 return ERR_PTR(-ENOMEM);
5798 BTRFS_I(inode)->root = root;
5799 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5800 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5802 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5803 inode->i_op = &btrfs_dir_ro_inode_operations;
5804 inode->i_opflags &= ~IOP_XATTR;
5805 inode->i_fop = &simple_dir_operations;
5806 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5807 inode->i_mtime = current_time(inode);
5808 inode->i_atime = inode->i_mtime;
5809 inode->i_ctime = inode->i_mtime;
5810 BTRFS_I(inode)->i_otime = inode->i_mtime;
5815 static inline u8 btrfs_inode_type(struct inode *inode)
5818 * Compile-time asserts that generic FT_* types still match
5821 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5822 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5823 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5824 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5825 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5826 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5827 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5828 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5830 return fs_umode_to_ftype(inode->i_mode);
5833 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5835 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5836 struct inode *inode;
5837 struct btrfs_root *root = BTRFS_I(dir)->root;
5838 struct btrfs_root *sub_root = root;
5839 struct btrfs_key location;
5844 if (dentry->d_name.len > BTRFS_NAME_LEN)
5845 return ERR_PTR(-ENAMETOOLONG);
5847 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5849 return ERR_PTR(ret);
5851 if (location.type == BTRFS_INODE_ITEM_KEY) {
5852 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5856 /* Do extra check against inode mode with di_type */
5857 if (btrfs_inode_type(inode) != di_type) {
5859 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5860 inode->i_mode, btrfs_inode_type(inode),
5863 return ERR_PTR(-EUCLEAN);
5868 index = srcu_read_lock(&fs_info->subvol_srcu);
5869 ret = fixup_tree_root_location(fs_info, dir, dentry,
5870 &location, &sub_root);
5873 inode = ERR_PTR(ret);
5875 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5877 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5879 srcu_read_unlock(&fs_info->subvol_srcu, index);
5881 if (!IS_ERR(inode) && root != sub_root) {
5882 down_read(&fs_info->cleanup_work_sem);
5883 if (!sb_rdonly(inode->i_sb))
5884 ret = btrfs_orphan_cleanup(sub_root);
5885 up_read(&fs_info->cleanup_work_sem);
5888 inode = ERR_PTR(ret);
5895 static int btrfs_dentry_delete(const struct dentry *dentry)
5897 struct btrfs_root *root;
5898 struct inode *inode = d_inode(dentry);
5900 if (!inode && !IS_ROOT(dentry))
5901 inode = d_inode(dentry->d_parent);
5904 root = BTRFS_I(inode)->root;
5905 if (btrfs_root_refs(&root->root_item) == 0)
5908 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5914 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5917 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5919 if (inode == ERR_PTR(-ENOENT))
5921 return d_splice_alias(inode, dentry);
5925 * All this infrastructure exists because dir_emit can fault, and we are holding
5926 * the tree lock when doing readdir. For now just allocate a buffer and copy
5927 * our information into that, and then dir_emit from the buffer. This is
5928 * similar to what NFS does, only we don't keep the buffer around in pagecache
5929 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5930 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5933 static int btrfs_opendir(struct inode *inode, struct file *file)
5935 struct btrfs_file_private *private;
5937 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5940 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5941 if (!private->filldir_buf) {
5945 file->private_data = private;
5956 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5959 struct dir_entry *entry = addr;
5960 char *name = (char *)(entry + 1);
5962 ctx->pos = get_unaligned(&entry->offset);
5963 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5964 get_unaligned(&entry->ino),
5965 get_unaligned(&entry->type)))
5967 addr += sizeof(struct dir_entry) +
5968 get_unaligned(&entry->name_len);
5974 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5976 struct inode *inode = file_inode(file);
5977 struct btrfs_root *root = BTRFS_I(inode)->root;
5978 struct btrfs_file_private *private = file->private_data;
5979 struct btrfs_dir_item *di;
5980 struct btrfs_key key;
5981 struct btrfs_key found_key;
5982 struct btrfs_path *path;
5984 struct list_head ins_list;
5985 struct list_head del_list;
5987 struct extent_buffer *leaf;
5994 struct btrfs_key location;
5996 if (!dir_emit_dots(file, ctx))
5999 path = btrfs_alloc_path();
6003 addr = private->filldir_buf;
6004 path->reada = READA_FORWARD;
6006 INIT_LIST_HEAD(&ins_list);
6007 INIT_LIST_HEAD(&del_list);
6008 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6011 key.type = BTRFS_DIR_INDEX_KEY;
6012 key.offset = ctx->pos;
6013 key.objectid = btrfs_ino(BTRFS_I(inode));
6015 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6020 struct dir_entry *entry;
6022 leaf = path->nodes[0];
6023 slot = path->slots[0];
6024 if (slot >= btrfs_header_nritems(leaf)) {
6025 ret = btrfs_next_leaf(root, path);
6033 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6035 if (found_key.objectid != key.objectid)
6037 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6039 if (found_key.offset < ctx->pos)
6041 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6043 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6044 name_len = btrfs_dir_name_len(leaf, di);
6045 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6047 btrfs_release_path(path);
6048 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6051 addr = private->filldir_buf;
6058 put_unaligned(name_len, &entry->name_len);
6059 name_ptr = (char *)(entry + 1);
6060 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6062 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6064 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6065 put_unaligned(location.objectid, &entry->ino);
6066 put_unaligned(found_key.offset, &entry->offset);
6068 addr += sizeof(struct dir_entry) + name_len;
6069 total_len += sizeof(struct dir_entry) + name_len;
6073 btrfs_release_path(path);
6075 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6079 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6084 * Stop new entries from being returned after we return the last
6087 * New directory entries are assigned a strictly increasing
6088 * offset. This means that new entries created during readdir
6089 * are *guaranteed* to be seen in the future by that readdir.
6090 * This has broken buggy programs which operate on names as
6091 * they're returned by readdir. Until we re-use freed offsets
6092 * we have this hack to stop new entries from being returned
6093 * under the assumption that they'll never reach this huge
6096 * This is being careful not to overflow 32bit loff_t unless the
6097 * last entry requires it because doing so has broken 32bit apps
6100 if (ctx->pos >= INT_MAX)
6101 ctx->pos = LLONG_MAX;
6108 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6109 btrfs_free_path(path);
6114 * This is somewhat expensive, updating the tree every time the
6115 * inode changes. But, it is most likely to find the inode in cache.
6116 * FIXME, needs more benchmarking...there are no reasons other than performance
6117 * to keep or drop this code.
6119 static int btrfs_dirty_inode(struct inode *inode)
6121 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6122 struct btrfs_root *root = BTRFS_I(inode)->root;
6123 struct btrfs_trans_handle *trans;
6126 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6129 trans = btrfs_join_transaction(root);
6131 return PTR_ERR(trans);
6133 ret = btrfs_update_inode(trans, root, inode);
6134 if (ret && ret == -ENOSPC) {
6135 /* whoops, lets try again with the full transaction */
6136 btrfs_end_transaction(trans);
6137 trans = btrfs_start_transaction(root, 1);
6139 return PTR_ERR(trans);
6141 ret = btrfs_update_inode(trans, root, inode);
6143 btrfs_end_transaction(trans);
6144 if (BTRFS_I(inode)->delayed_node)
6145 btrfs_balance_delayed_items(fs_info);
6151 * This is a copy of file_update_time. We need this so we can return error on
6152 * ENOSPC for updating the inode in the case of file write and mmap writes.
6154 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6157 struct btrfs_root *root = BTRFS_I(inode)->root;
6158 bool dirty = flags & ~S_VERSION;
6160 if (btrfs_root_readonly(root))
6163 if (flags & S_VERSION)
6164 dirty |= inode_maybe_inc_iversion(inode, dirty);
6165 if (flags & S_CTIME)
6166 inode->i_ctime = *now;
6167 if (flags & S_MTIME)
6168 inode->i_mtime = *now;
6169 if (flags & S_ATIME)
6170 inode->i_atime = *now;
6171 return dirty ? btrfs_dirty_inode(inode) : 0;
6175 * find the highest existing sequence number in a directory
6176 * and then set the in-memory index_cnt variable to reflect
6177 * free sequence numbers
6179 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6181 struct btrfs_root *root = inode->root;
6182 struct btrfs_key key, found_key;
6183 struct btrfs_path *path;
6184 struct extent_buffer *leaf;
6187 key.objectid = btrfs_ino(inode);
6188 key.type = BTRFS_DIR_INDEX_KEY;
6189 key.offset = (u64)-1;
6191 path = btrfs_alloc_path();
6195 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6198 /* FIXME: we should be able to handle this */
6204 * MAGIC NUMBER EXPLANATION:
6205 * since we search a directory based on f_pos we have to start at 2
6206 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6207 * else has to start at 2
6209 if (path->slots[0] == 0) {
6210 inode->index_cnt = 2;
6216 leaf = path->nodes[0];
6217 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6219 if (found_key.objectid != btrfs_ino(inode) ||
6220 found_key.type != BTRFS_DIR_INDEX_KEY) {
6221 inode->index_cnt = 2;
6225 inode->index_cnt = found_key.offset + 1;
6227 btrfs_free_path(path);
6232 * helper to find a free sequence number in a given directory. This current
6233 * code is very simple, later versions will do smarter things in the btree
6235 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6239 if (dir->index_cnt == (u64)-1) {
6240 ret = btrfs_inode_delayed_dir_index_count(dir);
6242 ret = btrfs_set_inode_index_count(dir);
6248 *index = dir->index_cnt;
6254 static int btrfs_insert_inode_locked(struct inode *inode)
6256 struct btrfs_iget_args args;
6257 args.location = &BTRFS_I(inode)->location;
6258 args.root = BTRFS_I(inode)->root;
6260 return insert_inode_locked4(inode,
6261 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6262 btrfs_find_actor, &args);
6266 * Inherit flags from the parent inode.
6268 * Currently only the compression flags and the cow flags are inherited.
6270 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6277 flags = BTRFS_I(dir)->flags;
6279 if (flags & BTRFS_INODE_NOCOMPRESS) {
6280 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6281 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6282 } else if (flags & BTRFS_INODE_COMPRESS) {
6283 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6284 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6287 if (flags & BTRFS_INODE_NODATACOW) {
6288 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6289 if (S_ISREG(inode->i_mode))
6290 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6293 btrfs_sync_inode_flags_to_i_flags(inode);
6296 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6297 struct btrfs_root *root,
6299 const char *name, int name_len,
6300 u64 ref_objectid, u64 objectid,
6301 umode_t mode, u64 *index)
6303 struct btrfs_fs_info *fs_info = root->fs_info;
6304 struct inode *inode;
6305 struct btrfs_inode_item *inode_item;
6306 struct btrfs_key *location;
6307 struct btrfs_path *path;
6308 struct btrfs_inode_ref *ref;
6309 struct btrfs_key key[2];
6311 int nitems = name ? 2 : 1;
6313 unsigned int nofs_flag;
6316 path = btrfs_alloc_path();
6318 return ERR_PTR(-ENOMEM);
6320 nofs_flag = memalloc_nofs_save();
6321 inode = new_inode(fs_info->sb);
6322 memalloc_nofs_restore(nofs_flag);
6324 btrfs_free_path(path);
6325 return ERR_PTR(-ENOMEM);
6329 * O_TMPFILE, set link count to 0, so that after this point,
6330 * we fill in an inode item with the correct link count.
6333 set_nlink(inode, 0);
6336 * we have to initialize this early, so we can reclaim the inode
6337 * number if we fail afterwards in this function.
6339 inode->i_ino = objectid;
6342 trace_btrfs_inode_request(dir);
6344 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6346 btrfs_free_path(path);
6348 return ERR_PTR(ret);
6354 * index_cnt is ignored for everything but a dir,
6355 * btrfs_set_inode_index_count has an explanation for the magic
6358 BTRFS_I(inode)->index_cnt = 2;
6359 BTRFS_I(inode)->dir_index = *index;
6360 BTRFS_I(inode)->root = root;
6361 BTRFS_I(inode)->generation = trans->transid;
6362 inode->i_generation = BTRFS_I(inode)->generation;
6365 * We could have gotten an inode number from somebody who was fsynced
6366 * and then removed in this same transaction, so let's just set full
6367 * sync since it will be a full sync anyway and this will blow away the
6368 * old info in the log.
6370 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6372 key[0].objectid = objectid;
6373 key[0].type = BTRFS_INODE_ITEM_KEY;
6376 sizes[0] = sizeof(struct btrfs_inode_item);
6380 * Start new inodes with an inode_ref. This is slightly more
6381 * efficient for small numbers of hard links since they will
6382 * be packed into one item. Extended refs will kick in if we
6383 * add more hard links than can fit in the ref item.
6385 key[1].objectid = objectid;
6386 key[1].type = BTRFS_INODE_REF_KEY;
6387 key[1].offset = ref_objectid;
6389 sizes[1] = name_len + sizeof(*ref);
6392 location = &BTRFS_I(inode)->location;
6393 location->objectid = objectid;
6394 location->offset = 0;
6395 location->type = BTRFS_INODE_ITEM_KEY;
6397 ret = btrfs_insert_inode_locked(inode);
6403 path->leave_spinning = 1;
6404 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6408 inode_init_owner(inode, dir, mode);
6409 inode_set_bytes(inode, 0);
6411 inode->i_mtime = current_time(inode);
6412 inode->i_atime = inode->i_mtime;
6413 inode->i_ctime = inode->i_mtime;
6414 BTRFS_I(inode)->i_otime = inode->i_mtime;
6416 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6417 struct btrfs_inode_item);
6418 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6419 sizeof(*inode_item));
6420 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6423 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6424 struct btrfs_inode_ref);
6425 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6426 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6427 ptr = (unsigned long)(ref + 1);
6428 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6431 btrfs_mark_buffer_dirty(path->nodes[0]);
6432 btrfs_free_path(path);
6434 btrfs_inherit_iflags(inode, dir);
6436 if (S_ISREG(mode)) {
6437 if (btrfs_test_opt(fs_info, NODATASUM))
6438 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6439 if (btrfs_test_opt(fs_info, NODATACOW))
6440 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6441 BTRFS_INODE_NODATASUM;
6444 inode_tree_add(inode);
6446 trace_btrfs_inode_new(inode);
6447 btrfs_set_inode_last_trans(trans, inode);
6449 btrfs_update_root_times(trans, root);
6451 ret = btrfs_inode_inherit_props(trans, inode, dir);
6454 "error inheriting props for ino %llu (root %llu): %d",
6455 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6460 discard_new_inode(inode);
6463 BTRFS_I(dir)->index_cnt--;
6464 btrfs_free_path(path);
6465 return ERR_PTR(ret);
6469 * utility function to add 'inode' into 'parent_inode' with
6470 * a give name and a given sequence number.
6471 * if 'add_backref' is true, also insert a backref from the
6472 * inode to the parent directory.
6474 int btrfs_add_link(struct btrfs_trans_handle *trans,
6475 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6476 const char *name, int name_len, int add_backref, u64 index)
6479 struct btrfs_key key;
6480 struct btrfs_root *root = parent_inode->root;
6481 u64 ino = btrfs_ino(inode);
6482 u64 parent_ino = btrfs_ino(parent_inode);
6484 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6485 memcpy(&key, &inode->root->root_key, sizeof(key));
6488 key.type = BTRFS_INODE_ITEM_KEY;
6492 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6493 ret = btrfs_add_root_ref(trans, key.objectid,
6494 root->root_key.objectid, parent_ino,
6495 index, name, name_len);
6496 } else if (add_backref) {
6497 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6501 /* Nothing to clean up yet */
6505 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6506 btrfs_inode_type(&inode->vfs_inode), index);
6507 if (ret == -EEXIST || ret == -EOVERFLOW)
6510 btrfs_abort_transaction(trans, ret);
6514 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6516 inode_inc_iversion(&parent_inode->vfs_inode);
6518 * If we are replaying a log tree, we do not want to update the mtime
6519 * and ctime of the parent directory with the current time, since the
6520 * log replay procedure is responsible for setting them to their correct
6521 * values (the ones it had when the fsync was done).
6523 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6524 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6526 parent_inode->vfs_inode.i_mtime = now;
6527 parent_inode->vfs_inode.i_ctime = now;
6529 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6531 btrfs_abort_transaction(trans, ret);
6535 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6538 err = btrfs_del_root_ref(trans, key.objectid,
6539 root->root_key.objectid, parent_ino,
6540 &local_index, name, name_len);
6542 btrfs_abort_transaction(trans, err);
6543 } else if (add_backref) {
6547 err = btrfs_del_inode_ref(trans, root, name, name_len,
6548 ino, parent_ino, &local_index);
6550 btrfs_abort_transaction(trans, err);
6553 /* Return the original error code */
6557 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6558 struct btrfs_inode *dir, struct dentry *dentry,
6559 struct btrfs_inode *inode, int backref, u64 index)
6561 int err = btrfs_add_link(trans, dir, inode,
6562 dentry->d_name.name, dentry->d_name.len,
6569 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6570 umode_t mode, dev_t rdev)
6572 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6573 struct btrfs_trans_handle *trans;
6574 struct btrfs_root *root = BTRFS_I(dir)->root;
6575 struct inode *inode = NULL;
6581 * 2 for inode item and ref
6583 * 1 for xattr if selinux is on
6585 trans = btrfs_start_transaction(root, 5);
6587 return PTR_ERR(trans);
6589 err = btrfs_find_free_ino(root, &objectid);
6593 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6594 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6596 if (IS_ERR(inode)) {
6597 err = PTR_ERR(inode);
6603 * If the active LSM wants to access the inode during
6604 * d_instantiate it needs these. Smack checks to see
6605 * if the filesystem supports xattrs by looking at the
6608 inode->i_op = &btrfs_special_inode_operations;
6609 init_special_inode(inode, inode->i_mode, rdev);
6611 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6615 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6620 btrfs_update_inode(trans, root, inode);
6621 d_instantiate_new(dentry, inode);
6624 btrfs_end_transaction(trans);
6625 btrfs_btree_balance_dirty(fs_info);
6627 inode_dec_link_count(inode);
6628 discard_new_inode(inode);
6633 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6634 umode_t mode, bool excl)
6636 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6637 struct btrfs_trans_handle *trans;
6638 struct btrfs_root *root = BTRFS_I(dir)->root;
6639 struct inode *inode = NULL;
6645 * 2 for inode item and ref
6647 * 1 for xattr if selinux is on
6649 trans = btrfs_start_transaction(root, 5);
6651 return PTR_ERR(trans);
6653 err = btrfs_find_free_ino(root, &objectid);
6657 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6658 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6660 if (IS_ERR(inode)) {
6661 err = PTR_ERR(inode);
6666 * If the active LSM wants to access the inode during
6667 * d_instantiate it needs these. Smack checks to see
6668 * if the filesystem supports xattrs by looking at the
6671 inode->i_fop = &btrfs_file_operations;
6672 inode->i_op = &btrfs_file_inode_operations;
6673 inode->i_mapping->a_ops = &btrfs_aops;
6675 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6679 err = btrfs_update_inode(trans, root, inode);
6683 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6688 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6689 d_instantiate_new(dentry, inode);
6692 btrfs_end_transaction(trans);
6694 inode_dec_link_count(inode);
6695 discard_new_inode(inode);
6697 btrfs_btree_balance_dirty(fs_info);
6701 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6702 struct dentry *dentry)
6704 struct btrfs_trans_handle *trans = NULL;
6705 struct btrfs_root *root = BTRFS_I(dir)->root;
6706 struct inode *inode = d_inode(old_dentry);
6707 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6712 /* do not allow sys_link's with other subvols of the same device */
6713 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6716 if (inode->i_nlink >= BTRFS_LINK_MAX)
6719 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6724 * 2 items for inode and inode ref
6725 * 2 items for dir items
6726 * 1 item for parent inode
6727 * 1 item for orphan item deletion if O_TMPFILE
6729 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6730 if (IS_ERR(trans)) {
6731 err = PTR_ERR(trans);
6736 /* There are several dir indexes for this inode, clear the cache. */
6737 BTRFS_I(inode)->dir_index = 0ULL;
6739 inode_inc_iversion(inode);
6740 inode->i_ctime = current_time(inode);
6742 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6744 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6750 struct dentry *parent = dentry->d_parent;
6753 err = btrfs_update_inode(trans, root, inode);
6756 if (inode->i_nlink == 1) {
6758 * If new hard link count is 1, it's a file created
6759 * with open(2) O_TMPFILE flag.
6761 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6765 d_instantiate(dentry, inode);
6766 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6768 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6769 err = btrfs_commit_transaction(trans);
6776 btrfs_end_transaction(trans);
6778 inode_dec_link_count(inode);
6781 btrfs_btree_balance_dirty(fs_info);
6785 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6787 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6788 struct inode *inode = NULL;
6789 struct btrfs_trans_handle *trans;
6790 struct btrfs_root *root = BTRFS_I(dir)->root;
6796 * 2 items for inode and ref
6797 * 2 items for dir items
6798 * 1 for xattr if selinux is on
6800 trans = btrfs_start_transaction(root, 5);
6802 return PTR_ERR(trans);
6804 err = btrfs_find_free_ino(root, &objectid);
6808 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6809 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6810 S_IFDIR | mode, &index);
6811 if (IS_ERR(inode)) {
6812 err = PTR_ERR(inode);
6817 /* these must be set before we unlock the inode */
6818 inode->i_op = &btrfs_dir_inode_operations;
6819 inode->i_fop = &btrfs_dir_file_operations;
6821 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6825 btrfs_i_size_write(BTRFS_I(inode), 0);
6826 err = btrfs_update_inode(trans, root, inode);
6830 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6831 dentry->d_name.name,
6832 dentry->d_name.len, 0, index);
6836 d_instantiate_new(dentry, inode);
6839 btrfs_end_transaction(trans);
6841 inode_dec_link_count(inode);
6842 discard_new_inode(inode);
6844 btrfs_btree_balance_dirty(fs_info);
6848 static noinline int uncompress_inline(struct btrfs_path *path,
6850 size_t pg_offset, u64 extent_offset,
6851 struct btrfs_file_extent_item *item)
6854 struct extent_buffer *leaf = path->nodes[0];
6857 unsigned long inline_size;
6861 WARN_ON(pg_offset != 0);
6862 compress_type = btrfs_file_extent_compression(leaf, item);
6863 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6864 inline_size = btrfs_file_extent_inline_item_len(leaf,
6865 btrfs_item_nr(path->slots[0]));
6866 tmp = kmalloc(inline_size, GFP_NOFS);
6869 ptr = btrfs_file_extent_inline_start(item);
6871 read_extent_buffer(leaf, tmp, ptr, inline_size);
6873 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6874 ret = btrfs_decompress(compress_type, tmp, page,
6875 extent_offset, inline_size, max_size);
6878 * decompression code contains a memset to fill in any space between the end
6879 * of the uncompressed data and the end of max_size in case the decompressed
6880 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6881 * the end of an inline extent and the beginning of the next block, so we
6882 * cover that region here.
6885 if (max_size + pg_offset < PAGE_SIZE) {
6886 char *map = kmap(page);
6887 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6895 * a bit scary, this does extent mapping from logical file offset to the disk.
6896 * the ugly parts come from merging extents from the disk with the in-ram
6897 * representation. This gets more complex because of the data=ordered code,
6898 * where the in-ram extents might be locked pending data=ordered completion.
6900 * This also copies inline extents directly into the page.
6902 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6904 size_t pg_offset, u64 start, u64 len,
6907 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6910 u64 extent_start = 0;
6912 u64 objectid = btrfs_ino(inode);
6913 int extent_type = -1;
6914 struct btrfs_path *path = NULL;
6915 struct btrfs_root *root = inode->root;
6916 struct btrfs_file_extent_item *item;
6917 struct extent_buffer *leaf;
6918 struct btrfs_key found_key;
6919 struct extent_map *em = NULL;
6920 struct extent_map_tree *em_tree = &inode->extent_tree;
6921 struct extent_io_tree *io_tree = &inode->io_tree;
6922 const bool new_inline = !page || create;
6924 read_lock(&em_tree->lock);
6925 em = lookup_extent_mapping(em_tree, start, len);
6927 em->bdev = fs_info->fs_devices->latest_bdev;
6928 read_unlock(&em_tree->lock);
6931 if (em->start > start || em->start + em->len <= start)
6932 free_extent_map(em);
6933 else if (em->block_start == EXTENT_MAP_INLINE && page)
6934 free_extent_map(em);
6938 em = alloc_extent_map();
6943 em->bdev = fs_info->fs_devices->latest_bdev;
6944 em->start = EXTENT_MAP_HOLE;
6945 em->orig_start = EXTENT_MAP_HOLE;
6947 em->block_len = (u64)-1;
6949 path = btrfs_alloc_path();
6955 /* Chances are we'll be called again, so go ahead and do readahead */
6956 path->reada = READA_FORWARD;
6959 * Unless we're going to uncompress the inline extent, no sleep would
6962 path->leave_spinning = 1;
6964 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6968 } else if (ret > 0) {
6969 if (path->slots[0] == 0)
6974 leaf = path->nodes[0];
6975 item = btrfs_item_ptr(leaf, path->slots[0],
6976 struct btrfs_file_extent_item);
6977 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6978 if (found_key.objectid != objectid ||
6979 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6981 * If we backup past the first extent we want to move forward
6982 * and see if there is an extent in front of us, otherwise we'll
6983 * say there is a hole for our whole search range which can
6990 extent_type = btrfs_file_extent_type(leaf, item);
6991 extent_start = found_key.offset;
6992 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6993 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6994 /* Only regular file could have regular/prealloc extent */
6995 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6998 "regular/prealloc extent found for non-regular inode %llu",
7002 extent_end = extent_start +
7003 btrfs_file_extent_num_bytes(leaf, item);
7005 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7007 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7010 size = btrfs_file_extent_ram_bytes(leaf, item);
7011 extent_end = ALIGN(extent_start + size,
7012 fs_info->sectorsize);
7014 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7019 if (start >= extent_end) {
7021 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7022 ret = btrfs_next_leaf(root, path);
7026 } else if (ret > 0) {
7029 leaf = path->nodes[0];
7031 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7032 if (found_key.objectid != objectid ||
7033 found_key.type != BTRFS_EXTENT_DATA_KEY)
7035 if (start + len <= found_key.offset)
7037 if (start > found_key.offset)
7040 /* New extent overlaps with existing one */
7042 em->orig_start = start;
7043 em->len = found_key.offset - start;
7044 em->block_start = EXTENT_MAP_HOLE;
7048 btrfs_extent_item_to_extent_map(inode, path, item,
7051 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7052 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7054 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7058 size_t extent_offset;
7064 size = btrfs_file_extent_ram_bytes(leaf, item);
7065 extent_offset = page_offset(page) + pg_offset - extent_start;
7066 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7067 size - extent_offset);
7068 em->start = extent_start + extent_offset;
7069 em->len = ALIGN(copy_size, fs_info->sectorsize);
7070 em->orig_block_len = em->len;
7071 em->orig_start = em->start;
7072 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7074 btrfs_set_path_blocking(path);
7075 if (!PageUptodate(page)) {
7076 if (btrfs_file_extent_compression(leaf, item) !=
7077 BTRFS_COMPRESS_NONE) {
7078 ret = uncompress_inline(path, page, pg_offset,
7079 extent_offset, item);
7086 read_extent_buffer(leaf, map + pg_offset, ptr,
7088 if (pg_offset + copy_size < PAGE_SIZE) {
7089 memset(map + pg_offset + copy_size, 0,
7090 PAGE_SIZE - pg_offset -
7095 flush_dcache_page(page);
7097 set_extent_uptodate(io_tree, em->start,
7098 extent_map_end(em) - 1, NULL, GFP_NOFS);
7103 em->orig_start = start;
7105 em->block_start = EXTENT_MAP_HOLE;
7107 btrfs_release_path(path);
7108 if (em->start > start || extent_map_end(em) <= start) {
7110 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7111 em->start, em->len, start, len);
7117 write_lock(&em_tree->lock);
7118 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7119 write_unlock(&em_tree->lock);
7121 btrfs_free_path(path);
7123 trace_btrfs_get_extent(root, inode, em);
7126 free_extent_map(em);
7127 return ERR_PTR(err);
7129 BUG_ON(!em); /* Error is always set */
7133 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7136 struct extent_map *em;
7137 struct extent_map *hole_em = NULL;
7138 u64 delalloc_start = start;
7144 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7148 * If our em maps to:
7150 * - a pre-alloc extent,
7151 * there might actually be delalloc bytes behind it.
7153 if (em->block_start != EXTENT_MAP_HOLE &&
7154 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7159 /* check to see if we've wrapped (len == -1 or similar) */
7168 /* ok, we didn't find anything, lets look for delalloc */
7169 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7170 end, len, EXTENT_DELALLOC, 1);
7171 delalloc_end = delalloc_start + delalloc_len;
7172 if (delalloc_end < delalloc_start)
7173 delalloc_end = (u64)-1;
7176 * We didn't find anything useful, return the original results from
7179 if (delalloc_start > end || delalloc_end <= start) {
7186 * Adjust the delalloc_start to make sure it doesn't go backwards from
7187 * the start they passed in
7189 delalloc_start = max(start, delalloc_start);
7190 delalloc_len = delalloc_end - delalloc_start;
7192 if (delalloc_len > 0) {
7195 const u64 hole_end = extent_map_end(hole_em);
7197 em = alloc_extent_map();
7206 * When btrfs_get_extent can't find anything it returns one
7209 * Make sure what it found really fits our range, and adjust to
7210 * make sure it is based on the start from the caller
7212 if (hole_end <= start || hole_em->start > end) {
7213 free_extent_map(hole_em);
7216 hole_start = max(hole_em->start, start);
7217 hole_len = hole_end - hole_start;
7220 if (hole_em && delalloc_start > hole_start) {
7222 * Our hole starts before our delalloc, so we have to
7223 * return just the parts of the hole that go until the
7226 em->len = min(hole_len, delalloc_start - hole_start);
7227 em->start = hole_start;
7228 em->orig_start = hole_start;
7230 * Don't adjust block start at all, it is fixed at
7233 em->block_start = hole_em->block_start;
7234 em->block_len = hole_len;
7235 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7236 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7239 * Hole is out of passed range or it starts after
7242 em->start = delalloc_start;
7243 em->len = delalloc_len;
7244 em->orig_start = delalloc_start;
7245 em->block_start = EXTENT_MAP_DELALLOC;
7246 em->block_len = delalloc_len;
7253 free_extent_map(hole_em);
7255 free_extent_map(em);
7256 return ERR_PTR(err);
7261 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7264 const u64 orig_start,
7265 const u64 block_start,
7266 const u64 block_len,
7267 const u64 orig_block_len,
7268 const u64 ram_bytes,
7271 struct extent_map *em = NULL;
7274 if (type != BTRFS_ORDERED_NOCOW) {
7275 em = create_io_em(inode, start, len, orig_start,
7276 block_start, block_len, orig_block_len,
7278 BTRFS_COMPRESS_NONE, /* compress_type */
7283 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7284 len, block_len, type);
7287 free_extent_map(em);
7288 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7289 start + len - 1, 0);
7298 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7301 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7302 struct btrfs_root *root = BTRFS_I(inode)->root;
7303 struct extent_map *em;
7304 struct btrfs_key ins;
7308 alloc_hint = get_extent_allocation_hint(inode, start, len);
7309 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7310 0, alloc_hint, &ins, 1, 1);
7312 return ERR_PTR(ret);
7314 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7315 ins.objectid, ins.offset, ins.offset,
7316 ins.offset, BTRFS_ORDERED_REGULAR);
7317 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7319 btrfs_free_reserved_extent(fs_info, ins.objectid,
7326 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7327 * block must be cow'd
7329 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7330 u64 *orig_start, u64 *orig_block_len,
7333 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7334 struct btrfs_path *path;
7336 struct extent_buffer *leaf;
7337 struct btrfs_root *root = BTRFS_I(inode)->root;
7338 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7339 struct btrfs_file_extent_item *fi;
7340 struct btrfs_key key;
7347 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7349 path = btrfs_alloc_path();
7353 ret = btrfs_lookup_file_extent(NULL, root, path,
7354 btrfs_ino(BTRFS_I(inode)), offset, 0);
7358 slot = path->slots[0];
7361 /* can't find the item, must cow */
7368 leaf = path->nodes[0];
7369 btrfs_item_key_to_cpu(leaf, &key, slot);
7370 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7371 key.type != BTRFS_EXTENT_DATA_KEY) {
7372 /* not our file or wrong item type, must cow */
7376 if (key.offset > offset) {
7377 /* Wrong offset, must cow */
7381 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7382 found_type = btrfs_file_extent_type(leaf, fi);
7383 if (found_type != BTRFS_FILE_EXTENT_REG &&
7384 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7385 /* not a regular extent, must cow */
7389 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7392 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7393 if (extent_end <= offset)
7396 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7397 if (disk_bytenr == 0)
7400 if (btrfs_file_extent_compression(leaf, fi) ||
7401 btrfs_file_extent_encryption(leaf, fi) ||
7402 btrfs_file_extent_other_encoding(leaf, fi))
7406 * Do the same check as in btrfs_cross_ref_exist but without the
7407 * unnecessary search.
7409 if (btrfs_file_extent_generation(leaf, fi) <=
7410 btrfs_root_last_snapshot(&root->root_item))
7413 backref_offset = btrfs_file_extent_offset(leaf, fi);
7416 *orig_start = key.offset - backref_offset;
7417 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7418 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7421 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7424 num_bytes = min(offset + *len, extent_end) - offset;
7425 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7428 range_end = round_up(offset + num_bytes,
7429 root->fs_info->sectorsize) - 1;
7430 ret = test_range_bit(io_tree, offset, range_end,
7431 EXTENT_DELALLOC, 0, NULL);
7438 btrfs_release_path(path);
7441 * look for other files referencing this extent, if we
7442 * find any we must cow
7445 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7446 key.offset - backref_offset, disk_bytenr);
7453 * adjust disk_bytenr and num_bytes to cover just the bytes
7454 * in this extent we are about to write. If there
7455 * are any csums in that range we have to cow in order
7456 * to keep the csums correct
7458 disk_bytenr += backref_offset;
7459 disk_bytenr += offset - key.offset;
7460 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7463 * all of the above have passed, it is safe to overwrite this extent
7469 btrfs_free_path(path);
7473 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7474 struct extent_state **cached_state, int writing)
7476 struct btrfs_ordered_extent *ordered;
7480 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7483 * We're concerned with the entire range that we're going to be
7484 * doing DIO to, so we need to make sure there's no ordered
7485 * extents in this range.
7487 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7488 lockend - lockstart + 1);
7491 * We need to make sure there are no buffered pages in this
7492 * range either, we could have raced between the invalidate in
7493 * generic_file_direct_write and locking the extent. The
7494 * invalidate needs to happen so that reads after a write do not
7498 (!writing || !filemap_range_has_page(inode->i_mapping,
7499 lockstart, lockend)))
7502 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7507 * If we are doing a DIO read and the ordered extent we
7508 * found is for a buffered write, we can not wait for it
7509 * to complete and retry, because if we do so we can
7510 * deadlock with concurrent buffered writes on page
7511 * locks. This happens only if our DIO read covers more
7512 * than one extent map, if at this point has already
7513 * created an ordered extent for a previous extent map
7514 * and locked its range in the inode's io tree, and a
7515 * concurrent write against that previous extent map's
7516 * range and this range started (we unlock the ranges
7517 * in the io tree only when the bios complete and
7518 * buffered writes always lock pages before attempting
7519 * to lock range in the io tree).
7522 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7523 btrfs_start_ordered_extent(inode, ordered, 1);
7526 btrfs_put_ordered_extent(ordered);
7529 * We could trigger writeback for this range (and wait
7530 * for it to complete) and then invalidate the pages for
7531 * this range (through invalidate_inode_pages2_range()),
7532 * but that can lead us to a deadlock with a concurrent
7533 * call to readpages() (a buffered read or a defrag call
7534 * triggered a readahead) on a page lock due to an
7535 * ordered dio extent we created before but did not have
7536 * yet a corresponding bio submitted (whence it can not
7537 * complete), which makes readpages() wait for that
7538 * ordered extent to complete while holding a lock on
7553 /* The callers of this must take lock_extent() */
7554 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7555 u64 orig_start, u64 block_start,
7556 u64 block_len, u64 orig_block_len,
7557 u64 ram_bytes, int compress_type,
7560 struct extent_map_tree *em_tree;
7561 struct extent_map *em;
7562 struct btrfs_root *root = BTRFS_I(inode)->root;
7565 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7566 type == BTRFS_ORDERED_COMPRESSED ||
7567 type == BTRFS_ORDERED_NOCOW ||
7568 type == BTRFS_ORDERED_REGULAR);
7570 em_tree = &BTRFS_I(inode)->extent_tree;
7571 em = alloc_extent_map();
7573 return ERR_PTR(-ENOMEM);
7576 em->orig_start = orig_start;
7578 em->block_len = block_len;
7579 em->block_start = block_start;
7580 em->bdev = root->fs_info->fs_devices->latest_bdev;
7581 em->orig_block_len = orig_block_len;
7582 em->ram_bytes = ram_bytes;
7583 em->generation = -1;
7584 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7585 if (type == BTRFS_ORDERED_PREALLOC) {
7586 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7587 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7588 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7589 em->compress_type = compress_type;
7593 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7594 em->start + em->len - 1, 0);
7595 write_lock(&em_tree->lock);
7596 ret = add_extent_mapping(em_tree, em, 1);
7597 write_unlock(&em_tree->lock);
7599 * The caller has taken lock_extent(), who could race with us
7602 } while (ret == -EEXIST);
7605 free_extent_map(em);
7606 return ERR_PTR(ret);
7609 /* em got 2 refs now, callers needs to do free_extent_map once. */
7614 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7615 struct buffer_head *bh_result,
7616 struct inode *inode,
7619 if (em->block_start == EXTENT_MAP_HOLE ||
7620 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7623 len = min(len, em->len - (start - em->start));
7625 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7627 bh_result->b_size = len;
7628 bh_result->b_bdev = em->bdev;
7629 set_buffer_mapped(bh_result);
7634 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7635 struct buffer_head *bh_result,
7636 struct inode *inode,
7637 struct btrfs_dio_data *dio_data,
7640 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7641 struct extent_map *em = *map;
7645 * We don't allocate a new extent in the following cases
7647 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7649 * 2) The extent is marked as PREALLOC. We're good to go here and can
7650 * just use the extent.
7653 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7654 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7655 em->block_start != EXTENT_MAP_HOLE)) {
7657 u64 block_start, orig_start, orig_block_len, ram_bytes;
7659 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7660 type = BTRFS_ORDERED_PREALLOC;
7662 type = BTRFS_ORDERED_NOCOW;
7663 len = min(len, em->len - (start - em->start));
7664 block_start = em->block_start + (start - em->start);
7666 if (can_nocow_extent(inode, start, &len, &orig_start,
7667 &orig_block_len, &ram_bytes) == 1 &&
7668 btrfs_inc_nocow_writers(fs_info, block_start)) {
7669 struct extent_map *em2;
7671 em2 = btrfs_create_dio_extent(inode, start, len,
7672 orig_start, block_start,
7673 len, orig_block_len,
7675 btrfs_dec_nocow_writers(fs_info, block_start);
7676 if (type == BTRFS_ORDERED_PREALLOC) {
7677 free_extent_map(em);
7681 if (em2 && IS_ERR(em2)) {
7686 * For inode marked NODATACOW or extent marked PREALLOC,
7687 * use the existing or preallocated extent, so does not
7688 * need to adjust btrfs_space_info's bytes_may_use.
7690 btrfs_free_reserved_data_space_noquota(inode, start,
7696 /* this will cow the extent */
7697 len = bh_result->b_size;
7698 free_extent_map(em);
7699 *map = em = btrfs_new_extent_direct(inode, start, len);
7705 len = min(len, em->len - (start - em->start));
7708 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7710 bh_result->b_size = len;
7711 bh_result->b_bdev = em->bdev;
7712 set_buffer_mapped(bh_result);
7714 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7715 set_buffer_new(bh_result);
7718 * Need to update the i_size under the extent lock so buffered
7719 * readers will get the updated i_size when we unlock.
7721 if (!dio_data->overwrite && start + len > i_size_read(inode))
7722 i_size_write(inode, start + len);
7724 WARN_ON(dio_data->reserve < len);
7725 dio_data->reserve -= len;
7726 dio_data->unsubmitted_oe_range_end = start + len;
7727 current->journal_info = dio_data;
7732 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7733 struct buffer_head *bh_result, int create)
7735 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7736 struct extent_map *em;
7737 struct extent_state *cached_state = NULL;
7738 struct btrfs_dio_data *dio_data = NULL;
7739 u64 start = iblock << inode->i_blkbits;
7740 u64 lockstart, lockend;
7741 u64 len = bh_result->b_size;
7745 len = min_t(u64, len, fs_info->sectorsize);
7748 lockend = start + len - 1;
7750 if (current->journal_info) {
7752 * Need to pull our outstanding extents and set journal_info to NULL so
7753 * that anything that needs to check if there's a transaction doesn't get
7756 dio_data = current->journal_info;
7757 current->journal_info = NULL;
7761 * If this errors out it's because we couldn't invalidate pagecache for
7762 * this range and we need to fallback to buffered.
7764 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7770 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7777 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7778 * io. INLINE is special, and we could probably kludge it in here, but
7779 * it's still buffered so for safety lets just fall back to the generic
7782 * For COMPRESSED we _have_ to read the entire extent in so we can
7783 * decompress it, so there will be buffering required no matter what we
7784 * do, so go ahead and fallback to buffered.
7786 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7787 * to buffered IO. Don't blame me, this is the price we pay for using
7790 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7791 em->block_start == EXTENT_MAP_INLINE) {
7792 free_extent_map(em);
7798 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7799 dio_data, start, len);
7803 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7804 lockend, &cached_state);
7806 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7808 /* Can be negative only if we read from a hole */
7811 free_extent_map(em);
7815 * We need to unlock only the end area that we aren't using.
7816 * The rest is going to be unlocked by the endio routine.
7818 lockstart = start + bh_result->b_size;
7819 if (lockstart < lockend) {
7820 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7821 lockstart, lockend, &cached_state);
7823 free_extent_state(cached_state);
7827 free_extent_map(em);
7832 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7836 current->journal_info = dio_data;
7840 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7844 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7847 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7849 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7853 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7858 static int btrfs_check_dio_repairable(struct inode *inode,
7859 struct bio *failed_bio,
7860 struct io_failure_record *failrec,
7863 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7866 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7867 if (num_copies == 1) {
7869 * we only have a single copy of the data, so don't bother with
7870 * all the retry and error correction code that follows. no
7871 * matter what the error is, it is very likely to persist.
7873 btrfs_debug(fs_info,
7874 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7875 num_copies, failrec->this_mirror, failed_mirror);
7879 failrec->failed_mirror = failed_mirror;
7880 failrec->this_mirror++;
7881 if (failrec->this_mirror == failed_mirror)
7882 failrec->this_mirror++;
7884 if (failrec->this_mirror > num_copies) {
7885 btrfs_debug(fs_info,
7886 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7887 num_copies, failrec->this_mirror, failed_mirror);
7894 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7895 struct page *page, unsigned int pgoff,
7896 u64 start, u64 end, int failed_mirror,
7897 bio_end_io_t *repair_endio, void *repair_arg)
7899 struct io_failure_record *failrec;
7900 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7901 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7904 unsigned int read_mode = 0;
7907 blk_status_t status;
7908 struct bio_vec bvec;
7910 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7912 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7914 return errno_to_blk_status(ret);
7916 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7919 free_io_failure(failure_tree, io_tree, failrec);
7920 return BLK_STS_IOERR;
7923 segs = bio_segments(failed_bio);
7924 bio_get_first_bvec(failed_bio, &bvec);
7926 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7927 read_mode |= REQ_FAILFAST_DEV;
7929 isector = start - btrfs_io_bio(failed_bio)->logical;
7930 isector >>= inode->i_sb->s_blocksize_bits;
7931 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7932 pgoff, isector, repair_endio, repair_arg);
7933 bio->bi_opf = REQ_OP_READ | read_mode;
7935 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7936 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7937 read_mode, failrec->this_mirror, failrec->in_validation);
7939 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7941 free_io_failure(failure_tree, io_tree, failrec);
7948 struct btrfs_retry_complete {
7949 struct completion done;
7950 struct inode *inode;
7955 static void btrfs_retry_endio_nocsum(struct bio *bio)
7957 struct btrfs_retry_complete *done = bio->bi_private;
7958 struct inode *inode = done->inode;
7959 struct bio_vec *bvec;
7960 struct extent_io_tree *io_tree, *failure_tree;
7961 struct bvec_iter_all iter_all;
7966 ASSERT(bio->bi_vcnt == 1);
7967 io_tree = &BTRFS_I(inode)->io_tree;
7968 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7969 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7972 ASSERT(!bio_flagged(bio, BIO_CLONED));
7973 bio_for_each_segment_all(bvec, bio, iter_all)
7974 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7975 io_tree, done->start, bvec->bv_page,
7976 btrfs_ino(BTRFS_I(inode)), 0);
7978 complete(&done->done);
7982 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7983 struct btrfs_io_bio *io_bio)
7985 struct btrfs_fs_info *fs_info;
7986 struct bio_vec bvec;
7987 struct bvec_iter iter;
7988 struct btrfs_retry_complete done;
7994 blk_status_t err = BLK_STS_OK;
7996 fs_info = BTRFS_I(inode)->root->fs_info;
7997 sectorsize = fs_info->sectorsize;
7999 start = io_bio->logical;
8001 io_bio->bio.bi_iter = io_bio->iter;
8003 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8004 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8005 pgoff = bvec.bv_offset;
8007 next_block_or_try_again:
8010 init_completion(&done.done);
8012 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8013 pgoff, start, start + sectorsize - 1,
8015 btrfs_retry_endio_nocsum, &done);
8021 wait_for_completion_io(&done.done);
8023 if (!done.uptodate) {
8024 /* We might have another mirror, so try again */
8025 goto next_block_or_try_again;
8029 start += sectorsize;
8033 pgoff += sectorsize;
8034 ASSERT(pgoff < PAGE_SIZE);
8035 goto next_block_or_try_again;
8042 static void btrfs_retry_endio(struct bio *bio)
8044 struct btrfs_retry_complete *done = bio->bi_private;
8045 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8046 struct extent_io_tree *io_tree, *failure_tree;
8047 struct inode *inode = done->inode;
8048 struct bio_vec *bvec;
8052 struct bvec_iter_all iter_all;
8059 ASSERT(bio->bi_vcnt == 1);
8060 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8062 io_tree = &BTRFS_I(inode)->io_tree;
8063 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8065 ASSERT(!bio_flagged(bio, BIO_CLONED));
8066 bio_for_each_segment_all(bvec, bio, iter_all) {
8067 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8068 bvec->bv_offset, done->start,
8071 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8072 failure_tree, io_tree, done->start,
8074 btrfs_ino(BTRFS_I(inode)),
8081 done->uptodate = uptodate;
8083 complete(&done->done);
8087 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8088 struct btrfs_io_bio *io_bio, blk_status_t err)
8090 struct btrfs_fs_info *fs_info;
8091 struct bio_vec bvec;
8092 struct bvec_iter iter;
8093 struct btrfs_retry_complete done;
8100 bool uptodate = (err == 0);
8102 blk_status_t status;
8104 fs_info = BTRFS_I(inode)->root->fs_info;
8105 sectorsize = fs_info->sectorsize;
8108 start = io_bio->logical;
8110 io_bio->bio.bi_iter = io_bio->iter;
8112 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8113 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8115 pgoff = bvec.bv_offset;
8118 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8119 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8120 bvec.bv_page, pgoff, start, sectorsize);
8127 init_completion(&done.done);
8129 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8130 pgoff, start, start + sectorsize - 1,
8131 io_bio->mirror_num, btrfs_retry_endio,
8138 wait_for_completion_io(&done.done);
8140 if (!done.uptodate) {
8141 /* We might have another mirror, so try again */
8145 offset += sectorsize;
8146 start += sectorsize;
8152 pgoff += sectorsize;
8153 ASSERT(pgoff < PAGE_SIZE);
8161 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8162 struct btrfs_io_bio *io_bio, blk_status_t err)
8164 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8168 return __btrfs_correct_data_nocsum(inode, io_bio);
8172 return __btrfs_subio_endio_read(inode, io_bio, err);
8176 static void btrfs_endio_direct_read(struct bio *bio)
8178 struct btrfs_dio_private *dip = bio->bi_private;
8179 struct inode *inode = dip->inode;
8180 struct bio *dio_bio;
8181 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8182 blk_status_t err = bio->bi_status;
8184 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8185 err = btrfs_subio_endio_read(inode, io_bio, err);
8187 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8188 dip->logical_offset + dip->bytes - 1);
8189 dio_bio = dip->dio_bio;
8193 dio_bio->bi_status = err;
8194 dio_end_io(dio_bio);
8195 btrfs_io_bio_free_csum(io_bio);
8199 static void __endio_write_update_ordered(struct inode *inode,
8200 const u64 offset, const u64 bytes,
8201 const bool uptodate)
8203 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8204 struct btrfs_ordered_extent *ordered = NULL;
8205 struct btrfs_workqueue *wq;
8206 u64 ordered_offset = offset;
8207 u64 ordered_bytes = bytes;
8210 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
8211 wq = fs_info->endio_freespace_worker;
8213 wq = fs_info->endio_write_workers;
8215 while (ordered_offset < offset + bytes) {
8216 last_offset = ordered_offset;
8217 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8221 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
8223 btrfs_queue_work(wq, &ordered->work);
8226 * If btrfs_dec_test_ordered_pending does not find any ordered
8227 * extent in the range, we can exit.
8229 if (ordered_offset == last_offset)
8232 * Our bio might span multiple ordered extents. In this case
8233 * we keep going until we have accounted the whole dio.
8235 if (ordered_offset < offset + bytes) {
8236 ordered_bytes = offset + bytes - ordered_offset;
8242 static void btrfs_endio_direct_write(struct bio *bio)
8244 struct btrfs_dio_private *dip = bio->bi_private;
8245 struct bio *dio_bio = dip->dio_bio;
8247 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8248 dip->bytes, !bio->bi_status);
8252 dio_bio->bi_status = bio->bi_status;
8253 dio_end_io(dio_bio);
8257 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8258 struct bio *bio, u64 offset)
8260 struct inode *inode = private_data;
8262 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8263 BUG_ON(ret); /* -ENOMEM */
8267 static void btrfs_end_dio_bio(struct bio *bio)
8269 struct btrfs_dio_private *dip = bio->bi_private;
8270 blk_status_t err = bio->bi_status;
8273 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8274 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8275 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8277 (unsigned long long)bio->bi_iter.bi_sector,
8278 bio->bi_iter.bi_size, err);
8280 if (dip->subio_endio)
8281 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8285 * We want to perceive the errors flag being set before
8286 * decrementing the reference count. We don't need a barrier
8287 * since atomic operations with a return value are fully
8288 * ordered as per atomic_t.txt
8293 /* if there are more bios still pending for this dio, just exit */
8294 if (!atomic_dec_and_test(&dip->pending_bios))
8298 bio_io_error(dip->orig_bio);
8300 dip->dio_bio->bi_status = BLK_STS_OK;
8301 bio_endio(dip->orig_bio);
8307 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8308 struct btrfs_dio_private *dip,
8312 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8313 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8317 * We load all the csum data we need when we submit
8318 * the first bio to reduce the csum tree search and
8321 if (dip->logical_offset == file_offset) {
8322 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8328 if (bio == dip->orig_bio)
8331 file_offset -= dip->logical_offset;
8332 file_offset >>= inode->i_sb->s_blocksize_bits;
8333 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8338 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8339 struct inode *inode, u64 file_offset, int async_submit)
8341 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8342 struct btrfs_dio_private *dip = bio->bi_private;
8343 bool write = bio_op(bio) == REQ_OP_WRITE;
8346 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8348 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8351 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8356 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8359 if (write && async_submit) {
8360 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8362 btrfs_submit_bio_start_direct_io);
8366 * If we aren't doing async submit, calculate the csum of the
8369 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8373 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8379 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8384 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8386 struct inode *inode = dip->inode;
8387 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8389 struct bio *orig_bio = dip->orig_bio;
8390 u64 start_sector = orig_bio->bi_iter.bi_sector;
8391 u64 file_offset = dip->logical_offset;
8392 int async_submit = 0;
8394 int clone_offset = 0;
8397 blk_status_t status;
8398 struct btrfs_io_geometry geom;
8400 submit_len = orig_bio->bi_iter.bi_size;
8401 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8402 start_sector << 9, submit_len, &geom);
8406 if (geom.len >= submit_len) {
8408 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8412 /* async crcs make it difficult to collect full stripe writes. */
8413 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8419 ASSERT(geom.len <= INT_MAX);
8420 atomic_inc(&dip->pending_bios);
8422 clone_len = min_t(int, submit_len, geom.len);
8425 * This will never fail as it's passing GPF_NOFS and
8426 * the allocation is backed by btrfs_bioset.
8428 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8430 bio->bi_private = dip;
8431 bio->bi_end_io = btrfs_end_dio_bio;
8432 btrfs_io_bio(bio)->logical = file_offset;
8434 ASSERT(submit_len >= clone_len);
8435 submit_len -= clone_len;
8436 if (submit_len == 0)
8440 * Increase the count before we submit the bio so we know
8441 * the end IO handler won't happen before we increase the
8442 * count. Otherwise, the dip might get freed before we're
8443 * done setting it up.
8445 atomic_inc(&dip->pending_bios);
8447 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8451 atomic_dec(&dip->pending_bios);
8455 clone_offset += clone_len;
8456 start_sector += clone_len >> 9;
8457 file_offset += clone_len;
8459 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8460 start_sector << 9, submit_len, &geom);
8463 } while (submit_len > 0);
8466 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8474 * Before atomic variable goto zero, we must make sure dip->errors is
8475 * perceived to be set. This ordering is ensured by the fact that an
8476 * atomic operations with a return value are fully ordered as per
8479 if (atomic_dec_and_test(&dip->pending_bios))
8480 bio_io_error(dip->orig_bio);
8482 /* bio_end_io() will handle error, so we needn't return it */
8486 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8489 struct btrfs_dio_private *dip = NULL;
8490 struct bio *bio = NULL;
8491 struct btrfs_io_bio *io_bio;
8492 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8495 bio = btrfs_bio_clone(dio_bio);
8497 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8503 dip->private = dio_bio->bi_private;
8505 dip->logical_offset = file_offset;
8506 dip->bytes = dio_bio->bi_iter.bi_size;
8507 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8508 bio->bi_private = dip;
8509 dip->orig_bio = bio;
8510 dip->dio_bio = dio_bio;
8511 atomic_set(&dip->pending_bios, 0);
8512 io_bio = btrfs_io_bio(bio);
8513 io_bio->logical = file_offset;
8516 bio->bi_end_io = btrfs_endio_direct_write;
8518 bio->bi_end_io = btrfs_endio_direct_read;
8519 dip->subio_endio = btrfs_subio_endio_read;
8523 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8524 * even if we fail to submit a bio, because in such case we do the
8525 * corresponding error handling below and it must not be done a second
8526 * time by btrfs_direct_IO().
8529 struct btrfs_dio_data *dio_data = current->journal_info;
8531 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8533 dio_data->unsubmitted_oe_range_start =
8534 dio_data->unsubmitted_oe_range_end;
8537 ret = btrfs_submit_direct_hook(dip);
8541 btrfs_io_bio_free_csum(io_bio);
8545 * If we arrived here it means either we failed to submit the dip
8546 * or we either failed to clone the dio_bio or failed to allocate the
8547 * dip. If we cloned the dio_bio and allocated the dip, we can just
8548 * call bio_endio against our io_bio so that we get proper resource
8549 * cleanup if we fail to submit the dip, otherwise, we must do the
8550 * same as btrfs_endio_direct_[write|read] because we can't call these
8551 * callbacks - they require an allocated dip and a clone of dio_bio.
8556 * The end io callbacks free our dip, do the final put on bio
8557 * and all the cleanup and final put for dio_bio (through
8564 __endio_write_update_ordered(inode,
8566 dio_bio->bi_iter.bi_size,
8569 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8570 file_offset + dio_bio->bi_iter.bi_size - 1);
8572 dio_bio->bi_status = BLK_STS_IOERR;
8574 * Releases and cleans up our dio_bio, no need to bio_put()
8575 * nor bio_endio()/bio_io_error() against dio_bio.
8577 dio_end_io(dio_bio);
8584 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8585 const struct iov_iter *iter, loff_t offset)
8589 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8590 ssize_t retval = -EINVAL;
8592 if (offset & blocksize_mask)
8595 if (iov_iter_alignment(iter) & blocksize_mask)
8598 /* If this is a write we don't need to check anymore */
8599 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8602 * Check to make sure we don't have duplicate iov_base's in this
8603 * iovec, if so return EINVAL, otherwise we'll get csum errors
8604 * when reading back.
8606 for (seg = 0; seg < iter->nr_segs; seg++) {
8607 for (i = seg + 1; i < iter->nr_segs; i++) {
8608 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8617 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8619 struct file *file = iocb->ki_filp;
8620 struct inode *inode = file->f_mapping->host;
8621 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8622 struct btrfs_dio_data dio_data = { 0 };
8623 struct extent_changeset *data_reserved = NULL;
8624 loff_t offset = iocb->ki_pos;
8628 bool relock = false;
8631 if (check_direct_IO(fs_info, iter, offset))
8634 inode_dio_begin(inode);
8637 * The generic stuff only does filemap_write_and_wait_range, which
8638 * isn't enough if we've written compressed pages to this area, so
8639 * we need to flush the dirty pages again to make absolutely sure
8640 * that any outstanding dirty pages are on disk.
8642 count = iov_iter_count(iter);
8643 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8644 &BTRFS_I(inode)->runtime_flags))
8645 filemap_fdatawrite_range(inode->i_mapping, offset,
8646 offset + count - 1);
8648 if (iov_iter_rw(iter) == WRITE) {
8650 * If the write DIO is beyond the EOF, we need update
8651 * the isize, but it is protected by i_mutex. So we can
8652 * not unlock the i_mutex at this case.
8654 if (offset + count <= inode->i_size) {
8655 dio_data.overwrite = 1;
8656 inode_unlock(inode);
8658 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8662 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8668 * We need to know how many extents we reserved so that we can
8669 * do the accounting properly if we go over the number we
8670 * originally calculated. Abuse current->journal_info for this.
8672 dio_data.reserve = round_up(count,
8673 fs_info->sectorsize);
8674 dio_data.unsubmitted_oe_range_start = (u64)offset;
8675 dio_data.unsubmitted_oe_range_end = (u64)offset;
8676 current->journal_info = &dio_data;
8677 down_read(&BTRFS_I(inode)->dio_sem);
8678 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8679 &BTRFS_I(inode)->runtime_flags)) {
8680 inode_dio_end(inode);
8681 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8685 ret = __blockdev_direct_IO(iocb, inode,
8686 fs_info->fs_devices->latest_bdev,
8687 iter, btrfs_get_blocks_direct, NULL,
8688 btrfs_submit_direct, flags);
8689 if (iov_iter_rw(iter) == WRITE) {
8690 up_read(&BTRFS_I(inode)->dio_sem);
8691 current->journal_info = NULL;
8692 if (ret < 0 && ret != -EIOCBQUEUED) {
8693 if (dio_data.reserve)
8694 btrfs_delalloc_release_space(inode, data_reserved,
8695 offset, dio_data.reserve, true);
8697 * On error we might have left some ordered extents
8698 * without submitting corresponding bios for them, so
8699 * cleanup them up to avoid other tasks getting them
8700 * and waiting for them to complete forever.
8702 if (dio_data.unsubmitted_oe_range_start <
8703 dio_data.unsubmitted_oe_range_end)
8704 __endio_write_update_ordered(inode,
8705 dio_data.unsubmitted_oe_range_start,
8706 dio_data.unsubmitted_oe_range_end -
8707 dio_data.unsubmitted_oe_range_start,
8709 } else if (ret >= 0 && (size_t)ret < count)
8710 btrfs_delalloc_release_space(inode, data_reserved,
8711 offset, count - (size_t)ret, true);
8712 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8716 inode_dio_end(inode);
8720 extent_changeset_free(data_reserved);
8724 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8726 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8727 __u64 start, __u64 len)
8731 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8735 return extent_fiemap(inode, fieinfo, start, len);
8738 int btrfs_readpage(struct file *file, struct page *page)
8740 struct extent_io_tree *tree;
8741 tree = &BTRFS_I(page->mapping->host)->io_tree;
8742 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8745 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8747 struct inode *inode = page->mapping->host;
8750 if (current->flags & PF_MEMALLOC) {
8751 redirty_page_for_writepage(wbc, page);
8757 * If we are under memory pressure we will call this directly from the
8758 * VM, we need to make sure we have the inode referenced for the ordered
8759 * extent. If not just return like we didn't do anything.
8761 if (!igrab(inode)) {
8762 redirty_page_for_writepage(wbc, page);
8763 return AOP_WRITEPAGE_ACTIVATE;
8765 ret = extent_write_full_page(page, wbc);
8766 btrfs_add_delayed_iput(inode);
8770 static int btrfs_writepages(struct address_space *mapping,
8771 struct writeback_control *wbc)
8773 return extent_writepages(mapping, wbc);
8777 btrfs_readpages(struct file *file, struct address_space *mapping,
8778 struct list_head *pages, unsigned nr_pages)
8780 return extent_readpages(mapping, pages, nr_pages);
8783 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8785 int ret = try_release_extent_mapping(page, gfp_flags);
8787 ClearPagePrivate(page);
8788 set_page_private(page, 0);
8794 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8796 if (PageWriteback(page) || PageDirty(page))
8798 return __btrfs_releasepage(page, gfp_flags);
8801 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8802 unsigned int length)
8804 struct inode *inode = page->mapping->host;
8805 struct extent_io_tree *tree;
8806 struct btrfs_ordered_extent *ordered;
8807 struct extent_state *cached_state = NULL;
8808 u64 page_start = page_offset(page);
8809 u64 page_end = page_start + PAGE_SIZE - 1;
8812 int inode_evicting = inode->i_state & I_FREEING;
8815 * we have the page locked, so new writeback can't start,
8816 * and the dirty bit won't be cleared while we are here.
8818 * Wait for IO on this page so that we can safely clear
8819 * the PagePrivate2 bit and do ordered accounting
8821 wait_on_page_writeback(page);
8823 tree = &BTRFS_I(inode)->io_tree;
8825 btrfs_releasepage(page, GFP_NOFS);
8829 if (!inode_evicting)
8830 lock_extent_bits(tree, page_start, page_end, &cached_state);
8833 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8834 page_end - start + 1);
8836 end = min(page_end, ordered->file_offset + ordered->len - 1);
8838 * IO on this page will never be started, so we need
8839 * to account for any ordered extents now
8841 if (!inode_evicting)
8842 clear_extent_bit(tree, start, end,
8843 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8844 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8845 EXTENT_DEFRAG, 1, 0, &cached_state);
8847 * whoever cleared the private bit is responsible
8848 * for the finish_ordered_io
8850 if (TestClearPagePrivate2(page)) {
8851 struct btrfs_ordered_inode_tree *tree;
8854 tree = &BTRFS_I(inode)->ordered_tree;
8856 spin_lock_irq(&tree->lock);
8857 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8858 new_len = start - ordered->file_offset;
8859 if (new_len < ordered->truncated_len)
8860 ordered->truncated_len = new_len;
8861 spin_unlock_irq(&tree->lock);
8863 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8865 end - start + 1, 1))
8866 btrfs_finish_ordered_io(ordered);
8868 btrfs_put_ordered_extent(ordered);
8869 if (!inode_evicting) {
8870 cached_state = NULL;
8871 lock_extent_bits(tree, start, end,
8876 if (start < page_end)
8881 * Qgroup reserved space handler
8882 * Page here will be either
8883 * 1) Already written to disk
8884 * In this case, its reserved space is released from data rsv map
8885 * and will be freed by delayed_ref handler finally.
8886 * So even we call qgroup_free_data(), it won't decrease reserved
8888 * 2) Not written to disk
8889 * This means the reserved space should be freed here. However,
8890 * if a truncate invalidates the page (by clearing PageDirty)
8891 * and the page is accounted for while allocating extent
8892 * in btrfs_check_data_free_space() we let delayed_ref to
8893 * free the entire extent.
8895 if (PageDirty(page))
8896 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8897 if (!inode_evicting) {
8898 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8899 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8900 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8903 __btrfs_releasepage(page, GFP_NOFS);
8906 ClearPageChecked(page);
8907 if (PagePrivate(page)) {
8908 ClearPagePrivate(page);
8909 set_page_private(page, 0);
8915 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8916 * called from a page fault handler when a page is first dirtied. Hence we must
8917 * be careful to check for EOF conditions here. We set the page up correctly
8918 * for a written page which means we get ENOSPC checking when writing into
8919 * holes and correct delalloc and unwritten extent mapping on filesystems that
8920 * support these features.
8922 * We are not allowed to take the i_mutex here so we have to play games to
8923 * protect against truncate races as the page could now be beyond EOF. Because
8924 * truncate_setsize() writes the inode size before removing pages, once we have
8925 * the page lock we can determine safely if the page is beyond EOF. If it is not
8926 * beyond EOF, then the page is guaranteed safe against truncation until we
8929 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8931 struct page *page = vmf->page;
8932 struct inode *inode = file_inode(vmf->vma->vm_file);
8933 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8934 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8935 struct btrfs_ordered_extent *ordered;
8936 struct extent_state *cached_state = NULL;
8937 struct extent_changeset *data_reserved = NULL;
8939 unsigned long zero_start;
8949 reserved_space = PAGE_SIZE;
8951 sb_start_pagefault(inode->i_sb);
8952 page_start = page_offset(page);
8953 page_end = page_start + PAGE_SIZE - 1;
8957 * Reserving delalloc space after obtaining the page lock can lead to
8958 * deadlock. For example, if a dirty page is locked by this function
8959 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8960 * dirty page write out, then the btrfs_writepage() function could
8961 * end up waiting indefinitely to get a lock on the page currently
8962 * being processed by btrfs_page_mkwrite() function.
8964 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8967 ret2 = file_update_time(vmf->vma->vm_file);
8971 ret = vmf_error(ret2);
8977 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8980 size = i_size_read(inode);
8982 if ((page->mapping != inode->i_mapping) ||
8983 (page_start >= size)) {
8984 /* page got truncated out from underneath us */
8987 wait_on_page_writeback(page);
8989 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8990 set_page_extent_mapped(page);
8993 * we can't set the delalloc bits if there are pending ordered
8994 * extents. Drop our locks and wait for them to finish
8996 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8999 unlock_extent_cached(io_tree, page_start, page_end,
9002 btrfs_start_ordered_extent(inode, ordered, 1);
9003 btrfs_put_ordered_extent(ordered);
9007 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9008 reserved_space = round_up(size - page_start,
9009 fs_info->sectorsize);
9010 if (reserved_space < PAGE_SIZE) {
9011 end = page_start + reserved_space - 1;
9012 btrfs_delalloc_release_space(inode, data_reserved,
9013 page_start, PAGE_SIZE - reserved_space,
9019 * page_mkwrite gets called when the page is firstly dirtied after it's
9020 * faulted in, but write(2) could also dirty a page and set delalloc
9021 * bits, thus in this case for space account reason, we still need to
9022 * clear any delalloc bits within this page range since we have to
9023 * reserve data&meta space before lock_page() (see above comments).
9025 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9026 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
9027 EXTENT_DEFRAG, 0, 0, &cached_state);
9029 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9032 unlock_extent_cached(io_tree, page_start, page_end,
9034 ret = VM_FAULT_SIGBUS;
9039 /* page is wholly or partially inside EOF */
9040 if (page_start + PAGE_SIZE > size)
9041 zero_start = offset_in_page(size);
9043 zero_start = PAGE_SIZE;
9045 if (zero_start != PAGE_SIZE) {
9047 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9048 flush_dcache_page(page);
9051 ClearPageChecked(page);
9052 set_page_dirty(page);
9053 SetPageUptodate(page);
9055 BTRFS_I(inode)->last_trans = fs_info->generation;
9056 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9057 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9059 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9062 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9063 sb_end_pagefault(inode->i_sb);
9064 extent_changeset_free(data_reserved);
9065 return VM_FAULT_LOCKED;
9071 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9072 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9073 reserved_space, (ret != 0));
9075 sb_end_pagefault(inode->i_sb);
9076 extent_changeset_free(data_reserved);
9080 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9082 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9083 struct btrfs_root *root = BTRFS_I(inode)->root;
9084 struct btrfs_block_rsv *rsv;
9086 struct btrfs_trans_handle *trans;
9087 u64 mask = fs_info->sectorsize - 1;
9088 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
9090 if (!skip_writeback) {
9091 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9098 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9099 * things going on here:
9101 * 1) We need to reserve space to update our inode.
9103 * 2) We need to have something to cache all the space that is going to
9104 * be free'd up by the truncate operation, but also have some slack
9105 * space reserved in case it uses space during the truncate (thank you
9106 * very much snapshotting).
9108 * And we need these to be separate. The fact is we can use a lot of
9109 * space doing the truncate, and we have no earthly idea how much space
9110 * we will use, so we need the truncate reservation to be separate so it
9111 * doesn't end up using space reserved for updating the inode. We also
9112 * need to be able to stop the transaction and start a new one, which
9113 * means we need to be able to update the inode several times, and we
9114 * have no idea of knowing how many times that will be, so we can't just
9115 * reserve 1 item for the entirety of the operation, so that has to be
9116 * done separately as well.
9118 * So that leaves us with
9120 * 1) rsv - for the truncate reservation, which we will steal from the
9121 * transaction reservation.
9122 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9123 * updating the inode.
9125 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9128 rsv->size = min_size;
9132 * 1 for the truncate slack space
9133 * 1 for updating the inode.
9135 trans = btrfs_start_transaction(root, 2);
9136 if (IS_ERR(trans)) {
9137 ret = PTR_ERR(trans);
9141 /* Migrate the slack space for the truncate to our reserve */
9142 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9147 * So if we truncate and then write and fsync we normally would just
9148 * write the extents that changed, which is a problem if we need to
9149 * first truncate that entire inode. So set this flag so we write out
9150 * all of the extents in the inode to the sync log so we're completely
9153 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9154 trans->block_rsv = rsv;
9157 ret = btrfs_truncate_inode_items(trans, root, inode,
9159 BTRFS_EXTENT_DATA_KEY);
9160 trans->block_rsv = &fs_info->trans_block_rsv;
9161 if (ret != -ENOSPC && ret != -EAGAIN)
9164 ret = btrfs_update_inode(trans, root, inode);
9168 btrfs_end_transaction(trans);
9169 btrfs_btree_balance_dirty(fs_info);
9171 trans = btrfs_start_transaction(root, 2);
9172 if (IS_ERR(trans)) {
9173 ret = PTR_ERR(trans);
9178 btrfs_block_rsv_release(fs_info, rsv, -1);
9179 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9180 rsv, min_size, false);
9181 BUG_ON(ret); /* shouldn't happen */
9182 trans->block_rsv = rsv;
9186 * We can't call btrfs_truncate_block inside a trans handle as we could
9187 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9188 * we've truncated everything except the last little bit, and can do
9189 * btrfs_truncate_block and then update the disk_i_size.
9191 if (ret == NEED_TRUNCATE_BLOCK) {
9192 btrfs_end_transaction(trans);
9193 btrfs_btree_balance_dirty(fs_info);
9195 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9198 trans = btrfs_start_transaction(root, 1);
9199 if (IS_ERR(trans)) {
9200 ret = PTR_ERR(trans);
9203 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9209 trans->block_rsv = &fs_info->trans_block_rsv;
9210 ret2 = btrfs_update_inode(trans, root, inode);
9214 ret2 = btrfs_end_transaction(trans);
9217 btrfs_btree_balance_dirty(fs_info);
9220 btrfs_free_block_rsv(fs_info, rsv);
9226 * create a new subvolume directory/inode (helper for the ioctl).
9228 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9229 struct btrfs_root *new_root,
9230 struct btrfs_root *parent_root,
9233 struct inode *inode;
9237 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9238 new_dirid, new_dirid,
9239 S_IFDIR | (~current_umask() & S_IRWXUGO),
9242 return PTR_ERR(inode);
9243 inode->i_op = &btrfs_dir_inode_operations;
9244 inode->i_fop = &btrfs_dir_file_operations;
9246 set_nlink(inode, 1);
9247 btrfs_i_size_write(BTRFS_I(inode), 0);
9248 unlock_new_inode(inode);
9250 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9252 btrfs_err(new_root->fs_info,
9253 "error inheriting subvolume %llu properties: %d",
9254 new_root->root_key.objectid, err);
9256 err = btrfs_update_inode(trans, new_root, inode);
9262 struct inode *btrfs_alloc_inode(struct super_block *sb)
9264 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9265 struct btrfs_inode *ei;
9266 struct inode *inode;
9268 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9275 ei->last_sub_trans = 0;
9276 ei->logged_trans = 0;
9277 ei->delalloc_bytes = 0;
9278 ei->new_delalloc_bytes = 0;
9279 ei->defrag_bytes = 0;
9280 ei->disk_i_size = 0;
9283 ei->index_cnt = (u64)-1;
9285 ei->last_unlink_trans = 0;
9286 ei->last_log_commit = 0;
9288 spin_lock_init(&ei->lock);
9289 ei->outstanding_extents = 0;
9290 if (sb->s_magic != BTRFS_TEST_MAGIC)
9291 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9292 BTRFS_BLOCK_RSV_DELALLOC);
9293 ei->runtime_flags = 0;
9294 ei->prop_compress = BTRFS_COMPRESS_NONE;
9295 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9297 ei->delayed_node = NULL;
9299 ei->i_otime.tv_sec = 0;
9300 ei->i_otime.tv_nsec = 0;
9302 inode = &ei->vfs_inode;
9303 extent_map_tree_init(&ei->extent_tree);
9304 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9305 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9306 IO_TREE_INODE_IO_FAILURE, inode);
9307 ei->io_tree.track_uptodate = true;
9308 ei->io_failure_tree.track_uptodate = true;
9309 atomic_set(&ei->sync_writers, 0);
9310 mutex_init(&ei->log_mutex);
9311 mutex_init(&ei->delalloc_mutex);
9312 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9313 INIT_LIST_HEAD(&ei->delalloc_inodes);
9314 INIT_LIST_HEAD(&ei->delayed_iput);
9315 RB_CLEAR_NODE(&ei->rb_node);
9316 init_rwsem(&ei->dio_sem);
9321 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9322 void btrfs_test_destroy_inode(struct inode *inode)
9324 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9325 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9329 void btrfs_free_inode(struct inode *inode)
9331 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9334 void btrfs_destroy_inode(struct inode *inode)
9336 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9337 struct btrfs_ordered_extent *ordered;
9338 struct btrfs_root *root = BTRFS_I(inode)->root;
9340 WARN_ON(!hlist_empty(&inode->i_dentry));
9341 WARN_ON(inode->i_data.nrpages);
9342 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9343 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9344 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9345 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9346 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9347 WARN_ON(BTRFS_I(inode)->csum_bytes);
9348 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9351 * This can happen where we create an inode, but somebody else also
9352 * created the same inode and we need to destroy the one we already
9359 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9364 "found ordered extent %llu %llu on inode cleanup",
9365 ordered->file_offset, ordered->len);
9366 btrfs_remove_ordered_extent(inode, ordered);
9367 btrfs_put_ordered_extent(ordered);
9368 btrfs_put_ordered_extent(ordered);
9371 btrfs_qgroup_check_reserved_leak(inode);
9372 inode_tree_del(inode);
9373 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9376 int btrfs_drop_inode(struct inode *inode)
9378 struct btrfs_root *root = BTRFS_I(inode)->root;
9383 /* the snap/subvol tree is on deleting */
9384 if (btrfs_root_refs(&root->root_item) == 0)
9387 return generic_drop_inode(inode);
9390 static void init_once(void *foo)
9392 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9394 inode_init_once(&ei->vfs_inode);
9397 void __cold btrfs_destroy_cachep(void)
9400 * Make sure all delayed rcu free inodes are flushed before we
9404 kmem_cache_destroy(btrfs_inode_cachep);
9405 kmem_cache_destroy(btrfs_trans_handle_cachep);
9406 kmem_cache_destroy(btrfs_path_cachep);
9407 kmem_cache_destroy(btrfs_free_space_cachep);
9408 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
9411 int __init btrfs_init_cachep(void)
9413 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9414 sizeof(struct btrfs_inode), 0,
9415 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9417 if (!btrfs_inode_cachep)
9420 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9421 sizeof(struct btrfs_trans_handle), 0,
9422 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9423 if (!btrfs_trans_handle_cachep)
9426 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9427 sizeof(struct btrfs_path), 0,
9428 SLAB_MEM_SPREAD, NULL);
9429 if (!btrfs_path_cachep)
9432 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9433 sizeof(struct btrfs_free_space), 0,
9434 SLAB_MEM_SPREAD, NULL);
9435 if (!btrfs_free_space_cachep)
9438 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9439 PAGE_SIZE, PAGE_SIZE,
9440 SLAB_RED_ZONE, NULL);
9441 if (!btrfs_free_space_bitmap_cachep)
9446 btrfs_destroy_cachep();
9450 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9451 u32 request_mask, unsigned int flags)
9454 struct inode *inode = d_inode(path->dentry);
9455 u32 blocksize = inode->i_sb->s_blocksize;
9456 u32 bi_flags = BTRFS_I(inode)->flags;
9458 stat->result_mask |= STATX_BTIME;
9459 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9460 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9461 if (bi_flags & BTRFS_INODE_APPEND)
9462 stat->attributes |= STATX_ATTR_APPEND;
9463 if (bi_flags & BTRFS_INODE_COMPRESS)
9464 stat->attributes |= STATX_ATTR_COMPRESSED;
9465 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9466 stat->attributes |= STATX_ATTR_IMMUTABLE;
9467 if (bi_flags & BTRFS_INODE_NODUMP)
9468 stat->attributes |= STATX_ATTR_NODUMP;
9470 stat->attributes_mask |= (STATX_ATTR_APPEND |
9471 STATX_ATTR_COMPRESSED |
9472 STATX_ATTR_IMMUTABLE |
9475 generic_fillattr(inode, stat);
9476 stat->dev = BTRFS_I(inode)->root->anon_dev;
9478 spin_lock(&BTRFS_I(inode)->lock);
9479 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9480 spin_unlock(&BTRFS_I(inode)->lock);
9481 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9482 ALIGN(delalloc_bytes, blocksize)) >> 9;
9486 static int btrfs_rename_exchange(struct inode *old_dir,
9487 struct dentry *old_dentry,
9488 struct inode *new_dir,
9489 struct dentry *new_dentry)
9491 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9492 struct btrfs_trans_handle *trans;
9493 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9494 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9495 struct inode *new_inode = new_dentry->d_inode;
9496 struct inode *old_inode = old_dentry->d_inode;
9497 struct timespec64 ctime = current_time(old_inode);
9498 struct dentry *parent;
9499 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9500 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9505 bool root_log_pinned = false;
9506 bool dest_log_pinned = false;
9507 struct btrfs_log_ctx ctx_root;
9508 struct btrfs_log_ctx ctx_dest;
9509 bool sync_log_root = false;
9510 bool sync_log_dest = false;
9511 bool commit_transaction = false;
9513 /* we only allow rename subvolume link between subvolumes */
9514 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9517 btrfs_init_log_ctx(&ctx_root, old_inode);
9518 btrfs_init_log_ctx(&ctx_dest, new_inode);
9520 /* close the race window with snapshot create/destroy ioctl */
9521 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9522 down_read(&fs_info->subvol_sem);
9523 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9524 down_read(&fs_info->subvol_sem);
9527 * We want to reserve the absolute worst case amount of items. So if
9528 * both inodes are subvols and we need to unlink them then that would
9529 * require 4 item modifications, but if they are both normal inodes it
9530 * would require 5 item modifications, so we'll assume their normal
9531 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9532 * should cover the worst case number of items we'll modify.
9534 trans = btrfs_start_transaction(root, 12);
9535 if (IS_ERR(trans)) {
9536 ret = PTR_ERR(trans);
9541 * We need to find a free sequence number both in the source and
9542 * in the destination directory for the exchange.
9544 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9547 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9551 BTRFS_I(old_inode)->dir_index = 0ULL;
9552 BTRFS_I(new_inode)->dir_index = 0ULL;
9554 /* Reference for the source. */
9555 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9556 /* force full log commit if subvolume involved. */
9557 btrfs_set_log_full_commit(trans);
9559 btrfs_pin_log_trans(root);
9560 root_log_pinned = true;
9561 ret = btrfs_insert_inode_ref(trans, dest,
9562 new_dentry->d_name.name,
9563 new_dentry->d_name.len,
9565 btrfs_ino(BTRFS_I(new_dir)),
9571 /* And now for the dest. */
9572 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9573 /* force full log commit if subvolume involved. */
9574 btrfs_set_log_full_commit(trans);
9576 btrfs_pin_log_trans(dest);
9577 dest_log_pinned = true;
9578 ret = btrfs_insert_inode_ref(trans, root,
9579 old_dentry->d_name.name,
9580 old_dentry->d_name.len,
9582 btrfs_ino(BTRFS_I(old_dir)),
9588 /* Update inode version and ctime/mtime. */
9589 inode_inc_iversion(old_dir);
9590 inode_inc_iversion(new_dir);
9591 inode_inc_iversion(old_inode);
9592 inode_inc_iversion(new_inode);
9593 old_dir->i_ctime = old_dir->i_mtime = ctime;
9594 new_dir->i_ctime = new_dir->i_mtime = ctime;
9595 old_inode->i_ctime = ctime;
9596 new_inode->i_ctime = ctime;
9598 if (old_dentry->d_parent != new_dentry->d_parent) {
9599 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9600 BTRFS_I(old_inode), 1);
9601 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9602 BTRFS_I(new_inode), 1);
9605 /* src is a subvolume */
9606 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9607 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9608 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9609 old_dentry->d_name.name,
9610 old_dentry->d_name.len);
9611 } else { /* src is an inode */
9612 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9613 BTRFS_I(old_dentry->d_inode),
9614 old_dentry->d_name.name,
9615 old_dentry->d_name.len);
9617 ret = btrfs_update_inode(trans, root, old_inode);
9620 btrfs_abort_transaction(trans, ret);
9624 /* dest is a subvolume */
9625 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9626 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9627 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9628 new_dentry->d_name.name,
9629 new_dentry->d_name.len);
9630 } else { /* dest is an inode */
9631 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9632 BTRFS_I(new_dentry->d_inode),
9633 new_dentry->d_name.name,
9634 new_dentry->d_name.len);
9636 ret = btrfs_update_inode(trans, dest, new_inode);
9639 btrfs_abort_transaction(trans, ret);
9643 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9644 new_dentry->d_name.name,
9645 new_dentry->d_name.len, 0, old_idx);
9647 btrfs_abort_transaction(trans, ret);
9651 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9652 old_dentry->d_name.name,
9653 old_dentry->d_name.len, 0, new_idx);
9655 btrfs_abort_transaction(trans, ret);
9659 if (old_inode->i_nlink == 1)
9660 BTRFS_I(old_inode)->dir_index = old_idx;
9661 if (new_inode->i_nlink == 1)
9662 BTRFS_I(new_inode)->dir_index = new_idx;
9664 if (root_log_pinned) {
9665 parent = new_dentry->d_parent;
9666 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9667 BTRFS_I(old_dir), parent,
9669 if (ret == BTRFS_NEED_LOG_SYNC)
9670 sync_log_root = true;
9671 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9672 commit_transaction = true;
9674 btrfs_end_log_trans(root);
9675 root_log_pinned = false;
9677 if (dest_log_pinned) {
9678 if (!commit_transaction) {
9679 parent = old_dentry->d_parent;
9680 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9681 BTRFS_I(new_dir), parent,
9683 if (ret == BTRFS_NEED_LOG_SYNC)
9684 sync_log_dest = true;
9685 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9686 commit_transaction = true;
9689 btrfs_end_log_trans(dest);
9690 dest_log_pinned = false;
9694 * If we have pinned a log and an error happened, we unpin tasks
9695 * trying to sync the log and force them to fallback to a transaction
9696 * commit if the log currently contains any of the inodes involved in
9697 * this rename operation (to ensure we do not persist a log with an
9698 * inconsistent state for any of these inodes or leading to any
9699 * inconsistencies when replayed). If the transaction was aborted, the
9700 * abortion reason is propagated to userspace when attempting to commit
9701 * the transaction. If the log does not contain any of these inodes, we
9702 * allow the tasks to sync it.
9704 if (ret && (root_log_pinned || dest_log_pinned)) {
9705 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9706 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9707 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9709 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9710 btrfs_set_log_full_commit(trans);
9712 if (root_log_pinned) {
9713 btrfs_end_log_trans(root);
9714 root_log_pinned = false;
9716 if (dest_log_pinned) {
9717 btrfs_end_log_trans(dest);
9718 dest_log_pinned = false;
9721 if (!ret && sync_log_root && !commit_transaction) {
9722 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9725 commit_transaction = true;
9727 if (!ret && sync_log_dest && !commit_transaction) {
9728 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9731 commit_transaction = true;
9733 if (commit_transaction) {
9735 * We may have set commit_transaction when logging the new name
9736 * in the destination root, in which case we left the source
9737 * root context in the list of log contextes. So make sure we
9738 * remove it to avoid invalid memory accesses, since the context
9739 * was allocated in our stack frame.
9741 if (sync_log_root) {
9742 mutex_lock(&root->log_mutex);
9743 list_del_init(&ctx_root.list);
9744 mutex_unlock(&root->log_mutex);
9746 ret = btrfs_commit_transaction(trans);
9750 ret2 = btrfs_end_transaction(trans);
9751 ret = ret ? ret : ret2;
9754 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9755 up_read(&fs_info->subvol_sem);
9756 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9757 up_read(&fs_info->subvol_sem);
9759 ASSERT(list_empty(&ctx_root.list));
9760 ASSERT(list_empty(&ctx_dest.list));
9765 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9766 struct btrfs_root *root,
9768 struct dentry *dentry)
9771 struct inode *inode;
9775 ret = btrfs_find_free_ino(root, &objectid);
9779 inode = btrfs_new_inode(trans, root, dir,
9780 dentry->d_name.name,
9782 btrfs_ino(BTRFS_I(dir)),
9784 S_IFCHR | WHITEOUT_MODE,
9787 if (IS_ERR(inode)) {
9788 ret = PTR_ERR(inode);
9792 inode->i_op = &btrfs_special_inode_operations;
9793 init_special_inode(inode, inode->i_mode,
9796 ret = btrfs_init_inode_security(trans, inode, dir,
9801 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9802 BTRFS_I(inode), 0, index);
9806 ret = btrfs_update_inode(trans, root, inode);
9808 unlock_new_inode(inode);
9810 inode_dec_link_count(inode);
9816 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9817 struct inode *new_dir, struct dentry *new_dentry,
9820 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9821 struct btrfs_trans_handle *trans;
9822 unsigned int trans_num_items;
9823 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9824 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9825 struct inode *new_inode = d_inode(new_dentry);
9826 struct inode *old_inode = d_inode(old_dentry);
9830 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9831 bool log_pinned = false;
9832 struct btrfs_log_ctx ctx;
9833 bool sync_log = false;
9834 bool commit_transaction = false;
9836 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9839 /* we only allow rename subvolume link between subvolumes */
9840 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9843 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9844 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9847 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9848 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9852 /* check for collisions, even if the name isn't there */
9853 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9854 new_dentry->d_name.name,
9855 new_dentry->d_name.len);
9858 if (ret == -EEXIST) {
9860 * eexist without a new_inode */
9861 if (WARN_ON(!new_inode)) {
9865 /* maybe -EOVERFLOW */
9872 * we're using rename to replace one file with another. Start IO on it
9873 * now so we don't add too much work to the end of the transaction
9875 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9876 filemap_flush(old_inode->i_mapping);
9878 /* close the racy window with snapshot create/destroy ioctl */
9879 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9880 down_read(&fs_info->subvol_sem);
9882 * We want to reserve the absolute worst case amount of items. So if
9883 * both inodes are subvols and we need to unlink them then that would
9884 * require 4 item modifications, but if they are both normal inodes it
9885 * would require 5 item modifications, so we'll assume they are normal
9886 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9887 * should cover the worst case number of items we'll modify.
9888 * If our rename has the whiteout flag, we need more 5 units for the
9889 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9890 * when selinux is enabled).
9892 trans_num_items = 11;
9893 if (flags & RENAME_WHITEOUT)
9894 trans_num_items += 5;
9895 trans = btrfs_start_transaction(root, trans_num_items);
9896 if (IS_ERR(trans)) {
9897 ret = PTR_ERR(trans);
9902 btrfs_record_root_in_trans(trans, dest);
9904 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9908 BTRFS_I(old_inode)->dir_index = 0ULL;
9909 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9910 /* force full log commit if subvolume involved. */
9911 btrfs_set_log_full_commit(trans);
9913 btrfs_pin_log_trans(root);
9915 ret = btrfs_insert_inode_ref(trans, dest,
9916 new_dentry->d_name.name,
9917 new_dentry->d_name.len,
9919 btrfs_ino(BTRFS_I(new_dir)), index);
9924 inode_inc_iversion(old_dir);
9925 inode_inc_iversion(new_dir);
9926 inode_inc_iversion(old_inode);
9927 old_dir->i_ctime = old_dir->i_mtime =
9928 new_dir->i_ctime = new_dir->i_mtime =
9929 old_inode->i_ctime = current_time(old_dir);
9931 if (old_dentry->d_parent != new_dentry->d_parent)
9932 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9933 BTRFS_I(old_inode), 1);
9935 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9936 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9937 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9938 old_dentry->d_name.name,
9939 old_dentry->d_name.len);
9941 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9942 BTRFS_I(d_inode(old_dentry)),
9943 old_dentry->d_name.name,
9944 old_dentry->d_name.len);
9946 ret = btrfs_update_inode(trans, root, old_inode);
9949 btrfs_abort_transaction(trans, ret);
9954 inode_inc_iversion(new_inode);
9955 new_inode->i_ctime = current_time(new_inode);
9956 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9957 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9958 root_objectid = BTRFS_I(new_inode)->location.objectid;
9959 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9960 new_dentry->d_name.name,
9961 new_dentry->d_name.len);
9962 BUG_ON(new_inode->i_nlink == 0);
9964 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9965 BTRFS_I(d_inode(new_dentry)),
9966 new_dentry->d_name.name,
9967 new_dentry->d_name.len);
9969 if (!ret && new_inode->i_nlink == 0)
9970 ret = btrfs_orphan_add(trans,
9971 BTRFS_I(d_inode(new_dentry)));
9973 btrfs_abort_transaction(trans, ret);
9978 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9979 new_dentry->d_name.name,
9980 new_dentry->d_name.len, 0, index);
9982 btrfs_abort_transaction(trans, ret);
9986 if (old_inode->i_nlink == 1)
9987 BTRFS_I(old_inode)->dir_index = index;
9990 struct dentry *parent = new_dentry->d_parent;
9992 btrfs_init_log_ctx(&ctx, old_inode);
9993 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9994 BTRFS_I(old_dir), parent,
9996 if (ret == BTRFS_NEED_LOG_SYNC)
9998 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9999 commit_transaction = true;
10001 btrfs_end_log_trans(root);
10002 log_pinned = false;
10005 if (flags & RENAME_WHITEOUT) {
10006 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10010 btrfs_abort_transaction(trans, ret);
10016 * If we have pinned the log and an error happened, we unpin tasks
10017 * trying to sync the log and force them to fallback to a transaction
10018 * commit if the log currently contains any of the inodes involved in
10019 * this rename operation (to ensure we do not persist a log with an
10020 * inconsistent state for any of these inodes or leading to any
10021 * inconsistencies when replayed). If the transaction was aborted, the
10022 * abortion reason is propagated to userspace when attempting to commit
10023 * the transaction. If the log does not contain any of these inodes, we
10024 * allow the tasks to sync it.
10026 if (ret && log_pinned) {
10027 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10028 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10029 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10031 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10032 btrfs_set_log_full_commit(trans);
10034 btrfs_end_log_trans(root);
10035 log_pinned = false;
10037 if (!ret && sync_log) {
10038 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
10040 commit_transaction = true;
10042 if (commit_transaction) {
10043 ret = btrfs_commit_transaction(trans);
10047 ret2 = btrfs_end_transaction(trans);
10048 ret = ret ? ret : ret2;
10051 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10052 up_read(&fs_info->subvol_sem);
10057 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10058 struct inode *new_dir, struct dentry *new_dentry,
10059 unsigned int flags)
10061 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10064 if (flags & RENAME_EXCHANGE)
10065 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10068 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10071 struct btrfs_delalloc_work {
10072 struct inode *inode;
10073 struct completion completion;
10074 struct list_head list;
10075 struct btrfs_work work;
10078 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10080 struct btrfs_delalloc_work *delalloc_work;
10081 struct inode *inode;
10083 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10085 inode = delalloc_work->inode;
10086 filemap_flush(inode->i_mapping);
10087 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10088 &BTRFS_I(inode)->runtime_flags))
10089 filemap_flush(inode->i_mapping);
10092 complete(&delalloc_work->completion);
10095 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10097 struct btrfs_delalloc_work *work;
10099 work = kmalloc(sizeof(*work), GFP_NOFS);
10103 init_completion(&work->completion);
10104 INIT_LIST_HEAD(&work->list);
10105 work->inode = inode;
10106 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
10112 * some fairly slow code that needs optimization. This walks the list
10113 * of all the inodes with pending delalloc and forces them to disk.
10115 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10117 struct btrfs_inode *binode;
10118 struct inode *inode;
10119 struct btrfs_delalloc_work *work, *next;
10120 struct list_head works;
10121 struct list_head splice;
10124 INIT_LIST_HEAD(&works);
10125 INIT_LIST_HEAD(&splice);
10127 mutex_lock(&root->delalloc_mutex);
10128 spin_lock(&root->delalloc_lock);
10129 list_splice_init(&root->delalloc_inodes, &splice);
10130 while (!list_empty(&splice)) {
10131 binode = list_entry(splice.next, struct btrfs_inode,
10134 list_move_tail(&binode->delalloc_inodes,
10135 &root->delalloc_inodes);
10136 inode = igrab(&binode->vfs_inode);
10138 cond_resched_lock(&root->delalloc_lock);
10141 spin_unlock(&root->delalloc_lock);
10144 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10145 &binode->runtime_flags);
10146 work = btrfs_alloc_delalloc_work(inode);
10152 list_add_tail(&work->list, &works);
10153 btrfs_queue_work(root->fs_info->flush_workers,
10156 if (nr != -1 && ret >= nr)
10159 spin_lock(&root->delalloc_lock);
10161 spin_unlock(&root->delalloc_lock);
10164 list_for_each_entry_safe(work, next, &works, list) {
10165 list_del_init(&work->list);
10166 wait_for_completion(&work->completion);
10170 if (!list_empty(&splice)) {
10171 spin_lock(&root->delalloc_lock);
10172 list_splice_tail(&splice, &root->delalloc_inodes);
10173 spin_unlock(&root->delalloc_lock);
10175 mutex_unlock(&root->delalloc_mutex);
10179 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10181 struct btrfs_fs_info *fs_info = root->fs_info;
10184 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10187 ret = start_delalloc_inodes(root, -1, true);
10193 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10195 struct btrfs_root *root;
10196 struct list_head splice;
10199 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10202 INIT_LIST_HEAD(&splice);
10204 mutex_lock(&fs_info->delalloc_root_mutex);
10205 spin_lock(&fs_info->delalloc_root_lock);
10206 list_splice_init(&fs_info->delalloc_roots, &splice);
10207 while (!list_empty(&splice) && nr) {
10208 root = list_first_entry(&splice, struct btrfs_root,
10210 root = btrfs_grab_fs_root(root);
10212 list_move_tail(&root->delalloc_root,
10213 &fs_info->delalloc_roots);
10214 spin_unlock(&fs_info->delalloc_root_lock);
10216 ret = start_delalloc_inodes(root, nr, false);
10217 btrfs_put_fs_root(root);
10225 spin_lock(&fs_info->delalloc_root_lock);
10227 spin_unlock(&fs_info->delalloc_root_lock);
10231 if (!list_empty(&splice)) {
10232 spin_lock(&fs_info->delalloc_root_lock);
10233 list_splice_tail(&splice, &fs_info->delalloc_roots);
10234 spin_unlock(&fs_info->delalloc_root_lock);
10236 mutex_unlock(&fs_info->delalloc_root_mutex);
10240 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10241 const char *symname)
10243 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10244 struct btrfs_trans_handle *trans;
10245 struct btrfs_root *root = BTRFS_I(dir)->root;
10246 struct btrfs_path *path;
10247 struct btrfs_key key;
10248 struct inode *inode = NULL;
10255 struct btrfs_file_extent_item *ei;
10256 struct extent_buffer *leaf;
10258 name_len = strlen(symname);
10259 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10260 return -ENAMETOOLONG;
10263 * 2 items for inode item and ref
10264 * 2 items for dir items
10265 * 1 item for updating parent inode item
10266 * 1 item for the inline extent item
10267 * 1 item for xattr if selinux is on
10269 trans = btrfs_start_transaction(root, 7);
10271 return PTR_ERR(trans);
10273 err = btrfs_find_free_ino(root, &objectid);
10277 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10278 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10279 objectid, S_IFLNK|S_IRWXUGO, &index);
10280 if (IS_ERR(inode)) {
10281 err = PTR_ERR(inode);
10287 * If the active LSM wants to access the inode during
10288 * d_instantiate it needs these. Smack checks to see
10289 * if the filesystem supports xattrs by looking at the
10292 inode->i_fop = &btrfs_file_operations;
10293 inode->i_op = &btrfs_file_inode_operations;
10294 inode->i_mapping->a_ops = &btrfs_aops;
10295 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10297 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10301 path = btrfs_alloc_path();
10306 key.objectid = btrfs_ino(BTRFS_I(inode));
10308 key.type = BTRFS_EXTENT_DATA_KEY;
10309 datasize = btrfs_file_extent_calc_inline_size(name_len);
10310 err = btrfs_insert_empty_item(trans, root, path, &key,
10313 btrfs_free_path(path);
10316 leaf = path->nodes[0];
10317 ei = btrfs_item_ptr(leaf, path->slots[0],
10318 struct btrfs_file_extent_item);
10319 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10320 btrfs_set_file_extent_type(leaf, ei,
10321 BTRFS_FILE_EXTENT_INLINE);
10322 btrfs_set_file_extent_encryption(leaf, ei, 0);
10323 btrfs_set_file_extent_compression(leaf, ei, 0);
10324 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10325 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10327 ptr = btrfs_file_extent_inline_start(ei);
10328 write_extent_buffer(leaf, symname, ptr, name_len);
10329 btrfs_mark_buffer_dirty(leaf);
10330 btrfs_free_path(path);
10332 inode->i_op = &btrfs_symlink_inode_operations;
10333 inode_nohighmem(inode);
10334 inode_set_bytes(inode, name_len);
10335 btrfs_i_size_write(BTRFS_I(inode), name_len);
10336 err = btrfs_update_inode(trans, root, inode);
10338 * Last step, add directory indexes for our symlink inode. This is the
10339 * last step to avoid extra cleanup of these indexes if an error happens
10343 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10344 BTRFS_I(inode), 0, index);
10348 d_instantiate_new(dentry, inode);
10351 btrfs_end_transaction(trans);
10352 if (err && inode) {
10353 inode_dec_link_count(inode);
10354 discard_new_inode(inode);
10356 btrfs_btree_balance_dirty(fs_info);
10360 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10361 u64 start, u64 num_bytes, u64 min_size,
10362 loff_t actual_len, u64 *alloc_hint,
10363 struct btrfs_trans_handle *trans)
10365 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10366 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10367 struct extent_map *em;
10368 struct btrfs_root *root = BTRFS_I(inode)->root;
10369 struct btrfs_key ins;
10370 u64 cur_offset = start;
10373 u64 last_alloc = (u64)-1;
10375 bool own_trans = true;
10376 u64 end = start + num_bytes - 1;
10380 while (num_bytes > 0) {
10382 trans = btrfs_start_transaction(root, 3);
10383 if (IS_ERR(trans)) {
10384 ret = PTR_ERR(trans);
10389 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10390 cur_bytes = max(cur_bytes, min_size);
10392 * If we are severely fragmented we could end up with really
10393 * small allocations, so if the allocator is returning small
10394 * chunks lets make its job easier by only searching for those
10397 cur_bytes = min(cur_bytes, last_alloc);
10398 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10399 min_size, 0, *alloc_hint, &ins, 1, 0);
10402 btrfs_end_transaction(trans);
10405 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10407 last_alloc = ins.offset;
10408 ret = insert_reserved_file_extent(trans, inode,
10409 cur_offset, ins.objectid,
10410 ins.offset, ins.offset,
10411 ins.offset, 0, 0, 0,
10412 BTRFS_FILE_EXTENT_PREALLOC);
10414 btrfs_free_reserved_extent(fs_info, ins.objectid,
10416 btrfs_abort_transaction(trans, ret);
10418 btrfs_end_transaction(trans);
10422 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10423 cur_offset + ins.offset -1, 0);
10425 em = alloc_extent_map();
10427 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10428 &BTRFS_I(inode)->runtime_flags);
10432 em->start = cur_offset;
10433 em->orig_start = cur_offset;
10434 em->len = ins.offset;
10435 em->block_start = ins.objectid;
10436 em->block_len = ins.offset;
10437 em->orig_block_len = ins.offset;
10438 em->ram_bytes = ins.offset;
10439 em->bdev = fs_info->fs_devices->latest_bdev;
10440 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10441 em->generation = trans->transid;
10444 write_lock(&em_tree->lock);
10445 ret = add_extent_mapping(em_tree, em, 1);
10446 write_unlock(&em_tree->lock);
10447 if (ret != -EEXIST)
10449 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10450 cur_offset + ins.offset - 1,
10453 free_extent_map(em);
10455 num_bytes -= ins.offset;
10456 cur_offset += ins.offset;
10457 *alloc_hint = ins.objectid + ins.offset;
10459 inode_inc_iversion(inode);
10460 inode->i_ctime = current_time(inode);
10461 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10462 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10463 (actual_len > inode->i_size) &&
10464 (cur_offset > inode->i_size)) {
10465 if (cur_offset > actual_len)
10466 i_size = actual_len;
10468 i_size = cur_offset;
10469 i_size_write(inode, i_size);
10470 btrfs_ordered_update_i_size(inode, i_size, NULL);
10473 ret = btrfs_update_inode(trans, root, inode);
10476 btrfs_abort_transaction(trans, ret);
10478 btrfs_end_transaction(trans);
10483 btrfs_end_transaction(trans);
10485 if (cur_offset < end)
10486 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10487 end - cur_offset + 1);
10491 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10492 u64 start, u64 num_bytes, u64 min_size,
10493 loff_t actual_len, u64 *alloc_hint)
10495 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10496 min_size, actual_len, alloc_hint,
10500 int btrfs_prealloc_file_range_trans(struct inode *inode,
10501 struct btrfs_trans_handle *trans, int mode,
10502 u64 start, u64 num_bytes, u64 min_size,
10503 loff_t actual_len, u64 *alloc_hint)
10505 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10506 min_size, actual_len, alloc_hint, trans);
10509 static int btrfs_set_page_dirty(struct page *page)
10511 return __set_page_dirty_nobuffers(page);
10514 static int btrfs_permission(struct inode *inode, int mask)
10516 struct btrfs_root *root = BTRFS_I(inode)->root;
10517 umode_t mode = inode->i_mode;
10519 if (mask & MAY_WRITE &&
10520 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10521 if (btrfs_root_readonly(root))
10523 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10526 return generic_permission(inode, mask);
10529 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10531 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10532 struct btrfs_trans_handle *trans;
10533 struct btrfs_root *root = BTRFS_I(dir)->root;
10534 struct inode *inode = NULL;
10540 * 5 units required for adding orphan entry
10542 trans = btrfs_start_transaction(root, 5);
10544 return PTR_ERR(trans);
10546 ret = btrfs_find_free_ino(root, &objectid);
10550 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10551 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10552 if (IS_ERR(inode)) {
10553 ret = PTR_ERR(inode);
10558 inode->i_fop = &btrfs_file_operations;
10559 inode->i_op = &btrfs_file_inode_operations;
10561 inode->i_mapping->a_ops = &btrfs_aops;
10562 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10564 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10568 ret = btrfs_update_inode(trans, root, inode);
10571 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10576 * We set number of links to 0 in btrfs_new_inode(), and here we set
10577 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10580 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10582 set_nlink(inode, 1);
10583 d_tmpfile(dentry, inode);
10584 unlock_new_inode(inode);
10585 mark_inode_dirty(inode);
10587 btrfs_end_transaction(trans);
10589 discard_new_inode(inode);
10590 btrfs_btree_balance_dirty(fs_info);
10594 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10596 struct inode *inode = tree->private_data;
10597 unsigned long index = start >> PAGE_SHIFT;
10598 unsigned long end_index = end >> PAGE_SHIFT;
10601 while (index <= end_index) {
10602 page = find_get_page(inode->i_mapping, index);
10603 ASSERT(page); /* Pages should be in the extent_io_tree */
10604 set_page_writeback(page);
10612 * Add an entry indicating a block group or device which is pinned by a
10613 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10614 * negative errno on failure.
10616 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10617 bool is_block_group)
10619 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10620 struct btrfs_swapfile_pin *sp, *entry;
10621 struct rb_node **p;
10622 struct rb_node *parent = NULL;
10624 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10629 sp->is_block_group = is_block_group;
10631 spin_lock(&fs_info->swapfile_pins_lock);
10632 p = &fs_info->swapfile_pins.rb_node;
10635 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10636 if (sp->ptr < entry->ptr ||
10637 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10638 p = &(*p)->rb_left;
10639 } else if (sp->ptr > entry->ptr ||
10640 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10641 p = &(*p)->rb_right;
10643 spin_unlock(&fs_info->swapfile_pins_lock);
10648 rb_link_node(&sp->node, parent, p);
10649 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10650 spin_unlock(&fs_info->swapfile_pins_lock);
10654 /* Free all of the entries pinned by this swapfile. */
10655 static void btrfs_free_swapfile_pins(struct inode *inode)
10657 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10658 struct btrfs_swapfile_pin *sp;
10659 struct rb_node *node, *next;
10661 spin_lock(&fs_info->swapfile_pins_lock);
10662 node = rb_first(&fs_info->swapfile_pins);
10664 next = rb_next(node);
10665 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10666 if (sp->inode == inode) {
10667 rb_erase(&sp->node, &fs_info->swapfile_pins);
10668 if (sp->is_block_group)
10669 btrfs_put_block_group(sp->ptr);
10674 spin_unlock(&fs_info->swapfile_pins_lock);
10677 struct btrfs_swap_info {
10683 unsigned long nr_pages;
10687 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10688 struct btrfs_swap_info *bsi)
10690 unsigned long nr_pages;
10691 u64 first_ppage, first_ppage_reported, next_ppage;
10694 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10695 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10696 PAGE_SIZE) >> PAGE_SHIFT;
10698 if (first_ppage >= next_ppage)
10700 nr_pages = next_ppage - first_ppage;
10702 first_ppage_reported = first_ppage;
10703 if (bsi->start == 0)
10704 first_ppage_reported++;
10705 if (bsi->lowest_ppage > first_ppage_reported)
10706 bsi->lowest_ppage = first_ppage_reported;
10707 if (bsi->highest_ppage < (next_ppage - 1))
10708 bsi->highest_ppage = next_ppage - 1;
10710 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10713 bsi->nr_extents += ret;
10714 bsi->nr_pages += nr_pages;
10718 static void btrfs_swap_deactivate(struct file *file)
10720 struct inode *inode = file_inode(file);
10722 btrfs_free_swapfile_pins(inode);
10723 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10726 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10729 struct inode *inode = file_inode(file);
10730 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10731 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10732 struct extent_state *cached_state = NULL;
10733 struct extent_map *em = NULL;
10734 struct btrfs_device *device = NULL;
10735 struct btrfs_swap_info bsi = {
10736 .lowest_ppage = (sector_t)-1ULL,
10743 * If the swap file was just created, make sure delalloc is done. If the
10744 * file changes again after this, the user is doing something stupid and
10745 * we don't really care.
10747 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10752 * The inode is locked, so these flags won't change after we check them.
10754 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10755 btrfs_warn(fs_info, "swapfile must not be compressed");
10758 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10759 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10762 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10763 btrfs_warn(fs_info, "swapfile must not be checksummed");
10768 * Balance or device remove/replace/resize can move stuff around from
10769 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10770 * concurrently while we are mapping the swap extents, and
10771 * fs_info->swapfile_pins prevents them from running while the swap file
10772 * is active and moving the extents. Note that this also prevents a
10773 * concurrent device add which isn't actually necessary, but it's not
10774 * really worth the trouble to allow it.
10776 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10777 btrfs_warn(fs_info,
10778 "cannot activate swapfile while exclusive operation is running");
10782 * Snapshots can create extents which require COW even if NODATACOW is
10783 * set. We use this counter to prevent snapshots. We must increment it
10784 * before walking the extents because we don't want a concurrent
10785 * snapshot to run after we've already checked the extents.
10787 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10789 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10791 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10793 while (start < isize) {
10794 u64 logical_block_start, physical_block_start;
10795 struct btrfs_block_group_cache *bg;
10796 u64 len = isize - start;
10798 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10804 if (em->block_start == EXTENT_MAP_HOLE) {
10805 btrfs_warn(fs_info, "swapfile must not have holes");
10809 if (em->block_start == EXTENT_MAP_INLINE) {
10811 * It's unlikely we'll ever actually find ourselves
10812 * here, as a file small enough to fit inline won't be
10813 * big enough to store more than the swap header, but in
10814 * case something changes in the future, let's catch it
10815 * here rather than later.
10817 btrfs_warn(fs_info, "swapfile must not be inline");
10821 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10822 btrfs_warn(fs_info, "swapfile must not be compressed");
10827 logical_block_start = em->block_start + (start - em->start);
10828 len = min(len, em->len - (start - em->start));
10829 free_extent_map(em);
10832 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10838 btrfs_warn(fs_info,
10839 "swapfile must not be copy-on-write");
10844 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10850 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10851 btrfs_warn(fs_info,
10852 "swapfile must have single data profile");
10857 if (device == NULL) {
10858 device = em->map_lookup->stripes[0].dev;
10859 ret = btrfs_add_swapfile_pin(inode, device, false);
10864 } else if (device != em->map_lookup->stripes[0].dev) {
10865 btrfs_warn(fs_info, "swapfile must be on one device");
10870 physical_block_start = (em->map_lookup->stripes[0].physical +
10871 (logical_block_start - em->start));
10872 len = min(len, em->len - (logical_block_start - em->start));
10873 free_extent_map(em);
10876 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10878 btrfs_warn(fs_info,
10879 "could not find block group containing swapfile");
10884 ret = btrfs_add_swapfile_pin(inode, bg, true);
10886 btrfs_put_block_group(bg);
10893 if (bsi.block_len &&
10894 bsi.block_start + bsi.block_len == physical_block_start) {
10895 bsi.block_len += len;
10897 if (bsi.block_len) {
10898 ret = btrfs_add_swap_extent(sis, &bsi);
10903 bsi.block_start = physical_block_start;
10904 bsi.block_len = len;
10911 ret = btrfs_add_swap_extent(sis, &bsi);
10914 if (!IS_ERR_OR_NULL(em))
10915 free_extent_map(em);
10917 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10920 btrfs_swap_deactivate(file);
10922 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10928 sis->bdev = device->bdev;
10929 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10930 sis->max = bsi.nr_pages;
10931 sis->pages = bsi.nr_pages - 1;
10932 sis->highest_bit = bsi.nr_pages - 1;
10933 return bsi.nr_extents;
10936 static void btrfs_swap_deactivate(struct file *file)
10940 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10943 return -EOPNOTSUPP;
10947 static const struct inode_operations btrfs_dir_inode_operations = {
10948 .getattr = btrfs_getattr,
10949 .lookup = btrfs_lookup,
10950 .create = btrfs_create,
10951 .unlink = btrfs_unlink,
10952 .link = btrfs_link,
10953 .mkdir = btrfs_mkdir,
10954 .rmdir = btrfs_rmdir,
10955 .rename = btrfs_rename2,
10956 .symlink = btrfs_symlink,
10957 .setattr = btrfs_setattr,
10958 .mknod = btrfs_mknod,
10959 .listxattr = btrfs_listxattr,
10960 .permission = btrfs_permission,
10961 .get_acl = btrfs_get_acl,
10962 .set_acl = btrfs_set_acl,
10963 .update_time = btrfs_update_time,
10964 .tmpfile = btrfs_tmpfile,
10966 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10967 .lookup = btrfs_lookup,
10968 .permission = btrfs_permission,
10969 .update_time = btrfs_update_time,
10972 static const struct file_operations btrfs_dir_file_operations = {
10973 .llseek = generic_file_llseek,
10974 .read = generic_read_dir,
10975 .iterate_shared = btrfs_real_readdir,
10976 .open = btrfs_opendir,
10977 .unlocked_ioctl = btrfs_ioctl,
10978 #ifdef CONFIG_COMPAT
10979 .compat_ioctl = btrfs_compat_ioctl,
10981 .release = btrfs_release_file,
10982 .fsync = btrfs_sync_file,
10985 static const struct extent_io_ops btrfs_extent_io_ops = {
10986 /* mandatory callbacks */
10987 .submit_bio_hook = btrfs_submit_bio_hook,
10988 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10992 * btrfs doesn't support the bmap operation because swapfiles
10993 * use bmap to make a mapping of extents in the file. They assume
10994 * these extents won't change over the life of the file and they
10995 * use the bmap result to do IO directly to the drive.
10997 * the btrfs bmap call would return logical addresses that aren't
10998 * suitable for IO and they also will change frequently as COW
10999 * operations happen. So, swapfile + btrfs == corruption.
11001 * For now we're avoiding this by dropping bmap.
11003 static const struct address_space_operations btrfs_aops = {
11004 .readpage = btrfs_readpage,
11005 .writepage = btrfs_writepage,
11006 .writepages = btrfs_writepages,
11007 .readpages = btrfs_readpages,
11008 .direct_IO = btrfs_direct_IO,
11009 .invalidatepage = btrfs_invalidatepage,
11010 .releasepage = btrfs_releasepage,
11011 .set_page_dirty = btrfs_set_page_dirty,
11012 .error_remove_page = generic_error_remove_page,
11013 .swap_activate = btrfs_swap_activate,
11014 .swap_deactivate = btrfs_swap_deactivate,
11017 static const struct inode_operations btrfs_file_inode_operations = {
11018 .getattr = btrfs_getattr,
11019 .setattr = btrfs_setattr,
11020 .listxattr = btrfs_listxattr,
11021 .permission = btrfs_permission,
11022 .fiemap = btrfs_fiemap,
11023 .get_acl = btrfs_get_acl,
11024 .set_acl = btrfs_set_acl,
11025 .update_time = btrfs_update_time,
11027 static const struct inode_operations btrfs_special_inode_operations = {
11028 .getattr = btrfs_getattr,
11029 .setattr = btrfs_setattr,
11030 .permission = btrfs_permission,
11031 .listxattr = btrfs_listxattr,
11032 .get_acl = btrfs_get_acl,
11033 .set_acl = btrfs_set_acl,
11034 .update_time = btrfs_update_time,
11036 static const struct inode_operations btrfs_symlink_inode_operations = {
11037 .get_link = page_get_link,
11038 .getattr = btrfs_getattr,
11039 .setattr = btrfs_setattr,
11040 .permission = btrfs_permission,
11041 .listxattr = btrfs_listxattr,
11042 .update_time = btrfs_update_time,
11045 const struct dentry_operations btrfs_dentry_operations = {
11046 .d_delete = btrfs_dentry_delete,